Programs & Examples On #Mmc3

How to set back button text in Swift

Back-button text is taken from parent view-controller's navigation item title. So whatever you set on previous view-controller's navigation item title, will be shown on current view controller's back button text. You can just put "" as navigation item title in parent view-controller's viewWillAppear method.

self.navigationItem.title = ""

Another way is to put

self.navigationController?.navigationBar.topItem?.title = ""

in current view controller's viewWillAppear method. This one will cause some other problem if navigation stack is too nested.

Auto-size dynamic text to fill fixed size container

The proposed iterative solutions can be sped up dramatically on two fronts:

1) Multiply the font size by some constant, rather than adding or subtracting 1.

2) First, zero in using a course constant, say, double the size each loop. Then, with a rough idea of where to start, do the same thing with a finer adjustment, say, multiply by 1.1. While the perfectionist might want the exact integer pixel size of the ideal font, most observers don't notice the difference between 100 and 110 pixels. If you are a perfectionist, then repeat a third time with an even finer adjustment.

Rather than writing a specific routine or plug-in that answers the exact question, I just rely on the basic ideas and write variations of the code to handle all kinds of layout issues, not just text, including fitting divs, spans, images,... by width, height, area,... within a container, matching another element....

Here's an example:

  var                           nWindowH_px             = jQuery(window).height();
  var                           nWas                    = 0;
  var                           nTry                    = 5;

  do{
   nWas = nTry;
   nTry *= 2;
   jQuery('#divTitle').css('font-size' ,nTry +'px');
  }while( jQuery('#divTitle').height() < nWindowH_px );

  nTry = nWas;

  do{
   nWas = nTry;
   nTry = Math.floor( nTry * 1.1 );
   jQuery('#divTitle').css('font-size' ,nTry +'px');
  }while( nWas != nTry   &&   jQuery('#divTitle').height() < nWindowH_px );

  jQuery('#divTitle').css('font-size' ,nWas +'px');

How do I set adaptive multiline UILabel text?

With Graphical User Interface (GUI) in Xcode, you can do the following:

  • Go to "Attribute Inspector" and set Lines value to 0. By default, it is set to 1.
  • The Label text can be written in multi-line by hitting option + return.

enter image description here

  • Now, go to "Size Inspector" and set the width, height, X & Y position of the Label.

enter image description here

That's all.

How to get a user's client IP address in ASP.NET?

use this

Dns.GetHostEntry(Dns.GetHostName())

Access to the path denied error in C#

Did you try specifing some file name?

eg:

string route="D:\\somefilename.txt";

Press TAB and then ENTER key in Selenium WebDriver

In javascript (node.js) this works for me:

describe('UI', function() {

describe('gets results from Bing', function() {
    this.timeout(10000);

    it('makes a search', function(done) {
        var driver = new webdriver.Builder().
        withCapabilities(webdriver.Capabilities.chrome()).
        build();


        driver.get('http://bing.com');
        var input = driver.findElement(webdriver.By.name('q'));
        input.sendKeys('something');
        input.sendKeys(webdriver.Key.ENTER);

        driver.wait(function() {
            driver.findElement(webdriver.By.className('sb_count')).
                getText().
                then(function(result) {
                  console.log('result: ', result);
                  done();
            });
        }, 8000);


    });
  });
});

For tab use webdriver.Key.TAB

How can I put a database under git (version control)?

Faced similar need and here is what my research on database version control systems threw up:

  1. Sqitch - perl based open source; available for all major databases including PostgreSQL https://github.com/sqitchers/sqitch
  2. Mahout - only for PostgreSQL; open source database schema version control. https://github.com/cbbrowne/mahout
  3. Liquibase - another open source db version control sw. free version of Datical. http://www.liquibase.org/index.html
  4. Datical - commercial version of Liquibase - https://www.datical.com/
  5. Flyway by BoxFuse - commercial sw. https://flywaydb.org/
  6. Another open source project https://gitlab.com/depesz/Versioning Author provides a guide here: https://www.depesz.com/2010/08/22/versioning/
  7. Red Gate Change Automation - only for SQL Server. https://www.red-gate.com/products/sql-development/sql-change-automation/

How to generate random float number in C

while it might not matter now here is a function which generate a float between 2 values.

#include <math.h>

float func_Uniform(float left, float right) {
    float randomNumber = sin(rand() * rand());
    return left + (right - left) * fabs(randomNumber);
}

key_load_public: invalid format

Instead of directly saving the private key Go to Conversions and Export SSh Key. Had the same issue and this worked for me

Swap DIV position with CSS only

In some cases you can just use the flex-box property order.

Very simple:

.flex-item {
    order: 2;
}

See: https://css-tricks.com/almanac/properties/o/order/

Copy file(s) from one project to another using post build event...VS2010

xcopy "$(ProjectDir)Views\Home\Index.cshtml" "$(SolutionDir)MEFMVCPOC\Views\Home"

and if you want to copy entire folders:

xcopy /E /Y "$(ProjectDir)Views" "$(SolutionDir)MEFMVCPOC\Views"

Update: here's the working version

xcopy "$(ProjectDir)Views\ModuleAHome\Index.cshtml" "$(SolutionDir)MEFMVCPOC\Views\ModuleAHome\" /Y /I

Here are some commonly used switches with xcopy:

  • /I - treat as a directory if copying multiple files.
  • /Q - Do not display the files being copied.
  • /S - Copy subdirectories unless empty.
  • /E - Copy empty subdirectories.
  • /Y - Do not prompt for overwrite of existing files.
  • /R - Overwrite read-only files.

Remove all padding and margin table HTML and CSS

Remove padding between cells inside the table. Just use cellpadding=0 and cellspacing=0 attributes in table tag.

Selecting the first "n" items with jQuery

I found this note in the end of the lt() docs:

Additional Notes:
Because :lt() is a jQuery extension and not part of the CSS specification, queries using :lt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").slice(0, index) instead.

So use $("selector").slice(from, to) for better performances.

How to use refs in React with Typescript

One way (which I've been doing) is to setup manually :

refs: {
    [string: string]: any;
    stepInput:any;
}

then you can even wrap this up in a nicer getter function (e.g. here):

stepInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.stepInput);

iOS 7 status bar overlapping UI

What I usually do is add two key-value properties to the Info.plist file.

enter image description here

The properties source code is:

enter image description here

Using different Web.config in development and production environment

You could also make it a post-build step. Setup a new configuration which is "Deploy" in addition to Debug and Release, and then have the post-build step copy over the correct web.config.

We use automated builds for all of our projects, and with those the build script updates the web.config file to point to the correct location. But that won't help you if you are doing everything from VS.

Update Tkinter Label from variable

The window is only displayed once the mainloop is entered. So you won't see any changes you make in your while True block preceding the line root.mainloop().


GUI interfaces work by reacting to events while in the mainloop. Here's an example where the StringVar is also connected to an Entry widget. When you change the text in the Entry widget it automatically changes in the Label.

from tkinter import *

root = Tk()
var = StringVar()
var.set('hello')

l = Label(root, textvariable = var)
l.pack()

t = Entry(root, textvariable = var)
t.pack()

root.mainloop() # the window is now displayed

I like the following reference: tkinter 8.5 reference: a GUI for Python


Here is a working example of what you were trying to do:

from tkinter import *
from time import sleep

root = Tk()
var = StringVar()
var.set('hello')

l = Label(root, textvariable = var)
l.pack()

for i in range(6):
    sleep(1) # Need this to slow the changes down
    var.set('goodbye' if i%2 else 'hello')
    root.update_idletasks()

root.update Enter event loop until all pending events have been processed by Tcl.

Eclipse returns error message "Java was started but returned exit code = 1"

I received this error out of the blue. Eclipse stopped working even though I made no config changes and did not install any new jdk's.

Here was my eclipse.ini file :

--clean
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20130807-1835
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vm
C:/Program Files (x86)/Java/jre7/bin/javaw.exe
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms40m
-Xmx1024m

To get Eclipse to start successfully I removed

    -vmargs
    -Dosgi.requiredJavaVersion=1.6
    -vm 
C:/Program Files (x86)/Java/jre7/bin/javaw.exe

So here is my updated file :

--clean
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20130807-1835
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-Xms40m
-Xmx1024m

I have no idea why removing osgi.requiredJavaVersion=1.6 fixed this as my jvm version is 1.6. From the doc http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fruntime-options.html

osgi.requiredJavaVersion
The minimum java version that is required to launch Eclipse. The default value is "1.4.1".

I think my java version was set correctly. Anyway Eclipse starts and runs for me now......

How can I clear event subscriptions in C#?

You can achieve this by using the Delegate.Remove or Delegate.RemoveAll methods.

Lambda expression to convert array/List of String to array/List of Integers

You can also use,

List<String> list = new ArrayList<>();
    list.add("1");
    list.add("2");
    list.add("3");

    Integer[] array = list.stream()
        .map( v -> Integer.valueOf(v))
        .toArray(Integer[]::new);

How to generate a range of numbers between two numbers?

CREATE OR ALTER  FUNCTION [dbo].[_ICAN_TF_Nums2](@a INT, @b INT)
-------------------------------------------------------------------------------------------------------------------
--INVENTIVE:Keyvan ARYAEE-MOEEN
-------------------------------------------------------------------------------------------------------------------
RETURNS @_ICAN_TF_Nums2 TABLE
(
    num int
)
AS
BEGIN
------------------------------------------------------------------------------------------------------------------
WITH nums AS
   (SELECT @a AS value
    UNION ALL
    SELECT value + 1 AS value
    FROM nums
    WHERE nums.value < @b)
INSERT @_ICAN_TF_Nums2
SELECT *
FROM nums
ORDER BY 1
option ( MaxRecursion 0 );
RETURN
END
-------------------------------------------------------------------------------------------------------------------
-- SELECT * FROM dbo._ICAN_TF_Nums2(1000, 1050)
-------------------------------------------------------------------------------------------------------------------

Create SQL identity as primary key?

If you're using T-SQL, the only thing wrong with your code is that you used braces {} instead of parentheses ().

PS: Both IDENTITY and PRIMARY KEY imply NOT NULL, so you can omit that if you wish.

MySQL GROUP BY two columns

Using Concat on the group by will work

SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
FROM clients, portfolios
WHERE clients.id = portfolios.client_id
GROUP BY CONCAT(portfolios.id, "-", clients.id)
ORDER BY total DESC
LIMIT 30

Android-Studio upgraded from 0.1.9 to 0.2.0 causing gradle build errors now

For people who have this problem today(to example to switch from 2.8.0 to 2.10.0), move to file gradle-wrapper.properties and set distributionUrl with the value you need. distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

I changed 2.8.0 to 2.10.0 and dont forget to Sync after

Python argparse command line flags without arguments

Your script is right. But by default is of None type. So it considers true of any other value other than None is assigned to args.argument_name variable.

I would suggest you to add a action="store_true". This would make the True/False type of flag. If used its True else False.

import argparse
parser = argparse.ArgumentParser('parser-name')
parser.add_argument("-f","--flag",action="store_true",help="just a flag argument")

usage

$ python3 script.py -f

After parsing when checked with args.f it returns true,

args = parser.parse_args()
print(args.f)
>>>true

After installing SQL Server 2014 Express can't find local db

I faced the same issue. Just download and install the SQL Server suite from the following link :http://www.microsoft.com/en-US/download/details.aspx?id=42299

restart your SSMS and you should be able to "Register Local Servers" via right-click on "Local Servers Groups", select "tasks", click "register local servers"

ZIP Code (US Postal Code) validation

Drupal 7 also has an easy solution here, this will allow you to validate against multiple countries.

https://drupal.org/project/postal_code_validation

You will need this module as well
https://drupal.org/project/postal_code

Test it in http://simplytest.me/

"OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)

Tried a combination of some answers and this eventually worked:

sudo -H pip install --upgrade --ignore-installed awsebcli

Cheers

Set value of textbox using JQuery

1) you are calling it wrong way try:

$(input[name="searchBar"]).val('hi')

2) if it doesn't work call your .js file at the end of the page or trigger your function on document.ready event

$(document).ready(function() {
  $(input[name="searchBar"]).val('hi');
});

How is attr_accessible used in Rails 4?

An update for Rails 5:

gem 'protected_attributes' 

doesn't seem to work anymore. But give:

gem 'protected_attributes_continued'

a try.

sql query to return differences between two tables

You can use except , for example something like this :

-- DB1..Tb1 have values than DB2..Tb1 not have
Select Col1,Col2,Col3 From DB1..Tb1
except
Select Col1,Col2,Col3 From DB2..Tb1
-- Now we change order
-- DB2..Tb1 have values than DB1..Tb1 not have
Select Col1,Col2,Col3 From DB2..Tb1
except
Select Col1,Col2,Col3 From DB1..Tb1

phpMyAdmin - The MySQL Extension is Missing

I just add

apt-get install php5-mysqlnd

This will ask to overwrite mysql.so from "php5-mysql".

This work for me.

JQuery to load Javascript file dynamically

Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.

You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:

$('#add_comment').click(function() {
    if(typeof TinyMCE == "undefined") {
        $.getScript('tinymce.js', function() {
            TinyMCE.init();
        });
    }
});

Assuming you only have to call init on it once, that is. If not, you can figure it out from here :)

Bulk package updates using Conda

the Conda Package Manager is almost ready for beta testing, but it will not be fully integrated until the release of Spyder 2.4 (https://github.com/spyder-ide/spyder/wiki/Roadmap). As soon as we have it ready for testing we will post something on the mailing list (https://groups.google.com/forum/#!forum/spyderlib). Be sure to subscribe

Cheers!

Setting environment variable in react-native?

you can also have different env scripts: production.env.sh development.env.sh production.env.sh

And then source them in when starting to work [which is just tied to an alias] so all the sh file has is export for each env variable:

export SOME_VAR=1234
export SOME_OTHER=abc

And then adding babel-plugin-transform-inline-environment-variables will allow access them in the code:

export const SOME_VAR: ?string = process.env.SOME_VAR;
export const SOME_OTHER: ?string = process.env.SOME_OTHER;

show/hide html table columns using css

One line of code using jQuery:

$('td:nth-child(2)').hide();

// If your table has header(th), use this:
//$('td:nth-child(2),th:nth-child(2)').hide();

Source: Hide a Table Column with a Single line of jQuery code

Appending values to dictionary in Python

how do i append a number into the drug_dictionary?

Do you wish to add "a number" or a set of values?

I use dictionaries to build associative arrays and lookup tables quite a bit.

Since python is so good at handling strings, I often use a string and add the values into a dict as a comma separated string

drug_dictionary = {} 

drug_dictionary={'MORPHINE':'',
         'OXYCODONE':'',
         'OXYMORPHONE':'',
         'METHADONE':'',
         'BUPRENORPHINE':'',
         'HYDROMORPHONE':'',
         'CODEINE':'',
         'HYDROCODONE':''}


drug_to_update = 'MORPHINE'

try: 
   oldvalue = drug_dictionary[drug_to_update] 
except: 
   oldvalue = ''

# to increment a value

   try: 
      newval = int(oldval) 
      newval += 1
   except: 
      newval = 1 


   drug_dictionary[drug_to_update] = "%s" % newval

# to append a value  

   try: 
      newval = int(oldval) 
      newval += 1
   except: 
      newval = 1 


   drug_dictionary[drug_to_update] = "%s,%s" % (oldval,newval) 

The Append method allows for storing a list of values but leaves you will a trailing comma

which you can remove with

drug_dictionary[drug_to_update][:-1]

the result of the appending the values as a string means that you can append lists of values as you need too and

print "'%s':'%s'" % ( drug_to_update, drug_dictionary[drug_to_update]) 

can return

'MORPHINE':'10,5,7,42,12,'

How to redirect single url in nginx?

location ~ /issue([0-9]+) {
    return 301 http://example.com/shop/issues/custom_isse_name$1;
}

javascript onclick increment number

For those who do NOT want an input box, here's a ready-to-compile example you can check out, which just counts the button clicks, updates them in the text and toggles the font. You could take the value and use it anywhere you see fit.

<!DOCTYPE html>
<html>


<body>
<p id="demo">JavaScript can change the style of an HTML element.</p>

<script>
   function incrementValue()
        {
            var demo_id = document.getElementById('demo')
            var value = parseInt(demo_id.value, 10);
            // if NaN, set to 0, else, keep the current value
            value = isNaN(value) ? 0 : value;
            value++;
            demo_id.value = value;

            if ((value%2)==0){
                demo_id.innerHTML = value;
                demo_id.style.fontSize = "25px"; 
                demo_id.style.color = "red";
                demo_id.style.backgroundColor = "yellow";   
            } 
            else {
                demo_id.innerHTML = value.toString() ;
                demo_id.style.fontSize = "15px"; 
                demo_id.style.color = "black";
                demo_id.style.backgroundColor = "white";
            }
        }
</script>

<form>
    <input type="button" onclick="incrementValue()" value="Increment Value" />
</form>
</body>


</html>

Check if my SSL Certificate is SHA1 or SHA2

I had to modify this slightly to be used on a Windows System. Here's the one-liner version for a windows box.

openssl.exe s_client -connect yoursitename.com:443 > CertInfo.txt && openssl x509 -text -in CertInfo.txt | find "Signature Algorithm" && del CertInfo.txt /F

Tested on Server 2012 R2 using http://iweb.dl.sourceforge.net/project/gnuwin32/openssl/0.9.8h-1/openssl-0.9.8h-1-bin.zip

find all subsets that sum to a particular value

Subset sum problem can be solved in O(sum*n) using dynamic programming. Optimal substructure for subset sum is as follows:

SubsetSum(A, n, sum) = SubsetSum(A, n-1, sum) || SubsetSum(A, n-1, sum-set[n-1])

SubsetSum(A, n, sum) = 0, if sum > 0 and n == 0 SubsetSum(A, n, sum) = 1, if sum == 0

Here A is array of elements, n is the number of elements of array A and sum is the sum of elements in the subset.

Using this dp, you can solve for the number of subsets for the sum.

For getting subset elements, we can use following algorithm:

After filling dp[n][sum] by calling SubsetSum(A, n, sum), we recursively traverse it from dp[n][sum]. For cell being traversed, we store path before reaching it and consider two possibilities for the element.

1) Element is included in current path.

2) Element is not included in current path.

Whenever sum becomes 0, we stop the recursive calls and print current path.

void findAllSubsets(int dp[], int A[], int i, int sum, vector<int>& p) { 

   if (sum == 0) { 
        print(p); 
        return; 
   } 

   // If sum can be formed without including current element
   if (dp[i-1][sum]) 
   { 
        // Create a new vector to store new subset 
        vector<int> b = p; 
        findAllSubsets(dp, A, i-1, sum, b); 
   } 

   // If given sum can be formed after including 
   // current element. 
   if (sum >= A[i] && dp[i-1][sum-A[i]]) 
   { 
        p.push_back(A[i]); 
        findAllSubsets(dp, A, i-1, sum-A[i], p); 
   } 

} 

How to set custom header in Volley Request

The accepted answer with getParams() is for setting POST body data, but the question in the title asked how to set HTTP headers like User-Agent. As CommonsWare said, you override getHeaders(). Here's some sample code which sets the User-Agent to 'Nintendo Gameboy' and Accept-Language to 'fr':

public void requestWithSomeHttpHeaders() {
    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "http://www.somewebsite.com";
    StringRequest getRequest = new StringRequest(Request.Method.GET, url, 
        new Response.Listener<String>() 
        {
            @Override
            public void onResponse(String response) {
                // response
                Log.d("Response", response);
            }
        }, 
        new Response.ErrorListener() 
        {
            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub
                Log.d("ERROR","error => "+error.toString());
            }
        }
    ) {     
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError { 
                Map<String, String>  params = new HashMap<String, String>();  
                params.put("User-Agent", "Nintendo Gameboy");  
                params.put("Accept-Language", "fr");

                return params;  
        }
    };
    queue.add(getRequest);

}

Get resultset from oracle stored procedure

In SQL Plus:

SQL> var r refcursor
SQL> set autoprint on
SQL> exec :r := function_returning_refcursor();

Replace the last line with a call to your procedure / function and the contents of the refcursor will be displayed

Android Endless List

You can detect end of the list with help of onScrollListener, working code is presented below:

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    if (view.getAdapter() != null && ((firstVisibleItem + visibleItemCount) >= totalItemCount) && totalItemCount != mPrevTotalItemCount) {
        Log.v(TAG, "onListEnd, extending list");
        mPrevTotalItemCount = totalItemCount;
        mAdapter.addMoreData();
    }
}

Another way to do that (inside adapter) is as following:

    public View getView(int pos, View v, ViewGroup p) {
            if(pos==getCount()-1){
                addMoreData(); //should be asynctask or thread
            }
            return view;
    }

Be aware that this method will be called many times, so you need to add another condition to block multiple calls of addMoreData().

When you add all elements to the list, please call notifyDataSetChanged() inside yours adapter to update the View (it should be run on UI thread - runOnUiThread)

Angular2 If ngModel is used within a form tag, either the name attribute must be set or the form

Try this...

<input type="text" class="form-control" name="name" placeholder="Name" required minlength="4" #name="ngModel" ngModel>
<div *ngIf="name.errors && (name.dirty || name.touched)">
    <div [hidden]="!name.errors.required" class="alert alert-danger form-alert">
        Please enter a name.
    </div>
    <div [hidden]="!name.errors.minlength" class="alert alert-danger form-alert">
        Enter name greater than 4 characters.
    </div>
</div>

Download image from the site in .NET/C#

There is no need to involve any image classes, you can simply call WebClient.DownloadFile:

string localFilename = @"c:\localpath\tofile.jpg";
using(WebClient client = new WebClient())
{
    client.DownloadFile("http://www.example.com/image.jpg", localFilename);
}

Update
Since you will want to check whether the file exists and download the file if it does, it's better to do this within the same request. So here is a method that will do that:

private static void DownloadRemoteImageFile(string uri, string fileName)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    // Check that the remote file was found. The ContentType
    // check is performed since a request for a non-existent
    // image file might be redirected to a 404-page, which would
    // yield the StatusCode "OK", even though the image was not
    // found.
    if ((response.StatusCode == HttpStatusCode.OK || 
        response.StatusCode == HttpStatusCode.Moved || 
        response.StatusCode == HttpStatusCode.Redirect) &&
        response.ContentType.StartsWith("image",StringComparison.OrdinalIgnoreCase))
    {

        // if the remote file was found, download oit
        using (Stream inputStream = response.GetResponseStream())
        using (Stream outputStream = File.OpenWrite(fileName))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            do
            {
                bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                outputStream.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);
        }
    }
}

In brief, it makes a request for the file, verifies that the response code is one of OK, Moved or Redirect and also that the ContentType is an image. If those conditions are true, the file is downloaded.

How to backup a local Git repository?

You can backup the git repo with git-copy . git-copy saved new project as a bare repo, it means minimum storage cost.

git copy /path/to/project /backup/project.backup

Then you can restore your project with git clone

git clone /backup/project.backup project

How to query a MS-Access Table from MS-Excel (2010) using VBA

Option Explicit

Const ConnectionStrngAccessPW As String = _"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\BARON\Desktop\Test_DB-PW.accdb;
Jet OLEDB:Database Password=123pass;"

Const ConnectionStrngAccess As String = _"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\BARON\Desktop\Test_DB.accdb;
Persist Security Info=False;"

'C:\Users\BARON\Desktop\Test.accdb

Sub ModifyingExistingDataOnAccessDB()

    Dim TableConn As ADODB.Connection
    Dim TableData As ADODB.Recordset


    Set TableConn = New ADODB.Connection
    Set TableData = New ADODB.Recordset

    TableConn.ConnectionString = ConnectionStrngAccess

    TableConn.Open

On Error GoTo CloseConnection

    With TableData
        .ActiveConnection = TableConn
        '.Source = "SELECT Emp_Age FROM Roster WHERE Emp_Age > 40;"
        .Source = "Roster"
        .LockType = adLockOptimistic
        .CursorType = adOpenForwardOnly
        .Open
        On Error GoTo CloseRecordset

            Do Until .EOF
                If .Fields("Emp_Age").Value > 40 Then
                    .Fields("Emp_Age").Value = 40
                    .Update
                End If
                .MoveNext
            Loop
            .MoveFirst

        MsgBox "Update Complete"
    End With


CloseRecordset:
    TableData.CancelUpdate
    TableData.Close

CloseConnection:
    TableConn.Close

    Set TableConn = Nothing
    Set TableData = Nothing

End Sub

Sub AddingDataToAccessDB()

    Dim TableConn As ADODB.Connection
    Dim TableData As ADODB.Recordset
    Dim r As Range

    Set TableConn = New ADODB.Connection
    Set TableData = New ADODB.Recordset

    TableConn.ConnectionString = ConnectionStrngAccess

    TableConn.Open

On Error GoTo CloseConnection

    With TableData
        .ActiveConnection = TableConn
        .Source = "Roster"
        .LockType = adLockOptimistic
        .CursorType = adOpenForwardOnly
        .Open
        On Error GoTo CloseRecordset

        Sheet3.Activate
        For Each r In Range("B3", Range("B3").End(xlDown))

            MsgBox "Adding " & r.Offset(0, 1)
            .AddNew
            .Fields("Emp_ID").Value = r.Offset(0, 0).Value
            .Fields("Emp_Name").Value = r.Offset(0, 1).Value
            .Fields("Emp_DOB").Value = r.Offset(0, 2).Value
            .Fields("Emp_SOD").Value = r.Offset(0, 3).Value
            .Fields("Emp_EOD").Value = r.Offset(0, 4).Value
            .Fields("Emp_Age").Value = r.Offset(0, 5).Value
            .Fields("Emp_Gender").Value = r.Offset(0, 6).Value
            .Update

        Next r

        MsgBox "Update Complete"
    End With


CloseRecordset:
    TableData.Close

CloseConnection:
    TableConn.Close

    Set TableConn = Nothing
    Set TableData = Nothing

End Sub

How do I include the string header?

You want to include <string> and use std::string:

#include <string>
#include <iostream>

int main()
{
    std::string s = "a string";
    std::cout << s << std::endl;
}

But what you really need to do is get an introductory level book. You aren't going to learn properly any other way, certainly not scrapping for information online.

Using openssl to get the certificate from a server

It turns out there is more complexity here: I needed to provide many more details to get this rolling. I think its something to do with the fact that its a connection that needs client authentication, and the hankshake needed more info to continue to the stage where the certificates were dumped.

Here is my working command:

openssl s_client -connect host:port -key our_private_key.pem -showcerts \
                 -cert our_server-signed_cert.pem

Hopefully this is a nudge in the right direction for anyone who could do with some more info.

VB.NET 'If' statement with 'Or' conditional has both sides evaluated?

It's your "fault" in that that's how Or is defined, so it's the behaviour you should expect:

In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. The OrElse Operator (Visual Basic) performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.

But you don't have to endure it. You can use OrElse to get short-circuiting behaviour.

So you probably want:

If (example Is Nothing OrElse Not example.Item = compare.Item) Then
    'Proceed
End If

I can't say it reads terribly nicely, but it should work...

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

If you have opened the command prompt(cmd) to run the jar on current folder,then the error will come as above.so close the command prompt and try maven clean and install,it will work definitely.

how to use LIKE with column name

ORACLE DATABASE example:

select * 
from table1 t1, table2 t2
WHERE t1.a like ('%' || t2.b || '%')

SQL LEFT JOIN Subquery Alias

You didn't select post_id in the subquery. You have to select it in the subquery like this:

SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM  wp_woocommerce_order_items
LEFT JOIN 
    (
        SELECT meta_value As Prenom, post_id  -- <----- this
        FROM wp_postmeta
        WHERE meta_key = '_shipping_first_name'
    ) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE  wp_woocommerce_order_items.order_id =2198 

How to show and update echo on same line

Well I did not read correctly the man echo page for this.

echo had 2 options that could do this if I added a 3rd escape character.

The 2 options are -n and -e.

-n will not output the trailing newline. So that saves me from going to a new line each time I echo something.

-e will allow me to interpret backslash escape symbols.

Guess what escape symbol I want to use for this: \r. Yes, carriage return would send me back to the start and it will visually look like I am updating on the same line.

So the echo line would look like this:

echo -ne "Movie $movies - $dir ADDED!"\\r

I had to escape the escape symbol so Bash would not kill it. that is why you see 2 \ symbols in there.

As mentioned by William, printf can also do similar (and even more extensive) tasks like this.

regular expression to validate datetime format (MM/DD/YYYY)

Try your regex with a tool like http://jsregex.com/ (There is many) or better, a unit test.

For a naive validation:

function validateDate(testdate) {
    var date_regex = /^\d{2}\/\d{2}\/\d{4}$/ ;
    return date_regex.test(testdate);
}

In your case, to validate (MM/DD/YYYY), with a year between 1900 and 2099, I'll write it like that:

function validateDate(testdate) {
    var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;
    return date_regex.test(testdate);
}

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

converting a javascript string to a html object

You cannot do it with just method, unless you use some javascript framework like jquery which supports it ..

string s = '<div id="myDiv"></div>'
var htmlObject = $(s); // jquery call

but still, it would not be found by the getElementById because for that to work the element must be in the DOM... just creating in the memory does not insert it in the dom.

You would need to use append or appendTo or after etc.. to put it in the dom first..

Of'course all these can be done through regular javascript but it would take more steps to accomplish the same thing... and the logic is the same in both cases..

Google Maps: how to get country, state/province/region, city given a lat/long value?

What you are looking for is called reverse geocoding. Google provides a server-side reverse geocoding service through the Google Geocoding API, which you should be able to use for your project.

This is how a response to the following request would look like:

http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false

Response:

{
  "status": "OK",
  "results": [ {
    "types": [ "street_address" ],
    "formatted_address": "275-291 Bedford Ave, Brooklyn, NY 11211, USA",
    "address_components": [ {
      "long_name": "275-291",
      "short_name": "275-291",
      "types": [ "street_number" ]
    }, {
      "long_name": "Bedford Ave",
      "short_name": "Bedford Ave",
      "types": [ "route" ]
    }, {
      "long_name": "New York",
      "short_name": "New York",
      "types": [ "locality", "political" ]
    }, {
      "long_name": "Brooklyn",
      "short_name": "Brooklyn",
      "types": [ "administrative_area_level_3", "political" ]
    }, {
      "long_name": "Kings",
      "short_name": "Kings",
      "types": [ "administrative_area_level_2", "political" ]
    }, {
      "long_name": "New York",
      "short_name": "NY",
      "types": [ "administrative_area_level_1", "political" ]
    }, {
      "long_name": "United States",
      "short_name": "US",
      "types": [ "country", "political" ]
    }, {
      "long_name": "11211",
      "short_name": "11211",
      "types": [ "postal_code" ]
    } ],
    "geometry": {
      "location": {
        "lat": 40.7142298,
        "lng": -73.9614669
      },
      "location_type": "RANGE_INTERPOLATED",
      "viewport": {
        "southwest": {
          "lat": 40.7110822,
          "lng": -73.9646145
        },
        "northeast": {
          "lat": 40.7173774,
          "lng": -73.9583193
        }
      }
    }
  },

  ... Additional results[] ...

You can also opt to receive the response in xml instead of json, by simply substituting json for xml in the request URI:

http://maps.googleapis.com/maps/api/geocode/xml?latlng=40.714224,-73.961452&sensor=false

As far as I know, Google will also return the same name for address components, especially for high-level names like country names and city names. Nevertheless, keep in mind that while the results are very accurate for most applications, you could still find the occasional spelling mistake or ambiguous result.

Tainted canvases may not be exported

For security reasons, your local drive is declared to be "other-domain" and will taint the canvas.

(That's because your most sensitive info is likely on your local drive!).

While testing try these workarounds:

  • Put all page related files (.html, .jpg, .js, .css, etc) on your desktop (not in sub-folders).

  • Post your images to a site that supports cross-domain sharing (like dropbox.com). Be sure you put your images in dropbox's public folder and also set the cross origin flag when downloading the image (var img=new Image(); img.crossOrigin="anonymous" ...)

  • Install a webserver on your development computer (IIS and PHP web servers both have free editions that work nicely on a local computer).

Error: macro names must be identifiers using #ifdef 0

The #ifdef directive is used to check if a preprocessor symbol is defined. The standard (C11 6.4.2 Identifiers) mandates that identifiers must not start with a digit:

identifier:
    identifier-nondigit
    identifier identifier-nondigit
    identifier digit
identifier-nondigit:
    nondigit
    universal-character-name
    other implementation-defined characters>
nondigit: one of
    _ a b c d e f g h i j k l m
    n o p q r s t u v w x y z
    A B C D E F G H I J K L M
    N O P Q R S T U V W X Y Z
digit: one of
    0 1 2 3 4 5 6 7 8 9

The correct form for using the pre-processor to block out code is:

#if 0
: : :
#endif

You can also use:

#ifdef NO_CHANCE_THAT_THIS_SYMBOL_WILL_EVER_EXIST
: : :
#endif

but you need to be confident that the symbols will not be inadvertently set by code other than your own. In other words, don't use something like NOTUSED or DONOTCOMPILE which others may also use. To be safe, the #if option should be preferred.

Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

The user jenkins needs to be added to the group docker:

sudo usermod -a -G docker jenkins

Then restart Jenkins.

Edit

If you arrive to this question of stack overflow because you receive this message from docker, but you don't use jenkins, most probably the error is the same: your unprivileged user does not belong to the docker group.

You can do:

sudo usermod -a -G docker alice

or whatever your username is.

You can check it at the end doing grep docker /etc/group and see something like this:

docker:x:998:alice

in one of the lines.

Then change your users group ID to docker:

newgrp docker

Finally, log out and log in again

How to print in C

try this:

printf("%d", addNumber(a,b))

Here's the documentation for printf.

What is pluginManagement in Maven's pom.xml?

The difference between <pluginManagement/> and <plugins/> is that a <plugin/> under:

  • <pluginManagement/> defines the settings for plugins that will be inherited by modules in your build. This is great for cases where you have a parent pom file.

  • <plugins/> is a section for the actual invocation of the plugins. It may or may not be inherited from a <pluginManagement/>.

You don't need to have a <pluginManagement/> in your project, if it's not a parent POM. However, if it's a parent pom, then in the child's pom, you need to have a declaration like:

<plugins>
    <plugin>
        <groupId>com.foo</groupId>
        <artifactId>bar-plugin</artifactId>
    </plugin>
</plugins>

Notice how you aren't defining any configuration. You can inherit it from the parent, unless you need to further adjust your invocation as per the child project's needs.

For more specific information, you can check:

List all kafka topics

to see that topic if we run the list topic command:

$ bin/kafka-topics.sh --list --zookeeper localhost:2181

To check if the data is landing in Kafka:

$ bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic twitterstream --from-beginning

Function that creates a timestamp in c#

If you want timestamps that correspond to actual real times BUT also want them to be unique (for a given application instance), you can use the following code:

public class HiResDateTime
{
   private static long lastTimeStamp = DateTime.UtcNow.Ticks;
   public static long UtcNowTicks
   {
       get
       {
           long orig, newval;
           do
           {
               orig = lastTimeStamp;
               long now = DateTime.UtcNow.Ticks;
               newval = Math.Max(now, orig + 1);
           } while (Interlocked.CompareExchange
                        (ref lastTimeStamp, newval, orig) != orig);

           return newval;
       }
   }
}

How to implement "Access-Control-Allow-Origin" header in asp.net

Another option is to add it on the web.config directly:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://www.yourSite.com" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
      </customHeaders>
    </httpProtocol>

... I found this in here

Difference between attr_accessor and attr_accessible

A quick & concise difference overview :

attr_accessor is an easy way to create read and write accessors in your class. It is used when you do not have a column in your database, but still want to show a field in your forms. This field is a “virtual attribute” in a Rails model.

virtual attribute – an attribute not corresponding to a column in the database.

attr_accessible is used to identify attributes that are accessible by your controller methods makes a property available for mass-assignment.. It will only allow access to the attributes that you specify, denying the rest.

How to get SLF4J "Hello World" working with log4j?

you need to add 3 dependency ( API+ API implementation + log4j dependency) 
Add also this 
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.5</version>
</dependency>

# And to see log in command line , set log4j.properties 

# Root logger option
log4j.rootLogger=INFO, file, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

#And to see log in file  , set log4j.properties 
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./logs/logging.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

AVD Manager - Cannot Create Android Virtual Device

Launching the AVD Manager from Visual Studio 2015 resolved this issue for me.

I had (a lot of packages) all the required packages installed but hadn't used them for some time & had issues detecting them in the SDK manager. I attempted all the solutions provided above to no avail, including running the AVD after running the monitor.bat file in 'android/sdk/tools'.

I then launched the AVD from VS in 'Tools->Android->Android Emulator Manager' and it detected both 'Google APIs Intel Atom x86' & the ARM EABI v7a system Images right off the bat!

Target is set to API Level 23.

Need to list all triggers in SQL Server database with table name and table's schema

C# Cribs: I ended up with this super generic one liner. Hope this is useful to both the original poster and/or people who just typed the same question I did into Google:

SELECT TriggerRecord.name as TriggerName,ParentRecord.name as ForTableName 
FROM sysobjects TriggerRecord 
INNER JOIN sysobjects ParentRecord ON TriggerRecord.parent_obj=ParentRecord.id 
WHERE TriggerRecord.xtype='TR'

Query Characteristics:

  • Usable with any SQL database (i.e. Initial Catalog)
  • Self explanatory
  • One single statement
  • Pasteable directly into most IDE's for most languages

Getting coordinates of marker in Google Maps API

One more alternative options

var map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 1,
    center: new google.maps.LatLng(35.137879, -82.836914),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

var myMarker = new google.maps.Marker({
    position: new google.maps.LatLng(47.651968, 9.478485),
    draggable: true
});

google.maps.event.addListener(myMarker, 'dragend', function (evt) {
    document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});

google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
    document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});

map.setCenter(myMarker.position);
myMarker.setMap(map);

and html file

<body>
    <section>
        <div id='map_canvas'></div>
        <div id="current">Nothing yet...</div>
    </section>
</body>

Passing html values into javascript functions

Simply put id attribute in your input text field -

<input type="text" maxlength="3" name="value" id="value" />

How to list npm user-installed packages?

npm ls

npm list is just an alias for npm ls

For the extended info use

npm la    
npm ll

You can always set --depth=0 at the end to get the first level deep.

npm ls --depth=0

You can check development and production packages.

npm ls --only=dev
npm ls --only=prod

To show the info in json format

npm ls --json=true

The default is false

npm ls --json=false

You can insist on long format to show extended information.

npm ls --long=true

You can show parseable output instead of tree view.

npm ls --parseable=true

You can list packages in the global install prefix instead of in the current project.

npm ls --global=true
npm ls -g // shorthand

Full documentation you can find here.

How do you get/set media volume (not ringtone volume) in Android?

The following code will set the media stream volume to max:

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
    audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
    AudioManager.FLAG_SHOW_UI);

Pandas: Looking up the list of sheets in an excel file

If you:

  • care about performance
  • don't need the data in the file at execution time.
  • want to go with conventional libraries vs rolling your own solution

Below was benchmarked on a ~10Mb xlsx, xlsb file.

xlsx, xls

from openpyxl import load_workbook

def get_sheetnames_xlsx(filepath):
    wb = load_workbook(filepath, read_only=True, keep_links=False)
    return wb.sheetnames

Benchmarks: ~ 14x speed improvement

# get_sheetnames_xlsx vs pd.read_excel
225 ms ± 6.21 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
3.25 s ± 140 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

xlsb

from pyxlsb import open_workbook

def get_sheetnames_xlsb(filepath):
  with open_workbook(filepath) as wb:
     return wb.sheets

Benchmarks: ~ 56x speed improvement

# get_sheetnames_xlsb vs pd.read_excel
96.4 ms ± 1.61 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
5.36 s ± 162 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Notes:

JavaScript window resize event

The resize event should never be used directly as it is fired continuously as we resize.

Use a debounce function to mitigate the excess calls.

window.addEventListener('resize',debounce(handler, delay, immediate),false);

Here's a common debounce floating around the net, though do look for more advanced ones as featuerd in lodash.

const debounce = (func, wait, immediate) => {
    var timeout;
    return () => {
        const context = this, args = arguments;
        const later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        const callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

This can be used like so...

window.addEventListener('resize', debounce(() => console.log('hello'),
200, false), false);

It will never fire more than once every 200ms.

For mobile orientation changes use:

window.addEventListener('orientationchange', () => console.log('hello'), false);

Here's a small library I put together to take care of this neatly.

How does DateTime.Now.Ticks exactly work?

to convert the current datetime to file name to save files you can use

DateTime.Now.ToFileTime();

this should resolve your objective

The HTTP request is unauthorized with client authentication scheme 'Ntlm' The authentication header received from the server was 'NTLM'

I had exactly the same issue last week - WCF program behaves strangely on one server - why?

For me the solution was rather simple. Sharepoint has its own set of permissions. My client tried to log on as a user that wasn't explicitly given access to the webservice through Sharepoint's administration panel.

I added the user to Sharepoint's whitelist and bang - it just worked.

Even if that isn't the issue, please note that

The HTTP request is unauthorized with client authentication scheme ‘Ntlm’. The authentication header received from the server was ‘NTLM’.

Means (in English) that you simply don't have permission. Your protocol is probably right - your user just doesn't have permissions.

Convert a PHP object to an associative array

You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:

$array = json_decode(json_encode($nested_object), true);

C++ inheritance - inaccessible base?

You have to do this:

class Bar : public Foo
{
    // ...
}

The default inheritance type of a class in C++ is private, so any public and protected members from the base class are limited to private. struct inheritance on the other hand is public by default.

How can I find the dimensions of a matrix in Python?

To get just a correct number of dimensions in NumPy:

len(a.shape)

In the first case:

import numpy as np
a = np.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
print("shape = ",np.shape(a))
print("dimensions = ",len(a.shape))

The output will be:

shape =  (2, 2, 3)
dimensions =  3

Get Application Name/ Label via ADB Shell or Terminal

If you know the app id of the package (like org.mozilla.firefox), it is easy. First to get the path of actual package file of the appId,

$  adb shell pm list packages -f com.google.android.apps.inbox
package:/data/app/com.google.android.apps.inbox-1/base.apk=com.google.android.apps.inbox

Now you can do some grep|sed magic to extract the path : /data/app/com.google.android.apps.inbox-1/base.apk

After that aapt tool comes in handy :

$  adb shell aapt dump badging /data/app/com.google.android.apps.inbox-1/base.apk
...
application-label:'Inbox'
application-label-hi:'Inbox'
application-label-ru:'Inbox'
...

Again some grep magic to get the Label.

Are there dictionaries in php?

No, there are no dictionaries in php. The closest thing you have is an array. However, an array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index. What do I mean by that?

$array = array(
    "foo" => "bar",
    "bar" => "foo"
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];

The following line is allowed with the above array but would give an error if it was a dictionary.

print $array[0]

Python has both arrays and dictionaries.

C# string reference type?

Above answers are helpful, I'd just like to add an example that I think is demonstrating clearly what happens when we pass parameter without the ref keyword, even when that parameter is a reference type:

MyClass c = new MyClass(); c.MyProperty = "foo";

CNull(c); // only a copy of the reference is sent 
Console.WriteLine(c.MyProperty); // still foo, we only made the copy null
CPropertyChange(c); 
Console.WriteLine(c.MyProperty); // bar


private void CNull(MyClass c2)
        {          
            c2 = null;
        }
private void CPropertyChange(MyClass c2) 
        {
            c2.MyProperty = "bar"; // c2 is a copy, but it refers to the same object that c does (on heap) and modified property would appear on c.MyProperty as well.
        }

How to force input to only allow Alpha Letters?

<input type="text" name="name" id="event" onkeydown="return alphaOnly(event);"   required />


function alphaOnly(event) {
  var key = event.keyCode;`enter code here`
  return ((key >= 65 && key <= 90) || key == 8);
};

Google Maps v3 - limit viewable area and zoom level

For some reason

if (strictBounds.contains(map.getCenter())) return;

didnt work for me (maybe a southern hemisphere issue). I had to change it to:

    function checkBounds() {
        var c = map.getCenter(),
            x = c.lng(),
            y = c.lat(),
            maxX = strictBounds.getNorthEast().lng(),
            maxY = strictBounds.getNorthEast().lat(),
            minX = strictBounds.getSouthWest().lng(),
            minY = strictBounds.getSouthWest().lat();

        if(x < minX || x > maxX || y < minY || y > maxY) {
            if (x < minX) x = minX;
            if (x > maxX) x = maxX;
            if (y < minY) y = minY;
            if (y > maxY) y = maxY;
            map.setCenter(new google.maps.LatLng(y, x));
        }
    }

Hope it will help someone.

How to get column values in one comma separated value

For Mysql:

SELECT t.user, 

(SELECT GROUP_CONCAT( t1.department ) FROM table_name t1 WHERE t1.user = t.user)department

FROM table_name t
GROUP BY t.user
LIMIT 0 , 30

Joining 2 SQL SELECT result sets into one

Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:

SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a

If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.

Large WCF web service request failing with (400) HTTP Bad Request

For what it is worth, an additional consideration when using .NET 4.0 is that if a valid endpoint is not found in your configuration, a default endpoint will be automatically created and used.

The default endpoint will use all default values so if you think you have a valid service configuration with a large value for maxReceivedMessageSize etc., but there is something wrong with the configuration, you would still get the 400 Bad Request since a default endpoint would be created and used.

This is done silently so it is hard to detect. You will see messages to this effect (e.g. 'No Endpoint found for Service, creating Default Endpoint' or similar) if you turn on tracing on the server but there is no other indication (to my knowledge).

Getting the screen resolution using PHP

Directly with PHP is not possible but...

I write this simple code to save screen resolution on a PHP session to use on a image gallery.

<?php
session_start();
if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
    echo 'User resolution: ' . $_SESSION['screen_width'] . 'x' . $_SESSION['screen_height'];
} else if(isset($_REQUEST['width']) AND isset($_REQUEST['height'])) {
    $_SESSION['screen_width'] = $_REQUEST['width'];
    $_SESSION['screen_height'] = $_REQUEST['height'];
    header('Location: ' . $_SERVER['PHP_SELF']);
} else {
    echo '<script type="text/javascript">window.location = "' . $_SERVER['PHP_SELF'] . '?width="+screen.width+"&height="+screen.height;</script>';
}
?>

Display array values in PHP

the join() function must work for you:

$array = array('apple','banana','ananas');
$string = join(',', $array);
echo $string;

Output :

apple,banana,ananas

Get connection status on Socket.io client

You can check the socket.connected property:

var socket = io.connect();
console.log('check 1', socket.connected);
socket.on('connect', function() {
  console.log('check 2', socket.connected);
});

It's updated dynamically, if the connection is lost it'll be set to false until the client picks up the connection again. So easy to check for with setInterval or something like that.

Another solution would be to catch disconnect events and track the status yourself.

Convert an integer to a float number

Type Conversions T() where T is the desired datatype of the result are quite simple in GoLang.

In my program, I scan an integer i from the user input, perform a type conversion on it and store it in the variable f. The output prints the float64 equivalent of the int input. float32 datatype is also available in GoLang

Code:

package main
import "fmt"
func main() {
    var i int
    fmt.Println("Enter an Integer input: ")
    fmt.Scanf("%d", &i)
    f := float64(i)
    fmt.Printf("The float64 representation of %d is %f\n", i, f)
}

Solution:

>>> Enter an Integer input:
>>> 232332
>>> The float64 representation of 232332 is 232332.000000

Save Screen (program) output to a file

You can also use Control-a + H to save loggings into screenlog.n file. One more Control-a + H to turn off.

C-a H: Begins/ends logging of the current window to the file "screenlog.n".

Div 100% height works on Firefox but not in IE

You might have to put one or both of:

html { height:100%; }

or

body { height:100%; }

EDIT: Whoops, didn't notice they were floated. You just need to float the container.

jquery to validate phone number

/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/

Supports :

  • (123) 456 7899
  • (123).456.7899
  • (123)-456-7899
  • 123-456-7899
  • 123 456 7899
  • 1234567899

Convert String to SecureString

no fancy linq, not adding all the chars by hand, just plain and simple:

var str = "foo";
var sc = new SecureString();
foreach(char c in str) sc.appendChar(c);

How to find out the location of currently used MySQL configuration file in linux

you can find it by running the following command

mysql --help

it will give you the mysql installed directory and all commands for mysql.

Java 8 Filter Array Using Lambda

Yes, you can do this by creating a DoubleStream from the array, filtering out the negatives, and converting the stream back to an array. Here is an example:

double[] d = {8, 7, -6, 5, -4};
d = Arrays.stream(d).filter(x -> x > 0).toArray();
//d => [8, 7, 5]

If you want to filter a reference array that is not an Object[] you will need to use the toArray method which takes an IntFunction to get an array of the original type as the result:

String[] a = { "s", "", "1", "", "" };
a = Arrays.stream(a).filter(s -> !s.isEmpty()).toArray(String[]::new);

How to use router.navigateByUrl and router.navigate in Angular

From my understanding, router.navigate is used to navigate relatively to current path. For eg : If our current path is abc.com/user, we want to navigate to the url : abc.com/user/10 for this scenario we can use router.navigate .


router.navigateByUrl() is used for absolute path navigation.

ie,

If we need to navigate to entirely different route in that case we can use router.navigateByUrl

For example if we need to navigate from abc.com/user to abc.com/assets, in this case we can use router.navigateByUrl()


Syntax :

router.navigateByUrl(' ---- String ----');

router.navigate([], {relativeTo: route})

Simple way to get element by id within a div tag?

In HTML ids should be unique. I suggest you change your code to something like this:

<div id="div1" >
    <input type="text" name="edit1" id="edit1" />
    <input type="text" name="edit2" id="edit2" />
</div>
<div id="div2" >
    <input type="text" name="edit1" id="edit3" />
    <input type="text" name="edit2" id="edit4" />
</div>

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

You have to add THEN

IF EXISTS(SELECT * FROM component_psar WHERE tbl_id = '2' AND row_nr = '1') 
THEN
UPDATE component_psar SET col_1 = '1', col_2 = '1', col_3 = '1', col_4 = '1', col_5 = '1', col_6 = '1', unit = '1', add_info = '1', fsar_lock = '1' WHERE tbl_id = '2' AND row_nr = '1' 
ELSE 
INSERT INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4, col_5, col_6, unit, add_info, fsar_lock) VALUES('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')

Set initial value in datepicker with jquery?

I'm not entirely sure if I understood your question, but it seems that you're trying to set value for an input type Date.

If you want to set a value for an input type 'Date', then it has to be formatted as "yyyy-MM-dd" (Note: capital MM for Month, lower case mm for minutes). Otherwise, it will clear the value and leave the datepicker empty.

Let's say you have a button called "DateChanger" and you want to set your datepicker to "22 Dec 2012" when you click it.

<script>
    $(document).ready(function () {
        $('#DateChanger').click(function() {
             $('#dtFrom').val("2012-12-22");
        });
    });
</script>
<input type="date" id="dtFrom" name="dtFrom" />
<button id="DateChanger">Click</button>

Remember to include JQuery reference.

Entity Framework and Connection Pooling

According to Daniel Simmons:

Create a new ObjectContext instance in a Using statement for each service method so that it is disposed of before the method returns. This step is critical for scalability of your service. It makes sure that database connections are not kept open across service calls and that temporary state used by a particular operation is garbage collected when that operation is over. The Entity Framework automatically caches metadata and other information it needs in the app domain, and ADO.NET pools database connections, so re-creating the context each time is a quick operation.

This is from his comprehensive article here:

http://msdn.microsoft.com/en-us/magazine/ee335715.aspx

I believe this advice extends to HTTP requests, so would be valid for ASP.NET. A stateful, fat-client application such as a WPF application might be the only case for a "shared" context.

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

Click outside menu to close in jquery

If using a plugin is ok in you case, then I suggest Ben Alman's clickoutside plugin located here:

its usage is as simple as this:

$('#menu').bind('clickoutside', function (event) {
    $(this).hide();
});

hope this helps.

jQuery count number of divs with a certain class?

You can use jQuery.children property.

var numItems = $('.wrapper').children('div').length;

for more information refer http://api.jquery.com/

Why does Git tell me "No such remote 'origin'" when I try to push to origin?

I faced this issue when I was tring to link a locally created repo with a blank repo on github. Initially I was trying git remote set-url but I had to do git remote add instead.

git remote add origin https://github.com/VijayNew/NewExample.git

TLS 1.2 in .NET Framework 4.0

According to this, you will need .NET 4.5 installed. For more details, visit the webpage. The gist of it is that after you have .NET 4.5 installed, your 4.0 apps will use the 4.5 System.dll. You can enable TLS 1.2 in two ways:

  • At the beginning of the application, add this code: ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
  • Set the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319: SchUseStrongCrypto to DWORD 1

How do I print the content of httprequest request?

In case someone also want to dump response like me. i avoided to dump response body. following code just dump the StatusCode and Headers.

static private String dumpResponse(HttpServletResponse resp){
    StringBuilder sb = new StringBuilder();

    sb.append("Response Status = [" + resp.getStatus() + "], ");
    String headers = resp.getHeaderNames().stream()
                    .map(headerName -> headerName + " : " + resp.getHeaders(headerName) )
                    .collect(Collectors.joining(", "));

    if (headers.isEmpty()) {
        sb.append("Response headers: NONE,");
    } else {
        sb.append("Response headers: "+headers+",");
    }

    return sb.toString();
}

Efficient SQL test query or validation query that will work across all (or most) databases

I use this one:

select max(table_catalog) as x from information_schema.tables

to check connection and ability to run queries (with 1 row as result) for postgreSQL, MySQL and MSSQL.

Count the number of all words in a string

Use nchar

if vector of strings is called x

(nchar(x) - nchar(gsub(' ','',x))) + 1

Find out number of spaces then add one

How do I perform HTML decoding/encoding using Python/Django?

If anyone is looking for a simple way to do this via the django templates, you can always use filters like this:

<html>
{{ node.description|safe }}
</html>

I had some data coming from a vendor and everything I posted had html tags actually written on the rendered page as if you were looking at the source.

jquery ajax get responsetext from http url

in jquery ajax functions, the success callback signature is:

function (data, textStatus) {
  // data could be xmlDoc, jsonObj, html, text, etc...
  this; // the options for this ajax request
}

depending on the data type you've asked, using the 'dataType' parameter, you'll get the 'data' argument.

from the docs:

dataType (String) Default: Intelligent Guess (xml or html). The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently pass either responseXML or responseText to your success callback, based on the MIME type of the response.

The available types (and the result passed as the first argument to your success callback) are:

"xml": Returns a XML document that can be processed via jQuery.

"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.

"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option "cache" is used. Note: This will turn POSTs into GETs for remote-domain requests.

"json": Evaluates the response as JSON and returns a JavaScript Object.

"jsonp": Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback. (Added in jQuery 1.2)

"text": A plain text string.

see http://docs.jquery.com/Ajax/jQuery.ajax#options

PHP strtotime +1 month adding an extra month

Maybe because its 2013-01-29 so +1 month would be 2013-02-29 which doesn't exist so it would be 2013-03-01

You could try

date('m/d/y h:i a',(strtotime('next month',strtotime(date('m/01/y')))));

from the comments on http://php.net/manual/en/function.strtotime.php

convert htaccess to nginx

Have not tested it yet, but the looks are better than the one Alex mentions.

The description at winginx.com/en/htaccess says:

About the htaccess to nginx converter

The service is to convert an Apache's .htaccess to nginx configuration instructions.

First of all, the service was thought as a mod_rewrite to nginx converter. However, it allows you to convert some other instructions that have reason to be ported from Apache to nginx.

Note server instructions (e.g. php_value, etc.) are ignored.

The converter does not check syntax, including regular expressions and logic errors.

Please, check the result manually before use.

How to configure SMTP settings in web.config

I don't have enough rep to answer ClintEastwood, and the accepted answer is correct for the Web.config file. Adding this in for code difference.

When your mailSettings are set on Web.config, you don't need to do anything other than new up your SmtpClient and .Send. It finds the connection itself without needing to be referenced. You would change your C# from this:

SmtpClient smtpClient = new SmtpClient("smtp.sender.you", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("username", "password");
smtpClient.Credentials = credentials;
smtpClient.Send(msgMail);  

To this:

SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(msgMail);

How do I make XAML DataGridColumns fill the entire DataGrid?

Another spin on the same theme:

protected void OnWindowSizeChanged(object sender, SizeChangedEventArgs e)
{
    dataGrid.Width = e.NewSize.Width - (e.NewSize.Width * .1);

    foreach (var column in dataGrid.Columns)
    {
       column.Width = dataGrid.Width / dataGrid.Columns.Count;
    }
 }

Check if checkbox is checked with jQuery

Simple Demo for checking and setting a check box.

jsfiddle!

$('.attr-value-name').click(function() {
    if($(this).parent().find('input[type="checkbox"]').is(':checked'))
    {
        $(this).parent().find('input[type="checkbox"]').prop('checked', false);
    }
    else
    {
        $(this).parent().find('input[type="checkbox"]').prop('checked', true);
    }
});

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

Improving upon @Ianl's answer,

It seems that if 2-step authentication is enabled, you have to use token instead of password. You could generate a token here.

If you want to disable the prompts for both the username and password then you can set the URL as follows -

git remote set-url origin https://username:[email protected]/WEMP/project-slideshow.git

Note that the URL has both the username and password. Also the .git/config file should show your current settings.


Update 20200128:

If you don't want to store the password in the config file, then you can generate your personal token and replace the password with the token. Here are some details.

It would look like this -

git remote set-url origin https://username:[email protected]/WEMP/project-slideshow.git

How can I make a menubar fixed on the top while scrolling

 #header {
        top:0;
        width:100%;
        position:fixed;
        background-color:#FFF;
    }

    #content {
        position:static;
        margin-top:100px;
    }

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

BLOB primarily intended to hold non-traditional data, such as images,videos,voice or mixed media. CLOB intended to retain character-based data.

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

Firstly run this query

SHOW VARIABLES LIKE '%char%';

You have character_set_server='latin1'

If so,go into your config file,my.cnf and add or uncomment these lines:

character-set-server = utf8
collation-server = utf8_unicode_ci

Restart the server. Yes late to the party,just encountered the same issue.

How to check user is "logged in"?

if (User.Identity.IsAuthenticated)
{
    Page.Title = "Home page for " + User.Identity.Name;
}
else
{
    Page.Title = "Home page for guest user.";
}

PHP, pass array through POST

There are two things to consider: users can modify forms, and you need to secure against Cross Site Scripting (XSS).

XSS

XSS is when a user enters HTML into their input. For example, what if a user submitted this value?:

" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value="

This would be written into your form like so:

<input type="hidden" name="prova[]" value="" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value=""/>

The best way to protect against this is to use htmlspecialchars() to secure your input. This encodes characters such as < into &lt;. For example:

<input type="hidden" name="prova[]" value="<?php echo htmlspecialchars($array); ?>"/>

You can read more about XSS here: https://www.owasp.org/index.php/XSS

Form Modification

If I were on your site, I could use Chrome's developer tools or Firebug to modify the HTML of your page. Depending on what your form does, this could be used maliciously.

I could, for example, add extra values to your array, or values that don't belong in the array. If this were a file system manager, then I could add files that don't exist or files that contain sensitive information (e.g.: replace myfile.jpg with ../index.php or ../db-connect.php).

In short, you always need to check your inputs later to make sure that they make sense, and only use safe inputs in forms. A File ID (a number) is safe, because you can check to see if the number exists, then extract the filename from a database (this assumes that your database contains validated input). A File Name isn't safe, for the reasons described above. You must either re-validate the filename or else I could change it to anything.

Single controller with multiple GET methods in ASP.NET Web API

I was trying to use Web Api 2 attribute routing to allow for multiple Get methods, and I had incorporated the helpful suggestions from previous answers, but in the Controller I had only decorated the "special" method (example):

[Route( "special/{id}" )]
public IHttpActionResult GetSomethingSpecial( string id ) {

...without also also placing a [RoutePrefix] at the top of the Controller:

[RoutePrefix("api/values")]
public class ValuesController : ApiController

I was getting errors stating that no Route was found matching the submitted URI. Once I had both the [Route] decorating the method as well as [RoutePrefix] decorating the Controller as a whole, it worked.

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

In terms of coding, a bidirectional relationship is more complex to implement because the application is responsible for keeping both sides in synch according to JPA specification 5 (on page 42). Unfortunately the example given in the specification does not give more details, so it does not give an idea of the level of complexity.

When not using a second level cache it is usually not a problem to do not have the relationship methods correctly implemented because the instances get discarded at the end of the transaction.

When using second level cache, if anything gets corrupted because of wrongly implemented relationship handling methods, this means that other transactions will also see the corrupted elements (the second level cache is global).

A correctly implemented bi-directional relationship can make queries and the code simpler, but should not be used if it does not really make sense in terms of business logic.

How to make a div 100% height of the browser window

If you’re able to absolutely position your elements,

position: absolute;
top: 0;
bottom: 0;

would do it.

Get time of specific timezone

You could use Intl.DateTimeFormat.

_x000D_
_x000D_
let options = {_x000D_
    timeZone: 'Europe/London',_x000D_
    year: 'numeric',_x000D_
    month: 'numeric',_x000D_
    day: 'numeric',_x000D_
    hour: 'numeric',_x000D_
    minute: 'numeric',_x000D_
    second: 'numeric',_x000D_
  },_x000D_
  formatter = new Intl.DateTimeFormat([], options);_x000D_
_x000D_
console.log(formatter.format(new Date()));
_x000D_
_x000D_
_x000D_

Alternatively, if you're formatting just once instead of bulk use Date.prototype.toLocaleDateString().

(new Date()).toLocaleString([], options)

Unfortunately browsers are not required to understand timezones other than UTC, so try these blocks and figure out an alternative in case it fails, for example fetch the timezone offset from a server.

How do I abort/cancel TPL Tasks?

You can use a CancellationToken to control whether the task gets cancelled. Are you talking about aborting it before it's started ("nevermind, I already did this"), or actually interrupting it in middle? If the former, the CancellationToken can be helpful; if the latter, you will probably need to implement your own "bail out" mechanism and check at appropriate points in the task execution whether you should fail fast (you can still use the CancellationToken to help you, but it's a little more manual).

MSDN has an article about cancelling Tasks: http://msdn.microsoft.com/en-us/library/dd997396.aspx

Datetime in where clause

WHERE datetime_column >= '20081220 00:00:00.000'
  AND datetime_column < '20081221 00:00:00.000'

How to fix syntax error, unexpected T_IF error in php?

Here is the issue

  $total_result = $result->num_rows;

try this

<?php
if ($result = $mysqli->query("SELECT * FROM players ORDER BY id"))
{
    if ($result->num_rows > 0)
    {
        $total_result = $result->num_rows;
        $total_pages = ceil($total_result / $per_page);

        if(isset($_GET['page']) && is_numeric($_GET['page']))
        {
            $show_page = $_GET['page'];

            if ($show_page > 0 && $show_page <= $total_pages)
            {
                $start = ($show_page - 1) * $per_page;
                $end = $start + $per_page;
            }
            else
            {
                $start = 0;
                $end = $per_page;
            }               

        }
        else
        {
            $start = 0;
            $end = $per_page;
        }


        //display paginations
        echo "<p> View pages: ";
        for ($i=1; $i < $total_pages; $i++)
        { 
            if (isset($_GET['page']) && $_GET['page'] == $i)
            {
                echo  $i . " ";
            }
            else
            {
                echo "<a href='view-pag.php?$i'>" . $i . "</a> | ";
            }

        }
        echo "</p>";

    }
    else
    {
        echo "No result to display.";
    }

}
else
{
    echo "Error: " . $mysqli->error;
}


?>

How do I create an average from a Ruby array?

I was hoping for Math.average(values), but no such luck.

values = [0,4,8,2,5,0,2,6]
average = values.sum / values.size.to_f

How should I tackle --secure-file-priv in MySQL?

It's working as intended. Your MySQL server has been started with --secure-file-priv option which basically limits from which directories you can load files using LOAD DATA INFILE.

You may use SHOW VARIABLES LIKE "secure_file_priv"; to see the directory that has been configured.

You have two options:

  1. Move your file to the directory specified by secure-file-priv.
  2. Disable secure-file-priv. This must be removed from startup and cannot be modified dynamically. To do this check your MySQL start up parameters (depending on platform) and my.ini.

Add a prefix string to beginning of each line

SETLOCAL ENABLEDELAYEDEXPANSION

YourPrefix=blabla

YourPath=C:\path

for /f "tokens=*" %%a in (!YourPath!\longfile.csv)     do (echo !YourPrefix!%%a) >> !YourPath!\Archive\output.csv

How to convert signed to unsigned integer in python

You could use the struct Python built-in library:

Encode:

import struct

i = -6884376
print('{0:b}'.format(i))

packed = struct.pack('>l', i)  # Packing a long number.
unpacked = struct.unpack('>L', packed)[0]  # Unpacking a packed long number to unsigned long
print(unpacked)
print('{0:b}'.format(unpacked))

Out:

-11010010000110000011000
4288082920
11111111100101101111001111101000

Decode:

dec_pack = struct.pack('>L', unpacked)  # Packing an unsigned long number.
dec_unpack = struct.unpack('>l', dec_pack)[0]  # Unpacking a packed unsigned long number to long (revert action).
print(dec_unpack)

Out:

-6884376

[NOTE]:

  • > is BigEndian operation.
  • l is long.
  • L is unsigned long.
  • In amd64 architecture int and long are 32bit, So you could use i and I instead of l and L respectively.

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

According to the latest updates for OpenCV 3.0 and higher, you need to change the Property Identifiers as follows in the code by Mehran:

cv2.cv.CV_CAP_PROP_POS_FRAMES

to

cv2.CAP_PROP_POS_FRAMES

and same applies to cv2.CAP_PROP_POS_FRAME_COUNT.

Hope it helps.

How to remove numbers from string using Regex.Replace?

Try the following:

var output = Regex.Replace(input, @"[\d-]", string.Empty);

The \d identifier simply matches any digit character.

Converting a string to a date in JavaScript

If you need to check the contents of the string before converting to Date format:

// Convert 'M/D/YY' to Date()
mdyToDate = function(mdy) {
  var d = mdy.split(/[\/\-\.]/, 3);

  if (d.length != 3) return null;

  // Check if date is valid
  var mon = parseInt(d[0]), 
      day = parseInt(d[1]),
      year= parseInt(d[2]);
  if (d[2].length == 2) year += 2000;
  if (day <= 31 && mon <= 12 && year >= 2015)
    return new Date(year, mon - 1, day);

  return null; 
}

jQuery form validation on button click

You can also achieve other way using button tag

According new html5 attribute you also can add a form attribute like

<form id="formId">
    <input type="text" name="fname">
</form>

<button id="myButton" form='#formId'>My Awesome Button</button>

So the button will be attached to the form.

This should work with the validate() plugin of jQuery like :

var validator = $( "#formId" ).validate();
validator.element( "#myButton" );

It's working too with input tag

Source :

https://developer.mozilla.org/docs/Web/HTML/Element/Button

How to host material icons offline?

Method 2. Self hosting Developer Guide

Download the latest release from github (assets: zip file), unzip, and copy the font folder, containing the material design icons files, into your local project -- https://github.com/google/material-design-icons/releases

You only need to use the font folder from the archive: it contains the icons fonts in the different formats (for multiple browser support) and boilerplate css.

  • Replace the source in the url attribute of @font-face, with the relative path to the iconfont folder in your local project, (where the font files are located) eg. url("iconfont/MaterialIcons-Regular.ttf")
@font-face {
   font-family: 'Material Icons';
   font-style: normal;
   font-weight: 400;
   src: url(iconfont/MaterialIcons-Regular.eot); /* For IE6-8 */
   src: local('Material Icons'),
        local('MaterialIcons-Regular'),
        url(iconfont/MaterialIcons-Regular.woff2) format('woff2'),
        url(iconfont/MaterialIcons-Regular.woff) format('woff'),
        url(iconfont/MaterialIcons-Regular.ttf) format('truetype');
}

.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 24px;  /* Preferred icon size */
  display: inline-block;
  line-height: 1;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;

  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;
  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;

  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;

  /* Support for IE. */
  font-feature-settings: 'liga';
}

<i class="material-icons">face</i>

NPM / Bower Packages

Google officially has a Bower and NPM dependency option -- follow Material Icons Guide 1

Using bower : bower install material-design-icons --save

Using NPM : npm install material-design-icons --save

Material Icons : Alternatively look into Material design icon font and CSS framework for self hosting the icons, from @marella's https://marella.me/material-icons/


Note

It seems google has the project on low maintenance mode. The last release was, at time of writing, 3 years ago!

There are several issues on GitHub regarding this, but I'd like to refer to @cyberalien comment on the issue Is this project actively maintained? #951 where it refers several community projects that forked and continue maintaining material icons.


Best Practices for mapping one object to another

This is a possible generic implementation using a bit of reflection (pseudo-code, don't have VS now):

public class DtoMapper<DtoType>
{
    Dictionary<string,PropertyInfo> properties;

    public DtoMapper()
    {
        // Cache property infos
        var t = typeof(DtoType);
        properties = t.GetProperties().ToDictionary(p => p.Name, p => p);
     }

    public DtoType Map(Dto dto)
    {
        var instance = Activator.CreateInstance(typeOf(DtoType));

        foreach(var p in properties)
        {
            p.SetProperty(
                instance, 
                Convert.Type(
                    p.PropertyType, 
                    dto.Items[Array.IndexOf(dto.ItemsNames, p.Name)]);

            return instance;
        }
    }

Usage:

var mapper = new DtoMapper<Model>();
var modelInstance = mapper.Map(dto);

This will be slow when you create the mapper instance but much faster later.

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

I have solved this issue by below steps:

Right click the Maven Project -> Build Path -> Configure Build Path In Order and Export tab, you can see the message like '2 build path entries are missing' Now select 'JRE System Library' and 'Maven Dependencies' checkbox Click OK Now you can see below in all type of Explorers (Package or Project or Navigator)

What's the difference between primitive and reference types?

Primitive Data Types :

  • Predefined by the language and named by a keyword
  • Total no = 8
    boolean
    char
    byte
    short
    integer
    long
    float
    double

Reference/Object Data Types :

  • Created using defined constructors of the classes
  • Used to access objects
  • Default value of any reference variable is null
  • Reference variable can be used to refer to any object of the declared type or any compatible type.

Recreating a Dictionary from an IEnumerable<KeyValuePair<>>

If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:

Dictionary<string, ArrayList> result = target.GetComponents()
                                      .ToDictionary(x => x.Key, x => x.Value);

There's no such thing as an IEnumerable<T1, T2> but a KeyValuePair<TKey, TValue> is fine.

PHP check if date between two dates

You are comparing the dates as strings, which won't work because the comparison is lexicographical. It's the same issue as when sorting a text file, where a line 20 would appear after a line 100 because the contents are not treated as numbers but as sequences of ASCII codes. In addition, the dates created are all wrong because you are using a string format string where a timestamp is expected (second argument).

Instead of this you should be comparing timestamps of DateTime objects, for instance:

 $paymentDate = date_create();
 $contractDateBegin = date_create_from_format('d/m/Y', '01/01/2001');
 $contractDateEnd = date_create_from_format('d/m/Y', '01/01/2015');

Your existing conditions will then work correctly.

Generate random 5 characters string

A speedy way is to use the most volatile characters of the uniqid function.

For example:

$rand = substr(uniqid('', true), -5);

Where to get this Java.exe file for a SQL Developer installation

I encountered the following message repeatedly when trying to start SQL Developer from my installation of Oracle Database 11g Enterprise: Enter the full pathname for java.exe.

No matter how many times I browsed to the correct path, I kept being presented with the exact same dialog box. This was in Windows 7, and the solution was to right-click on the SQL Developer icon and select "Run as administrator". I then used this path: C:\app\shellperson\product\11.1.0\db_1\jdk\jre\bin\java.exe

How to apply CSS to iframe?

Other answers here seem to use jQuery and CSS links.

This code uses vanilla JavaScript. It creates a new <style> element. It sets the text content of that element to be a string containing the new CSS. And it appends that element directly to the iframe document's head.

var iframe = document.getElementById('the-iframe');
var style = document.createElement('style');
style.textContent =
  '.some-class-name {' +
  '  some-style-name: some-value;' +
  '}' 
;
iframe.contentDocument.head.appendChild(style);

How to use clock() in C++

#include <iostream>
#include <cstdio>
#include <ctime>

int main() {
    std::clock_t start;
    double duration;

    start = std::clock();

    /* Your algorithm here */

    duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;

    std::cout<<"printf: "<< duration <<'\n';
}

What is the maximum length of a valid email address?

The other answers muddy the water a bit. Simple answer: 254 total chars in our control for email 256 are for the ENTIRE email address, which includes implied "<" at the beginning, and ">" at the end. Therefore, 254 are left over for our use.

Loop through all the files with a specific extension

as @chepner says in his comment you are comparing $i to a fixed string.

To expand and rectify the situation you should use [[ ]] with the regex operator =~

eg:

for i in $(ls);do
    if [[ $i =~ .*\.java$ ]];then
        echo "I want to do something with the file $i"
    fi
done

the regex to the right of =~ is tested against the value of the left hand operator and should not be quoted, ( quoted will not error but will compare against a fixed string and so will most likely fail"

but @chepner 's answer above using glob is a much more efficient mechanism.

How to replace ${} placeholders in a text file?

If you are open to using Perl, that would be my suggestion. Although there are probably some sed and/or AWK experts that probably know how to do this much easier. If you have a more complex mapping with more than just dbName for your replacements you could extend this pretty easily, but you might just as well put it into a standard Perl script at that point.

perl -p -e 's/\$\{dbName\}/testdb/s' yourfile | mysql

A short Perl script to do something slightly more complicated (handle multiple keys):

#!/usr/bin/env perl
my %replace = ( 'dbName' => 'testdb', 'somethingElse' => 'fooBar' );
undef $/;
my $buf = <STDIN>;
$buf =~ s/\$\{$_\}/$replace{$_}/g for keys %replace;
print $buf;

If you name the above script as replace-script, it could then be used as follows:

replace-script < yourfile | mysql

How to find a value in an excel column by vba code Cells.Find

Dim strFirstAddress As String
Dim searchlast As Range
Dim search As Range

Set search = ActiveSheet.Range("A1:A100")
Set searchlast = search.Cells(search.Cells.Count)

Set rngFindValue = ActiveSheet.Range("A1:A100").Find(Text, searchlast, xlValues)
If Not rngFindValue Is Nothing Then
  strFirstAddress = rngFindValue.Address
  Do
    Set rngFindValue = search.FindNext(rngFindValue)
  Loop Until rngFindValue.Address = strFirstAddress

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

You can create user with no password in phpmyadmin and it solves the problem! Lebbar Abdelhadi,

How to show loading spinner in jQuery?

If you are using $.ajax() you can use somthing like this:

$.ajax({
  url: "destination url",
  success: sdialog,
  error: edialog,
  // shows the loader element before sending.
  beforeSend: function() {
    $("#imgSpinner1").show();
  },
  // hides the loader after completion of request, whether successfull or failor.             
  complete: function() {
    $("#imgSpinner1").hide();
  },
  type: 'POST',
  dataType: 'json'
});

Although the setting is named "beforeSend", as of jQuery 1.5 "beforeSend" will be called regardless of the request type. i.e. The .show() function will be called if type: 'GET'.

Differences between socket.io and websockets

tl;dr;

Comparing them is like comparing Restaurant food (maybe expensive sometimes, and maybe not 100% you want it) with homemade food, where you have to gather and grow each one of the ingredients on your own.

Maybe if you just want to eat an apple, the latter is better. But if you want something complicated and you're alone, it's really not worth cooking and making all the ingredients by yourself.


I've worked with both of these. Here is my experience.

SocketIO

  • Has autoconnect

  • Has namespaces

  • Has rooms

  • Has subscriptions service

  • Has a pre-designed protocol of communication

    (talking about the protocol to subscribe, unsubscribe or send a message to a specific room, you must all design them yourself in websockets)

  • Has good logging support

  • Has integration with services such as redis

  • Has fallback in case WS is not supported (well, it's more and more rare circumstance though)

  • It's a library. Which means, it's actually helping your cause in every way. Websockets is a protocol, not a library, which SocketIO uses anyway.

  • The whole architecture is supported and designed by someone who is not you, thus you dont have to spend time designing and implementing anything from the above, but you can go straight to coding business rules.

  • Has a community because it's a library (you can't have a community for HTTP or Websockets :P They're just standards/protocols)

Websockets

  • You have the absolute control, depending on who you are, this can be very good or very bad
  • It's as light as it gets (remember, its a protocol, not a library)
  • You design your own architecture & protocol
  • Has no autoconnect, you implement it yourself if yo want it
  • Has no subscription service, you design it
  • Has no logging, you implement it
  • Has no fallback support
  • Has no rooms, or namespaces. If you want such concepts, you implement them yourself
  • Has no support for anything, you will be the one who implements everything
  • You first have to focus on the technical parts and designing everything that comes and goes from and to your Websockets
  • You have to debug your designs first, and this is going to take you a long time

Obviously, you can see I'm biased to SocketIO. I would love to say so, but I'm really really not.

I'm really fighting not to use SocketIO. I dont wanna use it. I like designing my own stuff and solving my own problems myself. But if you want to have a business and not just a 1000 lines project, and you're going to choose Websockets, you're going to have to implement every single thing yourself. You have to debug everything. You have to make your own subscription service. Your own protocol. Your own everything. And you have to make sure everything is quite sophisticated. And you'll make A LOT of mistakes along the way. You'll spend tons of time designing and debugging everything. I did and still do. I'm using websockets and the reason I'm here is because they're unbearable for a one guy trying to deal with solving business rules for his startup and instead dealing with Websocket designing jargon.

Choosing Websockets for a big application ain't an easy option if you're a one guy army or a small team. I've wrote more code in Websockets than I ever wrote with SocketIO in the past, and all I have to say is ... Choose SocketIO if you want a finished product and design. (unless you want something very simple in functionality)

Is there a numpy builtin to reject outliers from a list

if you want to get the index position of the outliers idx_list will return it.

def reject_outliers(data, m = 2.):
        d = np.abs(data - np.median(data))
        mdev = np.median(d)
        s = d/mdev if mdev else 0.
        data_range = np.arange(len(data))
        idx_list = data_range[s>=m]
        return data[s<m], idx_list

data_points = np.array([8, 10, 35, 17, 73, 77])  
print(reject_outliers(data_points))

after rejection: [ 8 10 35 17], index positions of outliers: [4 5]

How to align absolutely positioned element to center?

All you have to do is,

make sure your parent DIV has position:relative

and the element you want center, set it a height and width. use the following CSS

.layer {
    width: 600px; height: 500px;
    display: block;
    position:absolute;
    top:0;
    left: 0;
    right:0;
    bottom: 0;
    margin:auto;
  }
http://jsbin.com/aXEZUgEJ/1/

Construct pandas DataFrame from items in nested dictionary

In case someone wants to get the data frame in a "long format" (leaf values have the same type) without multiindex, you can do this:

pd.DataFrame.from_records(
    [
        (level1, level2, level3, leaf)
        for level1, level2_dict in user_dict.items()
        for level2, level3_dict in level2_dict.items()
        for level3, leaf in level3_dict.items()
    ],
    columns=['UserId', 'Category', 'Attribute', 'value']
)

    UserId    Category Attribute     value
0       12  Category 1     att_1         1
1       12  Category 1     att_2  whatever
2       12  Category 2     att_1        23
3       12  Category 2     att_2   another
4       15  Category 1     att_1        10
5       15  Category 1     att_2       foo
6       15  Category 2     att_1        30
7       15  Category 2     att_2       bar

(I know the original question probably wants (I.) to have Levels 1 and 2 as multiindex and Level 3 as columns and (II.) asks about other ways than iteration over values in the dict. But I hope this answer is still relevant and useful (I.): to people like me who have tried to find a way to get the nested dict into this shape and google only returns this question and (II.): because other answers involve some iteration as well and I find this approach flexible and easy to read; not sure about performance, though.)

SVN Commit specific files

try this script..

#!/bin/bash
NULL="_"
for f in `svn st|grep -v ^\?|sed s/.\ *//`; 
     do LIST="${LIST} $f $NULL on"; 
done
dialog --checklist "Select files to commit" 30 60 30 $LIST 2>/tmp/svnlist.txt
svn ci `cat /tmp/svnlist.txt|sed 's/"//g'`

How to do what head, tail, more, less, sed do in Powershell?

Get-Content (alias: gc) is your usual option for reading a text file. You can then filter further:

gc log.txt | select -first 10 # head
gc -TotalCount 10 log.txt     # also head
gc log.txt | select -last 10  # tail
gc -Tail 10 log.txt           # also tail (since PSv3), also much faster than above option
gc log.txt | more             # or less if you have it installed
gc log.txt | %{ $_ -replace '\d+', '($0)' }         # sed

This works well enough for small files, larger ones (more than a few MiB) are probably a bit slow.

The PowerShell Community Extensions include some cmdlets for specialised file stuff (e.g. Get-FileTail).

Is there a foreach loop in Go?

https://golang.org/ref/spec#For_range

A "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration values to corresponding iteration variables and then executes the block.

As an example:

for index, element := range someSlice {
    // index is the index where we are
    // element is the element from someSlice for where we are
}

If you don't care about the index, you can use _:

for _, element := range someSlice {
    // element is the element from someSlice for where we are
}

The underscore, _, is the blank identifier, an anonymous placeholder.

What is the difference between a definition and a declaration?

A declaration introduces an identifier and describes its type, be it a type, object, or function. A declaration is what the compiler needs to accept references to that identifier. These are declarations:

extern int bar;
extern int g(int, int);
double f(int, double); // extern can be omitted for function declarations
class foo; // no extern allowed for type declarations

A definition actually instantiates/implements this identifier. It's what the linker needs in order to link references to those entities. These are definitions corresponding to the above declarations:

int bar;
int g(int lhs, int rhs) {return lhs*rhs;}
double f(int i, double d) {return i+d;}
class foo {};

A definition can be used in the place of a declaration.

An identifier can be declared as often as you want. Thus, the following is legal in C and C++:

double f(int, double);
double f(int, double);
extern double f(int, double); // the same as the two above
extern double f(int, double);

However, it must be defined exactly once. If you forget to define something that's been declared and referenced somewhere, then the linker doesn't know what to link references to and complains about a missing symbols. If you define something more than once, then the linker doesn't know which of the definitions to link references to and complains about duplicated symbols.


Since the debate what is a class declaration vs. a class definition in C++ keeps coming up (in answers and comments to other questions) , I'll paste a quote from the C++ standard here.
At 3.1/2, C++03 says:

A declaration is a definition unless it [...] is a class name declaration [...].

3.1/3 then gives a few examples. Amongst them:

[Example: [...]
struct S { int a; int b; }; // defines S, S::a, and S::b [...]
struct S; // declares S
—end example

To sum it up: The C++ standard considers struct x; to be a declaration and struct x {}; a definition. (In other words, "forward declaration" a misnomer, since there are no other forms of class declarations in C++.)

Thanks to litb (Johannes Schaub) who dug out the actual chapter and verse in one of his answers.

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

Ok So after hours of trying finally implemented it. Below is the code ..

  buttons.get(2).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
       if(buttons.get(2).getText().toString().equalsIgnoreCase(getResources().getString(R.string.show))){
           editTexts.get(1).setInputType(InputType.TYPE_CLASS_TEXT);
           editTexts.get(1).setSelection(editTexts.get(1).getText().length());
           buttons.get(2).setText(getResources().getString(R.string.hide));
        }else{
           editTexts.get(1).setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
           //editTexts.get(1).setTransformationMethod(PasswordTransformationMethod.getInstance());
           editTexts.get(1).setSelection(editTexts.get(1).getText().length());
           buttons.get(2).setText(getResources().getString(R.string.show));
       }

    }
});

Explanations:- I have a button with default text as show. After onclick event on it checking if button's text is show. If it is show then changing the input type,adjusting the cursor position and setting new text as hide in it.

When it is hide... doing reverse i.e. hiding the password,adjusting the cursor and setting the text as show. And that's it. It is working like a charm.

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

Logcat not displaying my log calls

I needed to restart the adb service with the command adb usb

Prior to this I was getting all logging and able to debug, but wasn't getting my own log lines (yes, I was getting system logging associated with my application).

Get protocol, domain, and port from URL

Simple answer that works for all browsers:

let origin;

if (!window.location.origin) {
  origin = window.location.protocol + "//" + window.location.hostname + 
     (window.location.port ? ':' + window.location.port: '');
}

origin = window.location.origin;

Should I put input elements inside a label element?

Both are correct, but putting the input inside the label makes it much less flexible when styling with CSS.

First, a <label> is restricted in which elements it can contain. For example, you can only put a <div> between the <input> and the label text, if the <input> is not inside the <label>.

Second, while there are workarounds to make styling easier like wrapping the inner label text with a span, some styles will be in inherited from parent elements, which can make styling more complicated.

LINQ to Entities does not recognize the method

If anyone is looking for a VB.Net answer (as I was initially), here it is:

Public Function IsSatisfied() As Expression(Of Func(Of Charity, String, String, Boolean))

Return Function(charity, name, referenceNumber) (String.IsNullOrWhiteSpace(name) Or
                                                         charity.registeredName.ToLower().Contains(name.ToLower()) Or
                                                         charity.alias.ToLower().Contains(name.ToLower()) Or
                                                         charity.charityId.ToLower().Contains(name.ToLower())) And
                                                    (String.IsNullOrEmpty(referenceNumber) Or
                                                     charity.charityReference.ToLower().Contains(referenceNumber.ToLower()))
End Function

jQuery UI Sortable Position

Use update instead of stop

http://api.jqueryui.com/sortable/

update( event, ui )

Type: sortupdate

This event is triggered when the user stopped sorting and the DOM position has changed.

.

stop( event, ui )

Type: sortstop

This event is triggered when sorting has stopped. event Type: Event

Piece of code:

http://jsfiddle.net/7a1836ce/

<script type="text/javascript">

var sortable    = new Object();
sortable.s1     = new Array(1, 2, 3, 4, 5);
sortable.s2     = new Array(1, 2, 3, 4, 5);
sortable.s3     = new Array(1, 2, 3, 4, 5);
sortable.s4     = new Array(1, 2, 3, 4, 5);
sortable.s5     = new Array(1, 2, 3, 4, 5);

sortingExample();

function sortingExample()
{
    // Init vars

    var tDiv    = $('<div></div>');
    var tSel    = '';

    // ul
    for (var tName in sortable)
    {

        // Creating ul list
        tDiv.append(createUl(sortable[tName], tName));
        // Add selector id
        tSel += '#' + tName + ',';

    }

    $('body').append('<div id="divArrayInfo"></div>');
    $('body').append(tDiv);

    // ul sortable params

    $(tSel).sortable({connectWith:tSel,
       start: function(event, ui) 
       {
            ui.item.startPos = ui.item.index();
       },
        update: function(event, ui)
        {
            var a   = ui.item.startPos;
            var b   = ui.item.index();
            var id = this.id;

            // If element moved to another Ul then 'update' will be called twice
            // 1st from sender list
            // 2nd from receiver list
            // Skip call from sender. Just check is element removed or not

            if($('#' + id + ' li').length < sortable[id].length)
            {
                return;
            }

            if(ui.sender === null)
            {
                sortArray(a, b, this.id, this.id);
            }
            else
            {
                sortArray(a, b, $(ui.sender).attr('id'), this.id);
            }

            printArrayInfo();

        }
    }).disableSelection();;

// Add styles

    $('<style>')
    .attr('type', 'text/css')
    .html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
    .appendTo('head');


    printArrayInfo();

}

function printArrayInfo()
{

    var tStr = '';

    for ( tName in sortable)
    {

        tStr += tName + ': ';

        for(var i=0; i < sortable[tName].length; i++)
        {

            // console.log(sortable[tName][i]);
            tStr += sortable[tName][i] + ', ';

        }

        tStr += '<br>';

    }

    $('#divArrayInfo').html(tStr);

}


function createUl(tArray, tId)
{

    var tUl = $('<ul>', {id:tId, class:'sortableClass'})

    for(var i=0; i < tArray.length; i++)
    {

        // Create Li element
        var tLi = $('<li>' + tArray[i] + '</li>');
        tUl.append(tLi);

    }

    return tUl;
}

function sortArray(a, b, idA, idB)
{
    var c;

    c = sortable[idA].splice(a, 1);
    sortable[idB].splice(b, 0, c);      

}
</script>

Hidden Columns in jqGrid

It is a bit old, this post. But this is my code to show/hide the columns. I use the built in function to display the columns and just mark them.

Function that displays columns shown/hidden columns. The #jqGrid is the name of my grid, and the columnChooser is the jqGrid column chooser.

  function showHideColumns() {
        $('#jqGrid').jqGrid('columnChooser', {
            width: 250,
            dialog_opts: {
                modal: true,
                minWidth: 250,
                height: 300,
                show: 'blind',
                hide: 'explode',
                dividerLocation: 0.5
            } });

Class vs. static method in JavaScript

Here is a good example to demonstrate how Javascript works with static/instance variables and methods.

function Animal(name) {
    Animal.count = Animal.count+1||1;// static variables, use function name "Animal"
    this.name = name; //instance variable, using "this"
}

Animal.showCount = function () {//static method
    alert(Animal.count)
}

Animal.prototype.showName=function(){//instance method
    alert(this.name);
}

var mouse = new Animal("Mickey");
var elephant = new Animal("Haddoop");

Animal.showCount();  // static method, count=2
mouse.showName();//instance method, alert "Mickey"
mouse.showCount();//Error!! mouse.showCount is not a function, which is different from  Java

How to force a web browser NOT to cache images

I'm a NEW Coder, but here's what I came up with, to stop the Browser from caching and holding onto my webcam views:

<meta Http-Equiv="Cache" content="no-cache">
<meta Http-Equiv="Pragma-Control" content="no-cache">
<meta Http-Equiv="Cache-directive" Content="no-cache">
<meta Http-Equiv="Pragma-directive" Content="no-cache">
<meta Http-Equiv="Cache-Control" Content="no-cache">
<meta Http-Equiv="Pragma" Content="no-cache">
<meta Http-Equiv="Expires" Content="0">
<meta Http-Equiv="Pragma-directive: no-cache">
<meta Http-Equiv="Cache-directive: no-cache">

Not sure what works on what Browser, but it does work for some: IE: Works when webpage is refreshed and when website is revisited (without a refresh). CHROME: Works only when webpage is refreshed (even after a revisit). SAFARI and iPad: Doesn't work, I have to clear the History & Web Data.

Any Ideas on SAFARI/ iPad?

How to convert jsonString to JSONObject in Java

you must import org.json

JSONObject jsonObj = null;
        try {
            jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
        } catch (JSONException e) {
            e.printStackTrace();
        }

Pandas merge two dataframes with different columns

I think in this case concat is what you want:

In [12]:

pd.concat([df,df1], axis=0, ignore_index=True)
Out[12]:
   attr_1  attr_2  attr_3  id  quantity
0       0       1     NaN   1        20
1       1       1     NaN   2        23
2       1       1     NaN   3        19
3       0       0     NaN   4        19
4       1     NaN       0   5         8
5       0     NaN       1   6        13
6       1     NaN       1   7        20
7       1     NaN       1   8        25

by passing axis=0 here you are stacking the df's on top of each other which I believe is what you want then producing NaN value where they are absent from their respective dfs.

Visual Studio Code: format is not using indent settings

Visual Studio Code detects the current indentation per default and uses this - ignoring the .editorconfig

Set also "editor.detectIndentation" to false

(Files -> Preferences -> Settings)

screenshot

How to get Enum Value from index in Java?

Try this

Months.values()[index]

How to read numbers separated by space using scanf

int main()
{
char string[200];
int g,a,i,G[20],A[20],met;

gets(string);
g=convert_input(G,string);

for(i=0;i<=g;i++)
    printf("\n%d>>%d",i,G[i]);
return 0;
}

int convert_input(int K[],char string[200])
{
int j=0,i=0,temp=0;
while(string[i]!='\0')
{
    temp=0;
    while(string[i]!=' ' && string[i]!='\0')
        temp=temp*10 + (string[i++]-'0') ;
    if(string[i]==' ')
        i++;
    K[j++]=temp;
}
return j-1;
}

How to know if other threads have finished?

Do you want to wait for them to finish? If so, use the Join method.

There is also the isAlive property if you just want to check it.

How to import popper.js?

Ways to get popper.js: Package, CDN, and Local file

The best way depends on whether you have a project with a package manager like npm.

Package manager
If you're using a package manager, use it to get popper.js like this:

npm install popper.js --save

CDN
For a prototype or playground environment (like http://codepen.io) or may just want a url to a CDN file:

https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.5/umd/popper.js https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.5/umd/popper.min.js

note: Bootstrap 4 requires the versions under the umd path (more info on popper/bs4).

Local file

Just save one of the CDN files to use locally. For example, paste one of these URLs in a browser, then Save As... to get a local copy.

https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.5/umd/popper.js https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.5/umd/popper.min.js

Timestamp to human readable format

use Date.prototype.toLocaleTimeString() as documented here

please note the locale example en-US in the url.

String escape into XML

Using a third-party library (Newtonsoft.Json) as alternative:

public static string XmlEscape(string unescaped)
{
    if (unescaped == null) return null;
    return JsonConvert.SerializeObject(unescaped); ;
}

public static string XmlUnescape(string escaped)
{
    if (escaped == null) return null;
    return JsonConvert.DeserializeObject(escaped, typeof(string)).ToString();
}

Examples of escaped string:

a<b ==> "a&lt;b"

<foo></foo> ==> "foo&gt;&lt;/foo&gt;"

NOTE: In newer versions, the code written above may not work with escaping, so you need to specify how the strings will be escaped:

public static string XmlEscape(string unescaped)
{
    if (unescaped == null) return null;
    return JsonConvert.SerializeObject(unescaped, new JsonSerializerSettings()
    {
        StringEscapeHandling = StringEscapeHandling.EscapeHtml
    });
}

Examples of escaped string:

a<b ==> "a\u003cb"

<foo></foo> ==> "\u003cfoo\u003e\u003c/foo\u003e"

Merge Cell values with PHPExcel - PHP

Try this

$objPHPExcel->getActiveSheet()->mergeCells('A1:C1');

How to disable GCC warnings for a few lines of code

It appears this can be done. I'm unable to determine the version of GCC that it was added, but it was sometime before June 2010.

Here's an example:

#pragma GCC diagnostic error "-Wuninitialized"
    foo(a);         /* error is given for this one */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
    foo(b);         /* no diagnostic for this one */
#pragma GCC diagnostic pop
    foo(c);         /* error is given for this one */
#pragma GCC diagnostic pop
    foo(d);         /* depends on command line options */

CSS word-wrapping in div

As Andrew said, your text should be doing just that.

There is one instance that I can think of that will behave in the manner you suggest, and that is if you have the whitespace property set.

See if you don't have the following in your CSS somewhere:

white-space: nowrap

That will cause text to continue on the same line until interrupted by a line break.

OK, my apologies, not sure if edited or added the mark-up afterwards (didn't see it at first).

The overflow-x property is what's causing the scroll bar to appear. Remove that and the div will adjust to as high as it needs to be to contain all your text.

How to remove all the occurrences of a char in c++ string

This is how I do it:

std::string removeAll(std::string str, char c) {
    size_t offset = 0;
    size_t size = str.size();

    size_t i = 0;
    while (i < size - offset) {
        if (str[i + offset] == c) {
            offset++;
        }

        if (offset != 0) {
            str[i] = str[i + offset];
        }

        i++;
    }

    str.resize(size - offset);
    return str;
}

Basically whenever I find a given char, I advance the offset and relocate the char to the correct index. I don't know if this is correct or efficient, I'm starting (yet again) at C++ and i'd appreciate any input on that.

How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

tar -cvzf filename.tar.gz directory_to_compress/

Most tar commands have a z option to create a gziped version.

Though seems to me the question is how to circumvent Google. I'm not sure if renaming your output file would fool Google, but you could try. I.e.,

tar -cvzf filename.bla directory_to_compress/

and then send the filename.bla - contents will would be a zipped tar, so at the other end it could be retrieved as usual.

SQL Server 2005 Setting a variable to the result of a select query

You could also just put the first SELECT in a subquery. Since most optimizers will fold it into a constant anyway, there should not be a performance hit on this.

Incidentally, since you are using a predicate like this:

CONVERT(...) = CONVERT(...)

that predicate expression cannot be optimized properly or use indexes on the columns reference by the CONVERT() function.

Here is one way to make the original query somewhat better:

DECLARE @ooDate datetime
SELECT @ooDate = OO.Date FROM OLAP.OutageHours AS OO where OO.OutageID = 1

SELECT 
  COUNT(FF.HALID)
FROM
  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
    FF.HALID = OFIO.HALID 
WHERE
  FF.FaultDate >= @ooDate AND
  FF.FaultDate < DATEADD(day, 1, @ooDate) AND
  OFIO.OutageID = 1

This version could leverage in index that involved FaultDate, and achieves the same goal.

Here it is, rewritten to use a subquery to avoid the variable declaration and subsequent SELECT.

SELECT 
  COUNT(FF.HALID)
FROM
  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
    FF.HALID = OFIO.HALID 
WHERE
  CONVERT(varchar(10), FF.FaultDate, 126) = (SELECT CONVERT(varchar(10), OO.Date, 126) FROM OLAP.OutageHours AS OO where OO.OutageID = 1) AND
  OFIO.OutageID = 1

Note that this approach has the same index usage issue as the original, because of the use of CONVERT() on FF.FaultDate. This could be remedied by adding the subquery twice, but you would be better served with the variable approach in this case. This last version is only for demonstration.

Regards.

How to apply multiple transforms in CSS?

You can apply more than one transform like this:

li:nth-of-type(2){
    transform : translate(-20px, 0px) rotate(15deg);
}

Two values from one input in python?

a,b=[int(x) for x in input().split()]
print(a,b)

Output

10 8

10 8

How to add font-awesome to Angular 2 + CLI project

Many instructions above work, I suggest looking at those. However, something to note:

Using <i class="fas fa-coffee"></i> did not work in my project (new practice project only a week old) after installation and the sample icon here was also copied to the clipboard from Font Awesome within the past week.

This<i class="fa fa-coffee"></i> does work. If after installing Font Awesome on your project it isn't yet working, I suggest checking the class on your icon to remove the 's' to see if it works then.

CSS position:fixed inside a positioned element

I know this is an old post but I had the same question but didn't find an answer that set the element fixed relative to a parent div. The scroll bar on medium.com is a great pure CSS solution for setting something position: fixed; relative to a parent element instead of the viewport (kinda*). It is achieved by setting the parent div to position: relative; and having a button wrapper with position: absolute; and the button of course is position: fixed; as follows:

<div class="wrapper">
  <div class="content">
    Your long content here
  </div>

  <div class="button-wrapper">
    <button class="button">This is your button</button>
  </div>
</div>

<style>
  .wrapper {
    position: relative;
  }

  .button-wrapper {
    position: absolute;
    right: 0;
    top: 0;
    width: 50px;
  }

  .button {
    position: fixed;
    top: 0;
    width: 50px;
  }
</style>

working example

*Since fixed elements don't scroll with the page the vertical position will still be relative to the viewport but the horizontal position is relative to the parent with this solution.

How to test enum types?

Usually I would say it is overkill, but there are occasionally reasons for writing unit tests for enums.

Sometimes the values assigned to enumeration members must never change or the loading of legacy persisted data will fail. Similarly, apparently unused members must not be deleted. Unit tests can be used to guard against a developer making changes without realising the implications.

How to $watch multiple variable change in angular

No one has mentioned the obvious:

var myCallback = function() { console.log("name or age changed"); };
$scope.$watch("name", myCallback);
$scope.$watch("age", myCallback);

This might mean a little less polling. If you watch both name + age (for this) and name (elsewhere) then I assume Angular will effectively look at name twice to see if it's dirty.

It's arguably more readable to use the callback by name instead of inlining it. Especially if you can give it a better name than in my example.

And you can watch the values in different ways if you need to:

$scope.$watch("buyers", myCallback, true);
$scope.$watchCollection("sellers", myCallback);

$watchGroup is nice if you can use it, but as far as I can tell, it doesn't let you watch the group members as a collection or with object equality.

If you need the old and new values of both expressions inside one and the same callback function call, then perhaps some of the other proposed solutions are more convenient.

Difference between "enqueue" and "dequeue"

Enqueue means to add an element, dequeue to remove an element.

var stackInput= []; // First stack
var stackOutput= []; // Second stack

// For enqueue, just push the item into the first stack
function enqueue(stackInput, item) {
  return stackInput.push(item);
}

function dequeue(stackInput, stackOutput) {
  // Reverse the stack such that the first element of the output stack is the
  // last element of the input stack. After that, pop the top of the output to
  // get the first element that was ever pushed into the input stack
  if (stackOutput.length <= 0) {
    while(stackInput.length > 0) {
      var elementToOutput = stackInput.pop();
      stackOutput.push(elementToOutput);
    }
  }

  return stackOutput.pop();
}

How do I extract value from Json

String jsonErrorString=((HttpClientErrorException)exception).getResponseBodyAsString();
JSONObject jsonObj=null;
String errorDetails=null;
String status=null;
try {
        jsonObj = new JSONObject(jsonErrorString);
        int index =jsonObj.getString("detail").indexOf(":");
                errorDetails=jsonObj.getString("detail").substring(index);
                status=jsonObj.getString("status");

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            item.put("status", status);
            item.put("errordetailMsg", errorDetails);

How to provide user name and password when connecting to a network share

If you can't create an locally valid security token, it seems like you've ruled all out every option bar Win32 API and WNetAddConnection*.

Tons of information on MSDN about WNet - PInvoke information and sample code that connects to a UNC path here:

http://www.pinvoke.net/default.aspx/mpr/WNetAddConnection2.html#

MSDN Reference here:

http://msdn.microsoft.com/en-us/library/aa385391(VS.85).aspx