Programs & Examples On #Change password

This tag refers to the process of setting a new password on a system, thereby making the old password obsolete and no longer usable.

How do I turn off the mysql password validation?

Further to the answer from ktbos:

I modified the mysqld.cnf file and mysql failed to start. It turned out that I was modifying the wrong file!

So be sure the file you modify contains segment tags like [mysqld_safe] and [mysqld]. Under the latter I did as suggested and added the line:

validate_password_policy=LOW

This worked perfectly to resolve my issue of not requiring special characters within the password.

Git credential helper - update password

Solution using command line for Windows, Linux, and MacOS

If you have updated your GitHub password on the GitHub server, in the first attempt of the git fetch/pull/push command it generates the authentication failed message.

Execute the same git fetch/pull/push command a second time and it prompts for credentials (username and password). Enter the username and the new updated password of the GitHub server and login will be successful.

Even I had this problem, and I performed the above steps and done!!

PostgreSQL: How to change PostgreSQL user password?

If you are on windows.

Open pg_hba.conf file and change from md5 to peer

Open cmd, type psql postgres postgres

Then type \password to be prompted for a new password.

Refer to this medium post for further information & granular steps.

How do I update the password for Git?

I was able to change my git password by going to Credential Manager in Windows and deleting all the git entries under Windows Credentials Generic Credentials.

When doing a git pull or git push, windows will ask for the new user/password itself.

How does jQuery work when there are multiple elements with the same ID value?

If you have multiple elements with same id or same name, just assign same class to those multiple elements and access them by index & perform your required operation.

  <div>
        <span id="a" class="demo">1</span>
        <span id="a" class="demo">2</span>
        <span>3</span>
    </div>

JQ:

$($(".demo")[0]).val("First span");
$($(".demo")[1]).val("Second span");

Define global variable with webpack

You can use define window.myvar = {}. When you want to use it, you can use like window.myvar = 1

Getting the SQL from a Django QuerySet

The accepted answer did not work for me when using Django 1.4.4. Instead of the raw query, a reference to the Query object was returned: <django.db.models.sql.query.Query object at 0x10a4acd90>.

The following returned the query:

>>> queryset = MyModel.objects.all()
>>> queryset.query.__str__()

Angular 2 / 4 / 5 - Set base href dynamically

I just changed:

  <base href="/">

to this:

  <base href="/something.html/">

don't forget ending with /

ansible: lineinfile for several lines?

You can use a loop to do it. Here's an example using a with_items loop:

- name: Set some kernel parameters
  lineinfile:
    dest: /etc/sysctl.conf
    regexp: "{{ item.regexp }}"
    line: "{{ item.line }}"
  with_items:
    - { regexp: '^kernel.shmall', line: 'kernel.shmall = 2097152' }
    - { regexp: '^kernel.shmmax', line: 'kernel.shmmax = 134217728' }
    - { regexp: '^fs.file-max', line: 'fs.file-max = 65536' }

Where value in column containing comma delimited values

select *
from YourTable
where ','+replace(col, ' ', '')+',' like '%,Cat,%'

How to See the Contents of Windows library (*.lib)

DUMPBIN /EXPORTS Will get most of that information and hitting MSDN will get the rest.

Get one of the Visual Studio packages; C++

How to block users from closing a window in Javascript?

If your sending out an internal survey that requires 100% participation from your company's employees, then a better route would be to just have the form keep track of the responders ID/Username/email etc. Every few days or so just send a nice little email reminder to those in your organization to complete the survey...you could probably even automate this.

How to enter a multi-line command

I started by doing

if ($true) {
"you can write multiple lines here, and the command doesn't run untill you close the bracket"

"like this"
}

Recently found out I could just

&{
get-date
"more stuff"
}

Rolling back local and remote git repository by 1 commit

If you want revert last commit listen:

Step 1:

Check your local commits with messages

$ git log

Step 2:

Remove last commit without resetting the changes from local branch (or master)

$ git reset HEAD^

OR if you don't want last commit files and updates listens

$ git reset HEAD^ --hard

Step 3:

We can update the files and codes and again need to push with force it will delete previous commit. It will keep new commit.

$ git push origin branch -f

That's it!

Get property value from string using reflection

The following code is a Recursive method for displaying the entire hierarchy of all of the Property Names and Values contained in an object's instance. This method uses a simplified version of AlexD's GetPropertyValue() answer above in this thread. Thanks to this discussion thread, I was able to figure out how to do this!

For example, I use this method to show an explosion or dump of all of the properties in a WebService response by calling the method as follows:

PropertyValues_byRecursion("Response", response, false);

public static object GetPropertyValue(object srcObj, string propertyName)
{
  if (srcObj == null) 
  {
    return null; 
  }
  PropertyInfo pi = srcObj.GetType().GetProperty(propertyName.Replace("[]", ""));
  if (pi == null)
  {
    return null;
  }
  return pi.GetValue(srcObj);
}

public static void PropertyValues_byRecursion(string parentPath, object parentObj, bool showNullValues)
{
  /// Processes all of the objects contained in the parent object.
  ///   If an object has a Property Value, then the value is written to the Console
  ///   Else if the object is a container, then this method is called recursively
  ///       using the current path and current object as parameters

  // Note:  If you do not want to see null values, set showNullValues = false

  foreach (PropertyInfo pi in parentObj.GetType().GetTypeInfo().GetProperties())
  {
    // Build the current object property's namespace path.  
    // Recursion extends this to be the property's full namespace path.
    string currentPath = parentPath + "." + pi.Name;

    // Get the selected property's value as an object
    object myPropertyValue = GetPropertyValue(parentObj, pi.Name);
    if (myPropertyValue == null)
    {
      // Instance of Property does not exist
      if (showNullValues)
      {
        Console.WriteLine(currentPath + " = null");
        // Note: If you are replacing these Console.Write... methods callback methods,
        //       consider passing DBNull.Value instead of null in any method object parameters.
      }
    }
    else if (myPropertyValue.GetType().IsArray)
    {
      // myPropertyValue is an object instance of an Array of business objects.
      // Initialize an array index variable so we can show NamespacePath[idx] in the results.
      int idx = 0;
      foreach (object business in (Array)myPropertyValue)
      {
        if (business == null)
        {
          // Instance of Property does not exist
          // Not sure if this is possible in this context.
          if (showNullValues)
          {
            Console.WriteLine(currentPath  + "[" + idx.ToString() + "]" + " = null");
          }
        }
        else if (business.GetType().IsArray)
        {
          // myPropertyValue[idx] is another Array!
          // Let recursion process it.
          PropertyValues_byRecursion(currentPath + "[" + idx.ToString() + "]", business, showNullValues);
        }
        else if (business.GetType().IsSealed)
        {
          // Display the Full Property Path and its Value
          Console.WriteLine(currentPath + "[" + idx.ToString() + "] = " + business.ToString());
        }
        else
        {
          // Unsealed Type Properties can contain child objects.
          // Recurse into my property value object to process its properties and child objects.
          PropertyValues_byRecursion(currentPath + "[" + idx.ToString() + "]", business, showNullValues);
        }
        idx++;
      }
    }
    else if (myPropertyValue.GetType().IsSealed)
    {
      // myPropertyValue is a simple value
      Console.WriteLine(currentPath + " = " + myPropertyValue.ToString());
    }
    else
    {
      // Unsealed Type Properties can contain child objects.
      // Recurse into my property value object to process its properties and child objects.
      PropertyValues_byRecursion(currentPath, myPropertyValue, showNullValues);
    }
  }
}

How to sleep the thread in node.js without affecting other threads?

When working with async functions or observables provided by 3rd party libraries, for example Cloud firestore, I've found functions the waitFor method shown below (TypeScript, but you get the idea...) to be helpful when you need to wait on some process to complete, but you don't want to have to embed callbacks within callbacks within callbacks nor risk an infinite loop.

This method is sort of similar to a while (!condition) sleep loop, but yields asynchronously and performs a test on the completion condition at regular intervals till true or timeout.

export const sleep = (ms: number) => {
    return new Promise(resolve => setTimeout(resolve, ms))
}
/**
 * Wait until the condition tested in a function returns true, or until 
 * a timeout is exceeded.
 * @param interval The frenequency with which the boolean function contained in condition is called.
 * @param timeout  The maximum time to allow for booleanFunction to return true
 * @param booleanFunction:  A completion function to evaluate after each interval. waitFor will return true as soon as the completion function returns true.   
 */
export const waitFor = async function (interval: number, timeout: number,
    booleanFunction: Function): Promise<boolean> {
    let elapsed = 1;
    if (booleanFunction()) return true;
    while (elapsed < timeout) {
        elapsed += interval;
        await sleep(interval);
        if (booleanFunction()) {
            return true;
        }
    }
    return false;
}

The say you have a long running process on your backend you want to complete before some other task is undertaken. For example if you have a function that totals a list of accounts, but you want to refresh the accounts from the backend before you calculate, you can do something like this:

async recalcAccountTotals() : number {
     this.accountService.refresh();   //start the async process.
     if (this.accounts.dirty) {
           let updateResult = await waitFor(100,2000,()=> {return !(this.accounts.dirty)})
     }
 if(!updateResult) { 
      console.error("Account refresh timed out, recalc aborted");
      return NaN;
    }
 return ... //calculate the account total. 
}

Add a "sort" to a =QUERY statement in Google Spreadsheets

Sorting by C and D needs to be put into number form for the corresponding column, ie 3 and 4, respectively. Eg Order By 2 asc")

Parse an URL in JavaScript

I wrote a javascript url parsing library, URL.js, you can use it for this.

Example:

url.parse("http://mysite.com/form_image_edit.php?img_id=33").get.img_id === "33"

How to call controller from the button click in asp.net MVC 4

You are mixing razor and aspx syntax,if your view engine is razor just do this:

<button class="btn btn-info" type="button" id="addressSearch"   
          onclick="location.href='@Url.Action("List", "Search")'">

How to see the actual Oracle SQL statement that is being executed

-- i use something like this, with concepts and some code stolen from asktom.
-- suggestions for improvements are welcome

WITH
sess AS
(
SELECT *
FROM V$SESSION
WHERE USERNAME = USER
ORDER BY SID
)
SELECT si.SID,
si.LOCKWAIT,
si.OSUSER,
si.PROGRAM,
si.LOGON_TIME,
si.STATUS,
(
SELECT ROUND(USED_UBLK*8/1024,1)
FROM V$TRANSACTION,
sess
WHERE sess.TADDR = V$TRANSACTION.ADDR
AND sess.SID = si.SID

) rollback_remaining,

(
SELECT (MAX(DECODE(PIECE, 0,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 1,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 2,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 3,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 4,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 5,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 6,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 7,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 8,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 9,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 10,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 11,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 12,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 13,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 14,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 15,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 16,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 17,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 18,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 19,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 20,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 21,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 22,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 23,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 24,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 25,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 26,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 27,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 28,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 29,SQL_TEXT,NULL)))
FROM V$SQLTEXT_WITH_NEWLINES
WHERE ADDRESS = SI.SQL_ADDRESS AND
PIECE < 30
) SQL_TEXT
FROM sess si;

How do I link to part of a page? (hash?)

Provided that any element has the id attribute on a webpage. One could simply link/jump to the element that is referenced by the tag.

Within the same page:

<div id="markOne"> ..... </div> 
   ......
<a href="#markOne">Jump to markOne</a> 

Other page:

<div id="http://randomwebsite.com/mypage.html#markOne"> 
  Jumps to the markOne element in the mypage of the linked website
</div>

The targets don't necessarily have an anchor element.

You can go check this fiddle out.

remote: repository not found fatal: not found

Please find below the working solution for Windows: It worked for me. 1 Open Control Panel from the Start menu. 2 Select User Accounts. 3 Select the "Credential Manager". 4 Click on "Manage Windows Credentials". 5 Delete any credentials related to Git or GitHub. 6 Once you deleted all then try to clone again.

Check if Internet Connection Exists with jQuery?

Sending XHR requests is bad because it could fail if that particular server is down. Instead, use googles API library to load their cached version(s) of jQuery.

You can use googles API to perform a callback after loading jQuery, and this will check if jQuery was loaded successfully. Something like the code below should work:

<script type="text/javascript">
    google.load("jquery");

    // Call this function when the page has been loaded
    function test_connection() {
        if($){
            //jQuery WAS loaded.
        } else {
            //jQuery failed to load.  Grab the local copy.
        }
    }
    google.setOnLoadCallback(test_connection);
</script>

The google API documentation can be found here.

Does HTML5 <video> playback support the .avi format?

There are three formats with a reasonable level of support: H.264 (MPEG-4 AVC), OGG Theora (VP3) and WebM (VP8). See the wiki linked by Sam for which browsers support which; you will typically need at least one of those plus Flash fallback.

Whilst most browsers won't touch AVI, there are some browser builds that expose all the multimedia capabilities of the underlying OS to <video>. These browser will indeed be able to play AVI, as long as they have matching codecs installed (AVI can contain about a million different video and audio formats). In particular Safari on OS X with QuickTime, or Konqi with GStreamer.

Personally I think this is an absolutely disastrous idea, as it exposes a very large codec codebase to the net, a codebase that was mostly not written to be resistant to network attacks. One of the worst drawbacks of media player plugins was the huge number of security holes they made available to every web page exploit. Let's not make this mistake again.

What is the difference between a URI, a URL and a URN?

From RFC 3986:

A URI can be further classified as a locator, a name, or both. The term "Uniform Resource Locator" (URL) refers to the subset of URIs that, in addition to identifying a resource, provide a means of locating the resource by describing its primary access mechanism (e.g., its network "location"). The term "Uniform Resource Name" (URN) has been used historically to refer to both URIs under the "urn" scheme [RFC2141], which are required to remain globally unique and persistent even when the resource ceases to exist or becomes unavailable, and to any other URI with the properties of a name.

So all URLs are URIs, and all URNs are URIs - but URNs and URLs are different, so you can't say that all URIs are URLs.

If you haven't already read Roger Pate's answer, I'd advise doing so as well.

How to change bower's default components folder?

Try putting the components.json file in the public directory of your application, rather than the root directory, then re-run bower install ...try this in your app home directory:

cp components.json public
cd public
bower install

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

you must be using old version of wget i had same issue. i was using wget 1.12.so to solve this issue there are 2 way: Update wget or use curl

curl -LO 'https://example.com/filename.tar.gz'

Which websocket library to use with Node.js?

Update: This answer is outdated as newer versions of libraries mentioned are released since then.

Socket.IO v0.9 is outdated and a bit buggy, and Engine.IO is the interim successor. Socket.IO v1.0 (which will be released soon) will use Engine.IO and be much better than v0.9. I'd recommend you to use Engine.IO until Socket.IO v1.0 is released.

"ws" does not support fallback, so if the client browser does not support websockets, it won't work, unlike Socket.IO and Engine.IO which uses long-polling etc if websockets are not available. However, "ws" seems like the fastest library at the moment.

See my article comparing Socket.IO, Engine.IO and Primus: https://medium.com/p/b63bfca0539

pandas dataframe create new columns and fill with calculated values from same df

You can do this easily manually for each column like this:

df['A_perc'] = df['A']/df['sum']

If you want to do this in one step for all columns, you can use the div method (http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior):

ds.div(ds['sum'], axis=0)

And if you want this in one step added to the same dataframe:

>>> ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc')
          A         B         C         D       sum    A_perc    B_perc  \
1  0.151722  0.935917  1.033526  0.941962  3.063127  0.049532  0.305543   
2  0.033761  1.087302  1.110695  1.401260  3.633017  0.009293  0.299283   
3  0.761368  0.484268  0.026837  1.276130  2.548603  0.298739  0.190013   

     C_perc    D_perc  sum_perc  
1  0.337409  0.307517         1  
2  0.305722  0.385701         1  
3  0.010530  0.500718         1  

Add animated Gif image in Iphone UIImageView

Check this link

https://github.com/mayoff/uiimage-from-animated-gif/blob/master/uiimage-from-animated-gif/UIImage%2BanimatedGIF.h

and import these clases UIImage+animatedGIF.h,UIImage+animatedGIF.m

Use this code

 NSURL *urlZif = [[NSBundle mainBundle] URLForResource:@"dots64" withExtension:@"gif"];
 NSString *path=[[NSBundle mainBundle]pathForResource:@"bar180" ofType:@"gif"];
 NSURL *url=[[NSURL alloc] initFileURLWithPath:path];
 imageVw.image= [UIImage animatedImageWithAnimatedGIFURL:url];

Hope this is helpfull

Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central?

Solution 1: configure Java 7

It is need to enable TLS 1.2 protocol with Java property in the command line

mvn -Dhttps.protocols=TLSv1.2 install

install is just an example of a goal

The same error for ant can be solved by this way

java -Dhttps.protocols=TLSv1.2 -cp %ANT_HOME%/lib/ant-launcher.jar org.apache.tools.ant.launch.Launcher

Solution 2: use Java 7 with Oracle Advanced Support

Also problem can be solved by updating the Java 7 version. But the last available version (7u80) doesn't fix the problem. It is need to use an update provided with Oracle Advanced Support (formerly known as Java for Business).

Solution 3: use Java 8 instead

Configure $JAVA_HOME to point to Java 8.

How to convert hex strings to byte values in Java

Since there was no answer for hex string to single byte conversion, here is mine:

private static byte hexStringToByte(String data) {
    return (byte) ((Character.digit(data.charAt(0), 16) << 4)
                  | Character.digit(data.charAt(1), 16));
}

Sample usage:

hexStringToByte("aa"); // 170
hexStringToByte("ff"); // 255
hexStringToByte("10"); // 16

Or you can also try the Integer.parseInt(String number, int radix) imo, is way better than others.

// first parameter is a number represented in string
// second is the radix or the base number system to be use
Integer.parseInt("de", 16); // 222
Integer.parseInt("ad", 16); // 173
Integer.parseInt("c9", 16); // 201

Node.js + Nginx - What now?

The best and simpler setup with Nginx and Nodejs is to use Nginx as an HTTP and TCP load balancer with proxy_protocol enabled. In this context, Nginx will be able to proxy incoming requests to nodejs, and also terminate SSL connections to the backend Nginx server(s), and not to the proxy server itself. (SSL-PassThrough)

In my opinion, there is no point in giving non-SSL examples, since all web apps are (or should be) using secure environments.

Example config for the proxy server, in /etc/nginx/nginx.conf

user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
events {
    worker_connections  1024;
}
http {
  upstream webserver-http {
    server 192.168.1.4; #use a host port instead if using docker
    server 192.168.1.5; #use a host port instead if using docker
  }
  upstream nodejs-http {
    server 192.168.1.4:8080; #nodejs listening port
    server 192.168.1.5:8080; #nodejs listening port
  }
  server {
    server_name example.com;
    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Host $http_host;
      proxy_set_header X-Forwarded-Host $server_name;
      proxy_set_header Connection "";
      add_header       X-Upstream $upstream_addr;
      proxy_redirect     off;
      proxy_connect_timeout  300;
      proxy_http_version 1.1;
      proxy_buffers 16 16k;
      proxy_buffer_size 16k;
      proxy_cache_background_update on;
      proxy_pass http://webserver-http$request_uri;
    }
  }
  server {
    server_name node.example.com;
    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Host $http_host;
      proxy_set_header X-Forwarded-Host $server_name;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "Upgrade";
      add_header       X-Upstream $upstream_addr;
      proxy_redirect     off;
      proxy_connect_timeout  300;
      proxy_http_version 1.1;
      proxy_buffers 16 16k;
      proxy_buffer_size 16k;
      proxy_cache_background_update on;
      proxy_pass http://nodejs-http$request_uri;
    }
  }
}
stream {
  upstream webserver-https {
    server 192.168.1.4:443; #use a host port instead if using docker
    server 192.168.1.5:443; #use a host port instead if using docker
  }

  server {
    proxy_protocol on;
    tcp_nodelay on;
    listen 443;
    proxy_pass webserver-https;
  }
  log_format proxy 'Protocol: $protocol - $status $bytes_sent $bytes_received $session_time';
  access_log  /var/log/nginx/access.log proxy;
  error_log /var/log/nginx/error.log debug;
}

Now, let's handle the backend webserver. /etc/nginx/nginx.conf:

user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
load_module /etc/nginx/modules/ngx_http_geoip2_module.so; # GeoIP2
events {
    worker_connections  1024;
}
http {
    variables_hash_bucket_size 64;
    variables_hash_max_size 2048;
    server_tokens off;
    sendfile    on;
    tcp_nopush  on;
    tcp_nodelay on;
    autoindex off;
    keepalive_timeout  30;
    types_hash_bucket_size 256;
    client_max_body_size 100m;
    server_names_hash_bucket_size 256;
    include         mime.types;
    default_type    application/octet-stream;
    index  index.php index.html index.htm;
    # GeoIP2
    log_format  main    'Proxy Protocol Address: [$proxy_protocol_addr] '
                        '"$request" $remote_addr - $remote_user [$time_local] "$request" '
                        '$status $body_bytes_sent "$http_referer" '
                        '"$http_user_agent" "$http_x_forwarded_for"';

    # GeoIP2
    log_format  main_geo    'Original Client Address: [$realip_remote_addr]- Proxy Protocol Address: [$proxy_protocol_addr] '
                            'Proxy Protocol Server Address:$proxy_protocol_server_addr - '
                            '"$request" $remote_addr - $remote_user [$time_local] "$request" '
                            '$status $body_bytes_sent "$http_referer" '
                            '$geoip2_data_country_iso $geoip2_data_country_name';

    access_log  /var/log/nginx/access.log  main_geo; # GeoIP2
#===================== GEOIP2 =====================#
    geoip2 /usr/share/geoip/GeoLite2-Country.mmdb {
        $geoip2_metadata_country_build  metadata build_epoch;
        $geoip2_data_country_geonameid  country geoname_id;
        $geoip2_data_country_iso        country iso_code;
        $geoip2_data_country_name       country names en;
        $geoip2_data_country_is_eu      country is_in_european_union;
    }
    #geoip2 /usr/share/geoip/GeoLite2-City.mmdb {
    #   $geoip2_data_city_name city names en;
    #   $geoip2_data_city_geonameid city geoname_id;
    #   $geoip2_data_continent_code continent code;
    #   $geoip2_data_continent_geonameid continent geoname_id;
    #   $geoip2_data_continent_name continent names en;
    #   $geoip2_data_location_accuracyradius location accuracy_radius;
    #   $geoip2_data_location_latitude location latitude;
    #   $geoip2_data_location_longitude location longitude;
    #   $geoip2_data_location_metrocode location metro_code;
    #   $geoip2_data_location_timezone location time_zone;
    #   $geoip2_data_postal_code postal code;
    #   $geoip2_data_rcountry_geonameid registered_country geoname_id;
    #   $geoip2_data_rcountry_iso registered_country iso_code;
    #   $geoip2_data_rcountry_name registered_country names en;
    #   $geoip2_data_rcountry_is_eu registered_country is_in_european_union;
    #   $geoip2_data_region_geonameid subdivisions 0 geoname_id;
    #   $geoip2_data_region_iso subdivisions 0 iso_code;
    #   $geoip2_data_region_name subdivisions 0 names en;
   #}

#=================Basic Compression=================#
    gzip on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/css text/xml text/plain application/javascript image/jpeg image/png image/gif image/x-icon image/svg+xml image/webp application/font-woff application/json application/vnd.ms-fontobject application/vnd.ms-powerpoint;
    gzip_static on;
    
    include /etc/nginx/sites-enabled/example.com-https.conf;
}

Now, let's configure the virtual host with this SSL and proxy_protocol enabled config at /etc/nginx/sites-available/example.com-https.conf:

server {
    real_ip_header proxy_protocol;
    set_real_ip_from 192.168.1.1; #proxy server ip address
    #set_real_ip_from proxy; #proxy container hostname if you are using docker
    server_name 192.168.1.4; #Your current server ip address. It will redirect to the domain name.
    listen 80;
    listen 443 ssl http2;
    listen [::]:80;
    listen [::]:443 ssl http2;
    ssl_certificate     /etc/nginx/certs/example.com.crt;
    ssl_certificate_key /etc/nginx/certs/example.com.key;
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;
    return 301 https://example.com$request_uri;
}
server {
    real_ip_header proxy_protocol;
    set_real_ip_from 192.168.1.1; #proxy server ip address
    #set_real_ip_from proxy; #proxy container hostname if you are using docker
    server_name  example.com;
    listen       *:80;
    return 301   https://example.com$request_uri;
}
server {
    real_ip_header proxy_protocol;
    set_real_ip_from 192.168.1.1; #proxy server ip address
    #set_real_ip_from proxy; #proxy container hostname if you are using docker
    server_name www.example.com;
    listen 80;
    listen 443 http2;
    listen [::]:80;
    listen [::]:443 ssl http2 ;
    ssl_certificate     /etc/nginx/certs/example.com.crt;
    ssl_certificate_key /etc/nginx/certs/example.com.key;
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;
    return 301 https://example.com$request_uri;
}
server {
    real_ip_header proxy_protocol;
    set_real_ip_from 192.168.1.1; #proxy server ip address
    #set_real_ip_from proxy; #proxy container hostname if you are using docker
    server_name example.com;
    listen 443 proxy_protocol ssl http2;
    listen [::]:443 proxy_protocol ssl http2;
    root /var/www/html;
    charset UTF-8;
    add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains; preload';
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Referrer-Policy no-referrer;
    ssl_prefer_server_ciphers on;
    ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
    ssl_protocols TLSv1.2 TLSv1.1 TLSv1;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    keepalive_timeout   70;
    ssl_buffer_size 1400;
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=86400;
    resolver_timeout 10;
    ssl_certificate     /etc/nginx/certs/example.com.crt;
    ssl_certificate_key /etc/nginx/certs/example.com.key;
    ssl_trusted_certificate /etc/nginx/certs/example.com.crt;
location ~* \.(jpg|jpe?g|gif|png|ico|cur|gz|svgz|mp4|ogg|ogv|webm|htc|css|js|otf|eot|svg|ttf|woff|woff2)(\?ver=[0-9.]+)?$ {
    expires modified 1M;
    add_header Access-Control-Allow-Origin '*';
    add_header Pragma public;
    add_header Cache-Control "public, must-revalidate, proxy-revalidate";
    access_log off;
    }
    location ~ /.well-known { #For issuing LetsEncrypt Certificates
        allow all;
    }
location / {
    index index.php;
    try_files $uri $uri/ /index.php?$args;
    }
error_page  404    /404.php;

location ~ \.php$ {
    try_files       $uri =404;
    fastcgi_index   index.php;
    fastcgi_pass    unix:/tmp/php7-fpm.sock;
    #fastcgi_pass    php-container-hostname:9000; (if using docker)
    fastcgi_pass_request_headers on;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_param   SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    fastcgi_intercept_errors on;
    fastcgi_ignore_client_abort off;
    fastcgi_connect_timeout 60;
    fastcgi_send_timeout 180;
    fastcgi_read_timeout 180;
    fastcgi_request_buffering on;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 4 256k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    include fastcgi_params;
}
location = /robots.txt {
    access_log off;
    log_not_found off;
    }
location ~ /\. {
    deny  all;
    access_log off;
    log_not_found off;
    }
}

And lastly, a sample of 2 nodejs webservers: First server:

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello From Nodejs\n');
}).listen(8080, "192.168.1.4");
console.log('Server running at http://192.168.1.4:8080/');

Second server:

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello From Nodejs\n');
}).listen(8080, "192.168.1.5");
console.log('Server running at http://192.168.1.5:8080/');

Now everything should be perfectly working and load-balanced.

A while back i wrote about How to set up Nginx as a TCP load balancer in Docker. Check it out if you are using Docker.

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

Change key in Project > Build Setting "typecheck calls to printf/scanf : NO"

Explanation : [How it works]

Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense.

Hope it work

Other warning

objective c implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int

Change key "implicit conversion to 32Bits Type > Debug > *64 architecture : No"

[caution: It may void other warning of 64 Bits architecture conversion].

Solve error javax.mail.AuthenticationFailedException

If you are logging in to your gmail account from a new application or device, Google might be blocking that device. Try following these steps:

To protect your account, Google might make it harder to sign in to your account if we suspect it isn’t you. For example, Google might ask for additional information besides your username and password if you are traveling or if you try to sign in to your account from a new device.

Go to https://g.co/allowaccess from a different device you have previously used to access your Google account and follow the instructions. Try signing in again from the blocked app.

What is the difference between Trap and Interrupt?

A trap is a special kind of interrupt which is commonly referred to as a software interrupt. An interrupt is a more general term which covers both hardware interrupts (interrupts from hardware devices) and software interrupts (interrupts from software, such as traps).

Import cycle not allowed

I just encountered this. You may be accessing a method/type from within the same package using the package name itself.

Here is an example to illustrate what I mean:

In foo.go:

// foo.go
package foo

func Foo() {...}

In foo_test.go:

// foo_test.go
package foo

// try to access Foo()
foo.Foo() // WRONG <== This was the issue. You are already in package foo, there is no need to use foo.Foo() to access Foo()
Foo() // CORRECT

Is it wrong to place the <script> tag after the </body> tag?

Yes. But if you do add the code outside it most likely will not be the end of the world since most browsers will fix it, but it is still a bad practice to get into.

mysqldump data only

Try to dump to a delimited file.

mysqldump -u [username] -p -t -T/path/to/directory [database] --fields-enclosed-by=\" --fields-terminated-by=,

How can I create a Java method that accepts a variable number of arguments?

The following will create a variable length set of arguments of the type of string:

print(String arg1, String... arg2)

You can then refer to arg2 as an array of Strings. This is a new feature in Java 5.

How to set a cell to NaN in a pandas dataframe

You can use replace:

df['y'] = df['y'].replace({'N/A': np.nan})

Also be aware of the inplace parameter for replace. You can do something like:

df.replace({'N/A': np.nan}, inplace=True)

This will replace all instances in the df without creating a copy.

Similarly, if you run into other types of unknown values such as empty string or None value:

df['y'] = df['y'].replace({'': np.nan})

df['y'] = df['y'].replace({None: np.nan})

Reference: Pandas Latest - Replace

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

How to create a QR code reader in a HTML5 website?

Reader they show at http://www.webqr.com/index.html works like a charm, but literaly, you need the one on the webpage, the github version it's really hard to make it work, however, it is possible. The best way to go is reverse-engineer the example shown at the webpage.

However, to edit and get the full potential out of it, it's not so easy. At some point I may post the stripped-down reverse-engineered QR reader, but in the meantime have some fun hacking the code.

Happy coding.

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

Best way to create a simple python web service

Life is simple if you get a good web framework. Web services in Django are easy. Define your model, write view functions that return your CSV documents. Skip the templates.

How to split strings into text and number?

I'm always the one to bring up findall() =)

>>> strings = ['foofo21', 'bar432', 'foobar12345']
>>> [re.findall(r'(\w+?)(\d+)', s)[0] for s in strings]
[('foofo', '21'), ('bar', '432'), ('foobar', '12345')]

Note that I'm using a simpler (less to type) regex than most of the previous answers.

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

Where is adb.exe in windows 10 located?

Got it to work go to the local.properties file under your build.gradle files to find out the PATH to your SDK, from the SDK location go into the platform-tools folder and look and see if you have adb.exe.

If not go to http://adbshell.com/downloads and download ADB KITS. Copy the zip folder's contents into the platform-tools folder and re-make your project.

I didn't need to update the PATH in the Extended Controls Settings section on the emulator, I left Use detected ADB location settings on. Hope this makes this faster for you !

Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

Your example data does not have any duplicates, but your solution handle them automatically. This means that potentially some of the answers won't match to results of your function in case of duplicates.
Here is my solution which address duplicates the same way as yours. It also scales great!

a1 <- data.frame(a = 1:5, b=letters[1:5])
a2 <- data.frame(a = 1:3, b=letters[1:3])
rows.in.a1.that.are.not.in.a2  <- function(a1,a2)
{
    a1.vec <- apply(a1, 1, paste, collapse = "")
    a2.vec <- apply(a2, 1, paste, collapse = "")
    a1.without.a2.rows <- a1[!a1.vec %in% a2.vec,]
    return(a1.without.a2.rows)
}

library(data.table)
setDT(a1)
setDT(a2)

# no duplicates - as in example code
r <- fsetdiff(a1, a2)
all.equal(r, rows.in.a1.that.are.not.in.a2(a1,a2))
#[1] TRUE

# handling duplicates - make some duplicates
a1 <- rbind(a1, a1, a1)
a2 <- rbind(a2, a2, a2)
r <- fsetdiff(a1, a2, all = TRUE)
all.equal(r, rows.in.a1.that.are.not.in.a2(a1,a2))
#[1] TRUE

It needs data.table 1.9.8+

Extract the maximum value within each group in a dataframe

There are many possibilities to do this in R. Here are some of them:

df <- read.table(header = TRUE, text = 'Gene   Value
A      12
A      10
B      3
B      5
B      6
C      1
D      3
D      4')

# aggregate
aggregate(df$Value, by = list(df$Gene), max)
aggregate(Value ~ Gene, data = df, max)

# tapply
tapply(df$Value, df$Gene, max)

# split + lapply
lapply(split(df, df$Gene), function(y) max(y$Value))

# plyr
require(plyr)
ddply(df, .(Gene), summarise, Value = max(Value))

# dplyr
require(dplyr)
df %>% group_by(Gene) %>% summarise(Value = max(Value))

# data.table
require(data.table)
dt <- data.table(df)
dt[ , max(Value), by = Gene]

# doBy
require(doBy)
summaryBy(Value~Gene, data = df, FUN = max)

# sqldf
require(sqldf)
sqldf("select Gene, max(Value) as Value from df group by Gene", drv = 'SQLite')

# ave
df[as.logical(ave(df$Value, df$Gene, FUN = function(x) x == max(x))),]

CSS: how to get scrollbars for div inside container of fixed height

Code from the above answer by Dutchie432

.FixedHeightContainer {
    float:right;
    height: 250px;
    width:250px; 
    padding:3px; 
    background:#f00;
}

.Content {
    height:224px;
    overflow:auto;
    background:#fff;
}

How do I remove whitespace from the end of a string in Python?

>>> "    xyz     ".rstrip()
'    xyz'

There is more about rstrip in the documentation.

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

Try to make pairs of numbers from the set. The first + the last; the second + the one before last. It means n-1 + 1; n-2 + 2. The result is always n. And since you are adding two numbers together, there are only (n-1)/2 pairs that can be made from (n-1) numbers.

So it is like (N-1)/2 * N.

What Java ORM do you prefer, and why?

I had a really good experience with Avaje Ebean when I was writing a medium sized JavaSE application.

It uses standard JPA annotations to define entities, but exposes a much simpler API (No EntityManager or any of that attached/detached entities crap). It also lets you easily use SQL queries or event plain JDBC calls when necessary.

It also has a very nice fluid and type-safe API for queries. You can write things like:

List<Person> boys = Ebean.find(Person.class)
                                  .where()
                                       .eq("gender", "M")
                                       .le("age", 18)
                                  .orderBy("firstName")
                                  .findList();

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

Remove this line from your manifest:

<application android:label="@string/app_name" android:icon="@drawable/icon">

You have two application tags only one should be present.

Should I initialize variable within constructor or outside constructor

I find the second style (declaration + initialization in one go) superior. Reasons:

  • It makes it clear at a glance how the variable is initialized. Typically, when reading a program and coming across a variable, you'll first go to its declaration (often automatic in IDEs). With style 2, you see the default value right away. With style 1, you need to look at the constructor as well.
  • If you have more than one constructor, you don't have to repeat the initializations (and you cannot forget them).

Of course, if the initialization value is different in different constructors (or even calculated in the constructor), you must do it in the constructor.

What is the preferred syntax for defining enums in JavaScript?

es7 way, (iterator, freeze), usage:

const ThreeWiseMen = new Enum('Melchior', 'Caspar', 'Balthazar')

for (let name of ThreeWiseMen)
    console.log(name)


// with a given key
let key = ThreeWiseMen.Melchior

console.log(key in ThreeWiseMen) // true (string conversion, also true: 'Melchior' in ThreeWiseMen)

for (let entry from key.enum)
     console.log(entry)


// prevent alteration (throws TypeError in strict mode)
ThreeWiseMen.Me = 'Me too!'
ThreeWiseMen.Melchior.name = 'Foo'

code:

class EnumKey {

    constructor(props) { Object.freeze(Object.assign(this, props)) }

    toString() { return this.name }

}

export class Enum {

    constructor(...keys) {

        for (let [index, key] of keys.entries()) {

            Object.defineProperty(this, key, {

                value: new EnumKey({ name:key, index, enum:this }),
                enumerable: true,

            })

        }

        Object.freeze(this)

    }

    *[Symbol.iterator]() {

        for (let key of Object.keys(this))
            yield this[key]

    }

    toString() { return [...this].join(', ') }

}

TypeScript - Append HTML to container element in Angular 2

There is a better solution to this answer that is more Angular based.

  1. Save your string in a variable in the .ts file

    MyStrings = ["one","two","three"]

  2. In the html file use *ngFor.

    <div class="one" *ngFor="let string of MyStrings; let i = index"> <div class="two">{{string}}</div> </div>

  3. if you want to dynamically insert the div element, just push more strings into the MyStrings array

    myFunction(nextString){ this.MyString.push(nextString) }

this way every time you click the button containing the myFunction(nextString) you effectively add another class="two" div which acts the same way as inserting it into the DOM with pure javascript.

How do you know if Tomcat Server is installed on your PC

Open your windows search bar, and search for the keyword Tomcat. If a shortcut file is found instead, you can open the source file location of the shortcut by right-clicking the shortcut file and selecting the Properties.

Codeigniter $this->db->order_by(' ','desc') result is not complete

$this->db1->where('tennant_id', $tennant_id);
$this->db1->order_by('id', 'DESC');
return $this->db1->get('courses')->result();

How do I select an element in jQuery by using a variable for the ID?

Doing $('body').find(); is not necessary when looking up by ID; there is no performance gain.

Please also note that having an ID that starts with a number is not valid HTML:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

How can I detect if a selector returns null?

My favourite is to extend jQuery with this tiny convenience:

$.fn.exists = function () {
    return this.length !== 0;
}

Used like:

$("#notAnElement").exists();

More explicit than using length.

Splitting a continuous variable into equal sized groups

ntile from dplyr now does this but behaves weirdly with NA's.

I've used similar code in the following function that works in base R and does the equivalent of the cut2 solution above:

ntile_ <- function(x, n) {
    b <- x[!is.na(x)]
    q <- floor((n * (rank(b, ties.method = "first") - 1)/length(b)) + 1)
    d <- rep(NA, length(x))
    d[!is.na(x)] <- q
    return(d)
}

How to use underscore.js as a template engine?

with express it's so easy. all what you need is to use the consolidate module on node so you need to install it :

npm install consolidate --save

then you should change the default engine to html template by this:

app.set('view engine', 'html');

register the underscore template engine for the html extension:

app.engine('html', require('consolidate').underscore);

it's done !

Now for load for example an template called 'index.html':

res.render('index', { title : 'my first page'});

maybe you will need to install the underscore module.

npm install underscore --save

I hope this helped you!

Colorized grep -- viewing the entire file with highlighted matches

To highlight patterns while viewing the whole file, h can do this.

Plus it uses different colors for different patterns.

cat FILE | h 'PAT1' 'PAT2' ...

You can also pipe the output of h to less -R for better reading.

To grep and use 1 color for each pattern, cxpgrep could be a good fit.

How to print out the method name and line number and conditionally disable NSLog?

To complement the answers above, it can be quite useful to use a replacement for NSLog in certain situations, especially when debugging. For example, getting rid of all the date and process name/id information on each line can make output more readable and faster to boot.

The following link provides quite a bit of useful ammo for making simple logging much nicer.

http://cocoaheads.byu.edu/wiki/a-different-nslog

How to unzip files programmatically in Android?

use the following class

    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipInputStream;
    import android.util.Log;

    public class DecompressFast {



 private String _zipFile; 
  private String _location; 
 
  public DecompressFast(String zipFile, String location) { 
    _zipFile = zipFile; 
    _location = location; 
 
    _dirChecker(""); 
  } 
 
  public void unzip() { 
    try  { 
      FileInputStream fin = new FileInputStream(_zipFile); 
      ZipInputStream zin = new ZipInputStream(fin); 
      ZipEntry ze = null; 
      while ((ze = zin.getNextEntry()) != null) { 
        Log.v("Decompress", "Unzipping " + ze.getName()); 
 
        if(ze.isDirectory()) { 
          _dirChecker(ze.getName()); 
        } else { 
          FileOutputStream fout = new FileOutputStream(_location + ze.getName()); 
         BufferedOutputStream bufout = new BufferedOutputStream(fout);
          byte[] buffer = new byte[1024];
          int read = 0;
          while ((read = zin.read(buffer)) != -1) {
              bufout.write(buffer, 0, read);
          }

          
          
          
          bufout.close();
          
          zin.closeEntry(); 
          fout.close(); 
        } 
         
      } 
      zin.close(); 
      
      
      Log.d("Unzip", "Unzipping complete. path :  " +_location );
    } catch(Exception e) { 
      Log.e("Decompress", "unzip", e); 
      
      Log.d("Unzip", "Unzipping failed");
    } 
 
  } 
 
  private void _dirChecker(String dir) { 
    File f = new File(_location + dir); 
 
    if(!f.isDirectory()) { 
      f.mkdirs(); 
    } 
  } 


 }

How to use

 String zipFile = Environment.getExternalStorageDirectory() + "/the_raven.zip"; //your zip file location
    String unzipLocation = Environment.getExternalStorageDirectory() + "/unzippedtestNew/"; // destination folder location
  DecompressFast df= new DecompressFast(zipFile, unzipLocation);
    df.unzip();

Permissions

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

I received the error the OP stated using Django, React, and the django-cors-headers lib. To fix it with this stack, do the following:

In settings.py add the below per the official documentation.

from corsheaders.defaults import default_headers

CORS_ALLOW_HEADERS = default_headers + (
'YOUR_HEADER_NAME',
)

handling DATETIME values 0000-00-00 00:00:00 in JDBC

My point is that I just want the raw DATETIME string, so I can parse it myself as is.

That makes me think that your "workaround" is not a workaround, but in fact the only way to get the value from the database into your code:

SELECT CAST(add_date AS CHAR) as add_date

By the way, some more notes from the MySQL documentation:

MySQL Constraints on Invalid Data:

Before MySQL 5.0.2, MySQL is forgiving of illegal or improper data values and coerces them to legal values for data entry. In MySQL 5.0.2 and up, that remains the default behavior, but you can change the server SQL mode to select more traditional treatment of bad values such that the server rejects them and aborts the statement in which they occur.

[..]

If you try to store NULL into a column that doesn't take NULL values, an error occurs for single-row INSERT statements. For multiple-row INSERT statements or for INSERT INTO ... SELECT statements, MySQL Server stores the implicit default value for the column data type.

MySQL 5.x Date and Time Types:

MySQL also allows you to store '0000-00-00' as a “dummy date” (if you are not using the NO_ZERO_DATE SQL mode). This is in some cases more convenient (and uses less data and index space) than using NULL values.

[..]

By default, when MySQL encounters a value for a date or time type that is out of range or otherwise illegal for the type (as described at the beginning of this section), it converts the value to the “zero” value for that type.

How to find substring from string?

In C++

using namespace std;

string my_string {"Hello world"};
string element_to_be_found {"Hello"};

if(my_string.find(element_to_be_found)!=string::npos)
   std::cout<<"Element Found"<<std::endl;

Use of *args and **kwargs

Here's one of my favorite places to use the ** syntax as in Dave Webb's final example:

mynum = 1000
mystr = 'Hello World!'
print("{mystr} New-style formatting is {mynum}x more fun!".format(**locals()))

I'm not sure if it's terribly fast when compared to just using the names themselves, but it's a lot easier to type!

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

Two problems:

1 - You never told Git to start tracking any file

You write that you ran

git init
git commit -m "first commit"

and that, at that stage, you got

nothing added to commit but untracked files present (use "git add" to track).

Git is telling you that you never told it to start tracking any files in the first place, and it has nothing to take a snapshot of. Therefore, Git creates no commit. Before attempting to commit, you should tell Git (for instance):

Hey Git, you see that README.md file idly sitting in my working directory, there? Could you put it under version control for me? I'd like it to go in my first commit/snapshot/revision...

For that you need to stage the files of interest, using

git add README.md

before running

git commit -m "some descriptive message"

2 - You haven't set up the remote repository

You then ran

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

After that, your local repository should be able to communicate with the remote repository that resides at the specified URL (https://github.com/VijayNew/NewExample.git)... provided that remote repo actually exists! However, it seems that you never created that remote repo on GitHub in the first place: at the time of writing this answer, if I try to visit the correponding URL, I get

enter image description here

Before attempting to push to that remote repository, you need to make sure that the latter actually exists. So go to GitHub and create the remote repo in question. Then and only then will you be able to successfully push with

git push -u origin master

How to check if the string is empty?

I would test noneness before stripping. Also, I would use the fact that empty strings are False (or Falsy). This approach is similar to Apache's StringUtils.isBlank or Guava's Strings.isNullOrEmpty

This is what I would use to test if a string is either None OR Empty OR Blank:

def isBlank (myString):
    if myString and myString.strip():
        #myString is not None AND myString is not empty or blank
        return False
    #myString is None OR myString is empty or blank
    return True

And, the exact opposite to test if a string is not None NOR Empty NOR Blank:

def isNotBlank (myString):
    if myString and myString.strip():
        #myString is not None AND myString is not empty or blank
        return True
    #myString is None OR myString is empty or blank
    return False

More concise forms of the above code:

def isBlank (myString):
    return not (myString and myString.strip())

def isNotBlank (myString):
    return bool(myString and myString.strip())

Pretty print in MongoDB shell as default

Got to the question but could not figure out how to print it from externally-loaded mongo. So:

This works is for console: and is prefered in console, but does not work in external mongo-loaded javascript:

db.quizes.find().pretty()

This works in external mongo-loaded javscript:

db.quizes.find().forEach(printjson)

Why am I getting error CS0246: The type or namespace name could not be found?

I had a similar problem after first pulling and starting a new solution. It was fixed in visual studio by first cleaning the project. Then restoring the packages. When I built again, there were no more type or namespace errors.

Alternative for <blink>

The blink element is being abandoned by browsers: Firefox supported it up to version 22, and Opera up to version 12.

The HTML5 CR, which is the first draft specification that mentions blink, declares it as “obsolete” but describes (in the Rendering section) its “expected rendering” with the rule

blink { text-decoration: blink; }

and recommends that the element be replaced by the use of CSS. There are actually several alternative ways of emulating blink in CSS and JavaScript, but the rule mentioned is the most straightforward one: the value blink for text-decoration was defined specifically to provide a CSS counterpart to the blink element. However, support to it seems to be as limited as for the blink element.

If you really want to make content blink in a cross-browser way, you can use e.g. simple JavaScript code that changes content to invisible, back to visible etc. in a timed manner. For better results you could use CSS animations, with somewhat more limited browser support.

Redirect HTTP to HTTPS on default virtual host without ServerName

This is the complete way to omit unneeded redirects, too ;)

These rules are intended to be used in .htaccess files, as a RewriteRule in a *:80 VirtualHost entry needs no Conditions.

RewriteEngine on
RewriteCond %{HTTPS} off [OR] 
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]

Eplanations:

RewriteEngine on

==> enable the engine at all

RewriteCond %{HTTPS} off [OR]

==> match on non-https connections, or (not setting [OR] would cause an implicit AND !)

RewriteCond %{HTTP:X-Forwarded-Proto} !https

==> match on forwarded connections (proxy, loadbalancer, etc.) without https

RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]

==> if one of both Conditions match, do the rewrite of the whole URL, sending a 301 to have this 'learned' by the client (some do, some don't) and the L for the last rule.

Clone an image in cv2 python

The first answer is correct but you say that you are using cv2 which inherently uses numpy arrays. So, to make a complete different copy of say "myImage":

newImage = myImage.copy()

The above is enough. No need to import numpy.

How to get selenium to wait for ajax response?

For those who is using primefaces, just do:

selenium.waitForCondition("selenium.browserbot.getCurrentWindow().$.active==0", defaultWaitingPeriod);

How to fix "Attempted relative import in non-package" even with __init__.py

This approach worked for me and is less cluttered than some solutions:

try:
  from ..components.core import GameLoopEvents
except ValueError:
  from components.core import GameLoopEvents

The parent directory is in my PYTHONPATH, and there are __init__.py files in the parent directory and this directory.

The above always worked in python 2, but python 3 sometimes hit an ImportError or ModuleNotFoundError (the latter is new in python 3.6 and a subclass of ImportError), so the following tweak works for me in both python 2 and 3:

try:
  from ..components.core import GameLoopEvents
except ( ValueError, ImportError):
  from components.core import GameLoopEvents

Parsing JSON with Unix tools

You can try something like this -

curl -s 'http://twitter.com/users/jaypalsingh.json' | 
awk -F=":" -v RS="," '$1~/"text"/ {print}'

Batch files : How to leave the console window open

put at the end it will reopen your console

start cmd 

Changing route doesn't scroll to top in the new page

None of the answer provided solved my issue. I am using an animation between views and the scrolling would always happen after the animation. The solution I found so that the scrolling to the top happen before the animation is the following directive:

yourModule.directive('scrollToTopBeforeAnimation', ['$animate', function ($animate) {
    return {
        restrict: 'A',
        link: function ($scope, element) {
            $animate.on('enter', element, function (element, phase) {

                if (phase === 'start') {

                    window.scrollTo(0, 0);
                }

            })
        }
    };
}]);

I inserted it on my view as follows:

<div scroll-to-top-before-animation>
    <div ng-view class="view-animation"></div>
</div>

What is the difference between angular-route and angular-ui-router?

AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. Unlike the $route service in the Angular ngRoute module, which is organized around URL routes, UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.

https://github.com/angular-ui/ui-router

Check if a string isn't nil or empty in Lua

One simple thing you could do is abstract the test inside a function.

local function isempty(s)
  return s == nil or s == ''
end

if isempty(foo) then
  foo = "default value"
end

What's wrong with using == to compare floats in Java?

Here is a very long (but hopefully useful) discussion about this and many other floating point issues you may encounter: What Every Computer Scientist Should Know About Floating-Point Arithmetic

Correct way to import lodash

I just put them in their own file and export it for node and webpack:

// lodash-cherries.js
module.exports = {
  defaults: require('lodash/defaults'),
  isNil: require('lodash/isNil'),
  isObject: require('lodash/isObject'),
  isArray: require('lodash/isArray'),
  isFunction: require('lodash/isFunction'),
  isInteger: require('lodash/isInteger'),
  isBoolean: require('lodash/isBoolean'),
  keys: require('lodash/keys'),
  set: require('lodash/set'),
  get: require('lodash/get'),
}

How to check postgres user and password?

You may change the pg_hba.conf and then reload the postgresql. something in the pg_hba.conf may be like below:

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust

then you change your user to postgresql, you may login successfully.

su postgresql

WAMP Server doesn't load localhost

Change the port 80 to port 8080 and restart all services and access like localhost:8080/

It will work fine.

Can't compile C program on a Mac after upgrade to Mojave

I've found great solution and explanation at this GitHub comment. The trick:

make SDKROOT=`xcrun --show-sdk-path` MACOSX_DEPLOYMENT_TARGET=

Did the job.

C# Example of AES256 encryption using System.Security.Cryptography.Aes

public class AesCryptoService
{
    private static byte[] Key = Encoding.ASCII.GetBytes(@"qwr{@^h`h&_`50/ja9!'dcmh3!uw<&=?");
    private static byte[] IV = Encoding.ASCII.GetBytes(@"9/\~V).A,lY&=t2b");


    public static string EncryptStringToBytes_Aes(string plainText)
    {
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");
        byte[] encrypted;


        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;
            aesAlg.Mode = CipherMode.CBC;
            aesAlg.Padding = PaddingMode.PKCS7;

            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }
        
        return Convert.ToBase64String(encrypted);
    }


    
    public static string DecryptStringFromBytes_Aes(string Text)
    {
        if (Text == null || Text.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");

        string plaintext = null;
        byte[] cipherText = Convert.FromBase64String(Text.Replace(' ', '+'));

        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;
            aesAlg.Mode = CipherMode.CBC;
            aesAlg.Padding = PaddingMode.PKCS7;


            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }

        }

        return plaintext;
    }
}

Facebook Architecture

Well Facebook has undergone MANY many changes and it wasn't originally designed to be efficient. It was designed to do it's job. I have absolutely no idea what the code looks like and you probably won't find much info about it (for obvious security and copyright reasons), but just take a look at the API. Look at how often it changes and how much of it doesn't work properly, anymore, or at all.

I think the biggest ace up their sleeve is the Hiphop. http://developers.facebook.com/blog/post/358 You can use HipHop yourself: https://github.com/facebook/hiphop-php/wiki

But if you ask me it's a very ambitious and probably time wasting task. Hiphop only supports so much, it can't simply convert everything to C++. So what does this tell us? Well, it tells us that Facebook is NOT fully taking advantage of the PHP language. It's not using the latest 5.3 and I'm willing to bet there's still a lot that is PHP 4 compatible. Otherwise, they couldn't use HipHop. HipHop IS A GOOD IDEA and needs to grow and expand, but in it's current state it's not really useful for that many people who are building NEW PHP apps.

There's also PHP to JAVA via things like Resin/Quercus. Again, it doesn't support everything...

Another thing to note is that if you use any non-standard PHP module, you aren't going to be able to convert that code to C++ or Java either. However...Let's take a look at PHP modules. They are ARE compiled in C++. So if you can build PHP modules that do things (like parse XML, etc.) then you are basically (minus some interaction) working at the same speed. Of course you can't just make a PHP module for every possible need and your entire app because you would have to recompile and it would be much more difficult to code, etc.

However...There are some handy PHP modules that can help with speed concerns. Though at the end of the day, we have this awesome thing known as "the cloud" and with it, we can scale our applications (PHP included) so it doesn't matter as much anymore. Hardware is becoming cheaper and cheaper. Amazon just lowered it's prices (again) speaking of.

So as long as you code your PHP app around the idea that it will need to one day scale...Then I think you're fine and I'm not really sure I'd even look at Facebook and what they did because when they did it, it was a completely different world and now trying to hold up that infrastructure and maintain it...Well, you get things like HipHop.

Now how is HipHop going to help you? It won't. It can't. You're starting fresh, you can use PHP 5.3. I'd highly recommend looking into PHP 5.3 frameworks and all the new benefits that PHP 5.3 brings to the table along with the SPL libraries and also think about your database too. You're most likely serving up content from a database, so check out MongoDB and other types of databases that are schema-less and document-oriented. They are much much faster and better for the most "common" type of web site/app.

Look at NEW companies like Foursquare and Smugmug and some other companies that are utilizing NEW technology and HOW they are using it. For as successful as Facebook is, I honestly would not look at them for "how" to build an efficient web site/app. I'm not saying they don't have very (very) talented people that work there that are solving (their) problems creatively...I'm also not saying that Facebook isn't a great idea in general and that it's not successful and that you shouldn't get ideas from it....I'm just saying that if you could view their entire source code, you probably wouldn't benefit from it.

How can I install Apache Ant on Mac OS X?

MacPorts will install ant for you in MacOSX 10.9. Just use

$ sudo port install apache-ant

and it will install.

Bash script to check running process

This trick works for me. Hope this could help you. Let's save the followings as checkRunningProcess.sh

#!/bin/bash
ps_out=`ps -ef | grep $1 | grep -v 'grep' | grep -v $0`
result=$(echo $ps_out | grep "$1")
if [[ "$result" != "" ]];then
    echo "Running"
else
    echo "Not Running"
fi

Make the checkRunningProcess.sh executable.And then use it.
Example to use.

20:10 $ checkRunningProcess.sh proxy.py
Running
20:12 $ checkRunningProcess.sh abcdef
Not Running

PHP/Apache: PHP Fatal error: Call to undefined function mysql_connect()

I had this same problem and had to refer to the php manual which told me the mysql and mysqli extensions require libmysql.dll to load. I searched for it under C:\windows\system32 (windows 7) and could not find, so I downloaded it here and placed it in my C:\windows\system32. I restarted Apache and everything worked fine. Took me 3 days to figure out, hope it helps.

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();
}

Given two directory trees, how can I find out which files differ by content?

To report differences between dirA and dirB, while also updating/syncing.

rsync -auv <dirA> <dirB>

Swing vs JavaFx for desktop applications

What will be cleaner and easier to maintain?

All things being equal, probably JavaFX - the API is much more consistent across components. However, this depends much more on how the code is written rather than what library is used to write it.

And what will be faster to build from scratch?

Highly dependent on what you're building. Swing has more components around for it (3rd party as well as built in) and not all of them have made their way to the newer JavaFX platform yet, so there may be a certain amount of re-inventing the wheel if you need something a bit custom. On the other hand, if you want to do transitions / animations / video stuff then this is orders of magnitude easier in FX.

One other thing to bear in mind is (perhaps) look and feel. If you absolutely must have the default system look and feel, then JavaFX (at present) can't provide this. Not a big must have for me (I prefer the default FX look anyway) but I'm aware some policies mandate a restriction to system styles.

Personally, I see JavaFX as the "up and coming" UI library that's not quite there yet (but more than usable), and Swing as the borderline-legacy UI library that's fully featured and supported for the moment, but probably won't be so much in the years to come (and therefore chances are FX will overtake it at some point.)

get original element from ng-click

Not a direct answer to this question but rather to the "issue" of $event.currentTarget apparently be set to null.

This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.

You can check this for more information: Consecutive calls to console.log produce inconsistent results

How to create jar file with package structure?

This is what I do inside .sh file, let's consider install.sh

#!/bin/sh
echo Installing
cd .../Your_Project_Directory/com/cdy/ws/
jar cfe X.jar Main *.class
cd .../Your_Project_Directory/
ln -s .../Your_Project_Directory/com/cdy/ws/X.jar X
echo Testing...
java -jar X
echo You are Good to Go...Use hapily
#etc.

Creating Executable Jar file at the Class directory and creating a SymLink at anywhere you want.

Run it using,

$ sh install.sh[ENTER]
$ java -jar X[ENTER]

AngularJS ng-class if-else expression

You can try this method:

</p><br /><br />
<p>ng-class="{test: obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}<br /><br /><br />

ng-class="{test: obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}

You can get complete details from here.

Linux - Install redis-cli only

There are many way to install radis-cli. It comes with redis-tools and redis-server. Installing any of them will install redis-cli too. But it will also install other tools too. As you have redis-server installed somewhere and only interested to install redis-cli. To install install only redis-cli without other unnecessary tools follow below command

cd /tmp
wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable
make
cp src/redis-cli /usr/local/bin/
chmod 755 /usr/local/bin/redis-cli

Bash integer comparison

This script works!

#/bin/bash
if [[ ( "$#" < 1 ) || ( !( "$1" == 1 ) && !( "$1" == 0 ) ) ]] ; then
    echo this script requires a 1 or 0 as first parameter.
else
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
fi

But this also works, and in addition keeps the logic of the OP, since the question is about calculations. Here it is with only arithmetic expressions:

#/bin/bash
if (( $# )) && (( $1 == 0 || $1 == 1 )); then
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
else
    echo this script requires a 1 or 0 as first parameter.
fi

The output is the same1:

$ ./tmp.sh 
this script requires a 1 or 0 as first parameter.

$ ./tmp.sh 0
first parameter is 0

$ ./tmp.sh 1
first parameter is 1

$ ./tmp.sh 2
this script requires a 1 or 0 as first parameter.

[1] the second fails if the first argument is a string

Is JavaScript guaranteed to be single-threaded?

I've tried @bobince's example with a slight modifications:

<html>
<head>
    <title>Test</title>
</head>
<body>
    <textarea id="log" rows="20" cols="40"></textarea>
    <br />
    <button id="act">Run</button>
    <script type="text/javascript">
        let l= document.getElementById('log');
        let b = document.getElementById('act');
        let s = 0;

        b.addEventListener('click', function() {
            l.value += 'click begin\n';

            s = 10;
            let s2 = s;

            alert('alert!');

            s = s + s2;

            l.value += 'click end\n';
            l.value += `result = ${s}, should be ${s2 + s2}\n`;
            l.value += '----------\n';
        });

        window.addEventListener('resize', function() {
            if (s === 10) {
                s = 5;
            }

            l.value+= 'resize\n';
        });
    </script>
</body>
</html>

So, when you press Run, close alert popup and do a "single thread", you should see something like this:

click begin
click end
result = 20, should be 20

But if you try to run this in Opera or Firefox stable on Windows and minimize/maximize window with alert popup on screen, then there will be something like this:

click begin
resize
click end
result = 15, should be 20

I don't want to say, that this is "multithreading", but some piece of code had executed in a wrong time with me not expecting this, and now I have a corrupted state. And better to know about this behavior.

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

For future reference -

I had this issue with this piece of code in Microsoft Access with the debugger highlighting the line with the comment:

Option Compare Database
Option Explicit

Dim strSQL As String
Dim rstrSQL As String
Dim strTempPass As String


Private Sub btnForgotPassword_Click()
On Error GoTo ErrorHandler

Dim oApp As Outlook.Application '<---------------------------------Offending line
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application") 'this is the "instance" of Outlook
Set oMail = oApp.CreateItem(olMailItem) 'this is the actual "email"

I had to select references that were previously unselected. They were

Microsoft Outlook 15.0 Object Library
Microsoft Outlook View Control

Why can I not switch branches?

you can reset your branch with HEAD

git reset --hard branch_name

then fetch branches and delete branches which are not on remote from local,

git fetch -p 

How to run Ruby code from terminal?

If Ruby is installed, then

ruby yourfile.rb

where yourfile.rb is the file containing the ruby code.

Or

irb

to start the interactive Ruby environment, where you can type lines of code and see the results immediately.

How to compile and run C files from within Notepad++ using NppExec plugin?

Here is the code for compling and running java source code: - Open Notepadd++ - Hit F6 - Paste this code

npp_save <-- Saves the current document
CD $(CURRENT_DIRECTORY) <-- Moves to the current directory
javac "$(FILE_NAME)" <-- compiles your file named *.java
java "$(NAME_PART)" <-- executes the program

The Java Classpath variable has to be set for this...

Another useful site: http://www.scribd.com/doc/52238931/Notepad-Tutorial-Compile-and-Run-Java-Program

How do I output lists as a table in Jupyter notebook?

I recently used prettytable for rendering a nice ASCII table. It's similar to the postgres CLI output.

import pandas as pd
from prettytable import PrettyTable

data = [[1,2,3],[4,5,6],[7,8,9]]
df = pd.DataFrame(data, columns=['one', 'two', 'three'])

def generate_ascii_table(df):
    x = PrettyTable()
    x.field_names = df.columns.tolist()
    for row in df.values:
        x.add_row(row)
    print(x)
    return x

generate_ascii_table(df)

Output:

+-----+-----+-------+
| one | two | three |
+-----+-----+-------+
|  1  |  2  |   3   |
|  4  |  5  |   6   |
|  7  |  8  |   9   |
+-----+-----+-------+

Adding extra zeros in front of a number using jQuery?

Assuming you have those values stored in some strings, try this:

function pad (str, max) {
  str = str.toString();
  return str.length < max ? pad("0" + str, max) : str;
}

pad("3", 3);    // => "003"
pad("123", 3);  // => "123"
pad("1234", 3); // => "1234"

var test = "MR 2";
var parts = test.split(" ");
parts[1] = pad(parts[1], 3);
parts.join(" "); // => "MR 002"

jQuery function to get all unique elements from an array?

Paul Irish has a "Duck Punching" method (see example 2) that modifies jQuery's $.unique() method to return unique elements of any type:

(function($){
    var _old = $.unique;
    $.unique = function(arr){
        // do the default behavior only if we got an array of elements
        if (!!arr[0].nodeType){
            return _old.apply(this,arguments);
        } else {
            // reduce the array to contain no dupes via grep/inArray
            return $.grep(arr,function(v,k){
                return $.inArray(v,arr) === k;
            });
        }
    };
})(jQuery);

C++ equivalent of Java's toString?

The question has been answered. But I wanted to add a concrete example.

class Point{

public:
      Point(int theX, int theY) :x(theX), y(theY)
      {}
      // Print the object
      friend ostream& operator <<(ostream& outputStream, const Point& p);
private:
      int x;
      int y;
};

ostream& operator <<(ostream& outputStream, const Point& p){
       int posX = p.x;
       int posY = p.y;

       outputStream << "x="<<posX<<","<<"y="<<posY;
      return outputStream;
}

This example requires understanding operator overload.

What does %>% mean in R

Use ?'%*%' to get the documentation.

%*% is matrix multiplication. For matrix multiplication, you need an m x n matrix times an n x p matrix.

Draw Circle using css alone

  • Create a div with a set height and width (so, for a circle, use the same height and width), forming a square
  • add a border-radius of 50% which will make it circular in shape. (note: no prefix has been required for a long time)
  • You can then play around with background-color / gradients / (even pseudo elements) to create something like this:

_x000D_
_x000D_
.red {_x000D_
  background-color: red;_x000D_
}_x000D_
.green {_x000D_
  background-color: green;_x000D_
}_x000D_
.blue {_x000D_
  background-color: blue;_x000D_
}_x000D_
.yellow {_x000D_
  background-color: yellow;_x000D_
}_x000D_
.sphere {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  border-radius: 50%;_x000D_
  text-align: center;_x000D_
  vertical-align: middle;_x000D_
  font-size: 500%;_x000D_
  position: relative;_x000D_
  box-shadow: inset -10px -10px 100px #000, 10px 10px 20px black, inset 0px 0px 10px black;_x000D_
  display: inline-block;_x000D_
  margin: 5%;_x000D_
}_x000D_
.sphere::after {_x000D_
  background-color: rgba(255, 255, 255, 0.3);_x000D_
  content: '';_x000D_
  height: 45%;_x000D_
  width: 12%;_x000D_
  position: absolute;_x000D_
  top: 4%;_x000D_
  left: 15%;_x000D_
  border-radius: 50%;_x000D_
  transform: rotate(40deg);_x000D_
}
_x000D_
<div class="sphere red"></div>_x000D_
<div class="sphere green"></div>_x000D_
<div class="sphere blue"></div>_x000D_
<div class="sphere yellow"></div>_x000D_
<div class="sphere"></div>
_x000D_
_x000D_
_x000D_

How to find all the dependencies of a table in sql server

In SQL Server 2008 there are two new Dynamic Management Functions introduced to keep track of object dependencies: sys.dm_sql_referenced_entities and sys.dm_sql_referencing_entities:

1/ Returning the entities that refer to a given entity:

SELECT
        referencing_schema_name, referencing_entity_name, 
        referencing_class_desc, is_caller_dependent
FROM sys.dm_sql_referencing_entities ('<TableName>', 'OBJECT')

2/ Returning entities that are referenced by an object:

SELECT
        referenced_schema_name, referenced_entity_name, referenced_minor_name, 
        referenced_class_desc, is_caller_dependent, is_ambiguous
FROM sys.dm_sql_referenced_entities ('<StoredProcedureName>', 'OBJECT');

Alternatively, you can use sp_depends:

EXEC sp_depends '<TableName>'

Another option is to use a pretty useful tool called SQL Dependency Tracker from Red Gate.

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

I think that it is the Environment error,you should try setting : DJANGO_SETTINGS_MODULE='correctly_settings'

How to Deserialize XML document

The following snippet should do the trick (and you can ignore most of the serialization attributes):

public class Car
{
  public string StockNumber { get; set; }
  public string Make { get; set; }
  public string Model { get; set; }
}

[XmlRootAttribute("Cars")]
public class CarCollection
{
  [XmlElement("Car")]
  public Car[] Cars { get; set; }
}

...

using (TextReader reader = new StreamReader(path))
{
  XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
  return (CarCollection) serializer.Deserialize(reader);
}

How to define a variable in a Dockerfile?

Late to the party, but if you don't want to expose environment variables, I guess it's easier to do something like this:

RUN echo 1 > /tmp/__var_1
RUN echo `cat /tmp/__var_1`
RUN rm -f /tmp/__var_1

I ended up doing it because we host private npm packages in aws codeartifact:

RUN aws codeartifact get-authorization-token --output text > /tmp/codeartifact.token
RUN npm config set //company-123456.d.codeartifact.us-east-2.amazonaws.com/npm/internal/:_authToken=`cat /tmp/codeartifact.token`
RUN rm -f /tmp/codeartifact.token

And here ARG cannot work and i don't want to use ENV because i don't want to expose this token to anything else

Array versus List<T>: When to use which?

Rather than going through a comparison of the features of each data type, I think the most pragmatic answer is "the differences probably aren't that important for what you need to accomplish, especially since they both implement IEnumerable, so follow popular convention and use a List until you have a reason not to, at which point you probably will have your reason for using an array over a List."

Most of the time in managed code you're going to want to favor collections being as easy to work with as possible over worrying about micro-optimizations.

Git adding files to repo

After adding files to the stage, you need to commit them with git commit -m "comment" after git add .. Finally, to push them to a remote repository, you need to git push <remote_repo> <local_branch>.

What is useState() in React?

useState() is an example built-in React hook that lets you use states in your functional components. This was not possible before React 16.7.

The useState function is a built in hook that can be imported from the react package. It allows you to add state to your functional components. Using the useState hook inside a function component, you can create a piece of state without switching to class components.

Zip lists in Python

Source: My Blog Post (better formatting)

Example

numbers = [1,2,3]
letters = 'abcd'

zip(numbers, letters)
# [(1, 'a'), (2, 'b'), (3, 'c')]

Input

Zero or more iterables [1] (ex. list, string, tuple, dictionary)

Output (list)

1st tuple = (element_1 of numbers, element_1 of letters)

2nd tuple = (e_2 numbers, e_2 letters)

n-th tuple = (e_n numbers, e_n letters)

  1. List of n tuples: n is the length of the shortest argument (input)
    • len(numbers) == 3 < len(letters) == 4 ? short= 3 ? return 3 tuples
  2. Length each tuple = # of args (tuple takes an element from each arg)
    • args = (numbers,letters); len(args) == 2 ? tuple with 2 elements
  3. ith tuple = (element_i arg1, element_i arg2…, element_i argn)

Edge Cases

1) Empty String: len(str)= 0 = no tuples

2) Single String: len(str) == 2 tuples with len(args) == 1 element(s)

zip()
# []
zip('')
# []
zip('hi')
# [('h',), ('i',)]

Zip in Action!

1. Build a dictionary [2] out of two lists

keys = ["drink","band","food"]
values = ["La Croix", "Daft Punk", "Sushi"]

my_favorite = dict( zip(keys, values) )

my_favorite["drink"]
# 'La Croix'

my_faves = dict()
for i in range(len(keys)):
    my_faves[keys[i]] = values[i]
  • zip is an elegant, clear, & concise solution

2. Print columns in a table

"*" [3] is called "unpacking": f(*[arg1,arg2,arg3]) == f(arg1, arg2, arg3)

student_grades = [
[   'Morty'  ,  1   ,  "B"  ],
[   'Rick'   ,  4   ,  "A"  ],
[   'Jerry'  ,  3   ,  "M"  ],
[  'Kramer'  ,  0   ,  "F"  ],
]

row_1 = student_grades[0]
print row_1
# ['Morty', 1, 'B']

columns = zip(*student_grades)
names = columns[0]
print names
# ('Morty', 'Rick', 'Jerry', 'Kramer')

Extra Credit: Unzipping

zip(*args) is called “unzipping” because it has the inverse effect of zip

numbers = (1,2,3)
letters = ('a','b','c')

zipped = zip(numbers, letters)
print zipped
# [(1, 'a'), (2, 'b'), (3, 'c')]

unzipped = zip(*zipped)
print unzipped
# [(1, 2, 3), ('a', 'b', 'c')]
  • unzipped: tuple_1 = e1 of each zipped tuple. tuple_2 = e2 of each zipped

Footnotes

  1. An object capable of returning its members one at a time (ex. list [1,2,3], string 'I like codin', tuple (1,2,3), dictionary {'a':1, 'b':2})
  2. {key1:value1, key2:value2...}
  3. “Unpacking” (*)

* Code:

# foo - function, returns sum of two arguments
def foo(x,y):
    return x + y
print foo(3,4)
# 7

numbers = [1,2]
print foo(numbers)
# TypeError: foo() takes exactly 2 arguments (1 given)

print foo(*numbers)
# 3

* took numbers (1 arg) and “unpacked” its’ 2 elements into 2 args

Is there a typical state machine implementation pattern?

There is a book titled Practical Statecharts in C/C++. However, it is way too heavyweight for what we need.

Can't bind to 'ngIf' since it isn't a known property of 'div'

If you are using RC5 then import this:

import { CommonModule } from '@angular/common';  
import { BrowserModule } from '@angular/platform-browser';

and be sure to import CommonModule from the module that is providing your component.

 @NgModule({
    imports: [CommonModule],
    declarations: [MyComponent]
  ...
})
class MyComponentModule {}

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

A simple solution is

UUID.randomUUID().toString().replace("-", "")

(Like the existing solutions, only that it avoids the String#replaceAll call. Regular expression replacement is not required here, so String#replace feels more natural, though technically it still is implemented with regular expressions. Given that the generation of the UUID is more costly than the replacement, there should not be a significant difference in runtime.)

Using the UUID class is probably fast enough for most scenarios, though I would expect that some specialized hand-written variant, which does not need the postprocessing, to be faster. Anyway, the bottleneck of the overall computation will normally be the random number generator. In case of the UUID class, it uses SecureRandom.

Which random number generator to use is also a trade-off that depends on the application. If it is security-sensitive, SecureRandom is, in general, the recommendation. Otherwise, ThreadLocalRandom is an alternative (faster than SecureRandom or the old Random, but not cryptographically secure).

How big can a MySQL database get before performance starts to degrade

A point to consider is also the purpose of the system and the data in the day to day.

For example, for a system with GPS monitoring of cars is not relevant query data from the positions of the car in previous months.

Therefore the data can be passed to other historical tables for possible consultation and reduce the execution times of the day to day queries.

How to use Macro argument as string literal?

You want to use the stringizing operator:

#define STRING(s) #s

int main()
{
    const char * cstr = STRING(abc); //cstr == "abc"
}

Execute another jar in a Java program

If you are java 1.6 then the following can also be done:

import javax.tools.JavaCompiler; 
import javax.tools.ToolProvider; 

public class CompilerExample {

    public static void main(String[] args) {
        String fileToCompile = "/Users/rupas/VolatileExample.java";

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        int compilationResult = compiler.run(null, null, null, fileToCompile);

        if (compilationResult == 0) {
            System.out.println("Compilation is successful");
        } else {
            System.out.println("Compilation Failed");
        }
    }
}

How to create a new figure in MATLAB?

As has already been said: figure will create a new figure for your next plots. While calling figure you can also configure it. Example:

figHandle = figure('Name', 'Name of Figure', 'OuterPosition',[1, 1, scrsz(3), scrsz(4)]);

The example sets the name for the window and the outer size of it in relation to the used screen. Here figHandle is the handle to the resulting figure and can be used later to change appearance and content. Examples:

Dot notation:

figHandle.PaperOrientation = 'portrait';
figHandle.PaperUnits = 'centimeters';

Old Style:

set(figHandle, 'PaperOrientation', 'portrait', 'PaperUnits', 'centimeters');

Using the handle with dot notation or set, options for printing are configured here.

By keeping the handles for the figures with distinc names you can interact with multiple active figures. To set a existing figure as your active, call figure(figHandle). New plots will go there now.

IIS URL Rewrite and Web.config

1) Your existing web.config: you have declared rewrite map .. but have not created any rules that will use it. RewriteMap on its' own does absolutely nothing.

2) Below is how you can do it (it does not utilise rewrite maps -- rules only, which is fine for small amount of rewrites/redirects):

This rule will do SINGLE EXACT rewrite (internal redirect) /page to /page.html. URL in browser will remain unchanged.

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRewrite" stopProcessing="true">
                <match url="^page$" />
                <action type="Rewrite" url="/page.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

This rule #2 will do the same as above, but will do 301 redirect (Permanent Redirect) where URL will change in browser.

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRedirect" stopProcessing="true">
                <match url="^page$" />
                <action type="Redirect" url="/page.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Rule #3 will attempt to execute such rewrite for ANY URL if there are such file with .html extension (i.e. for /page it will check if /page.html exists, and if it does then rewrite occurs):

<system.webServer>
    <rewrite>
        <rules>
            <rule name="DynamicRewrite" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{REQUEST_FILENAME}\.html" matchType="IsFile" />
                </conditions>
                <action type="Rewrite" url="/{R:1}.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

JSON order mixed up

Not sure if I am late to the party but I found this nice example that overrides the JSONObject constructor and makes sure that the JSON data are output in the same way as they are added. Behind the scenes JSONObject uses the MAP and MAP does not guarantee the order hence we need to override it to make sure we are receiving our JSON as per our order.

If you add this to your JSONObject then the resulting JSON would be in the same order as you have created it.

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import org.json.JSONObject;
import lombok.extern.java.Log;

@Log
public class JSONOrder {

    public static void main(String[] args) throws IOException {

        JSONObject jsontest = new JSONObject();
        try {
            Field changeMap = jsonEvent.getClass().getDeclaredField("map");
            changeMap.setAccessible(true);
            changeMap.set(jsonEvent, new LinkedHashMap<>());
            changeMap.setAccessible(false);
        } catch (IllegalAccessException | NoSuchFieldException e) {
            log.info(e.getMessage());
        }
        jsontest.put("one", "I should be first");
        jsonEvent.put("two", "I should be second");
        jsonEvent.put("third", "I should be third");
        System.out.println(jsonEvent);
    }
}

How to get the public IP address of a user in C#

This is what I use:

protected void GetUser_IP()
{
    string VisitorsIPAddr = string.Empty;
    if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
    {
        VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    }
    else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
    {
        VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
    }
    uip.Text = "Your IP is: " + VisitorsIPAddr;
}

"uip" is the name of the label in the aspx page that shows the user IP.

HTML - How to do a Confirmation popup to a Submit button and then send the request?

Another option that you can use is:

onclick="if(confirm('Do you have sure ?')){}else{return false;};"

using this function on submit button you will get what you expect.

How to create friendly URL in php?

There are lots of different ways to do this. One way is to use the RewriteRule techniques mentioned earlier to mask query string values.

One of the ways I really like is if you use the front controller pattern, you can also use urls like http://yoursite.com/index.php/path/to/your/page/here and parse the value of $_SERVER['REQUEST_URI'].

You can easily extract the /path/to/your/page/here bit with the following bit of code:

$route = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME']));

From there, you can parse it however you please, but for pete's sake make sure you sanitise it ;)

Java current machine name and logged in user?

To get the currently logged in user:

System.getProperty("user.name"); //platform independent 

and the hostname of the machine:

java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
System.out.println("Hostname of local machine: " + localMachine.getHostName());

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

Just to update all, after some deliberations, I have decided to use Async Http Client instead to solve my earlier problem. The library allows a cleaner approach (to me) to manipulate HTTP responses especially in cases where JSON objects are returned in all scenarios/HTTP statuses.

protected void getLogin() {

    EditText username = (EditText) findViewById(R.id.username); 
    EditText password = (EditText) findViewById(R.id.password); 

    RequestParams params = new RequestParams();
    params.put("username", username.getText().toString());
    params.put("password", password.getText().toString());

    RestClient.post(getHost() + "api/v1/auth/login", params,
            new JsonHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                JSONObject response) {

            try {

                //process JSONObject obj 
                Log.w("myapp","success status code..." + statusCode);

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
                Throwable throwable, JSONObject errorResponse) {
            Log.w("myapp", "failure status code..." + statusCode);


            try {
                //process JSONObject obj
                Log.w("myapp", "error ..."  + errorResponse.getString("message").toString());
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource, as per this line:

java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource

I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource class in it.

How can I use mySQL replace() to replace strings in multiple records?

UPDATE some_table SET some_field = REPLACE(some_field, '&lt;', '<')

How to write multiple line string using Bash with variables?

The syntax (<<<) and the command used (echo) is wrong.

Correct would be:

#!/bin/bash

kernel="2.6.39"
distro="xyz"
cat >/etc/myconfig.conf <<EOL
line 1, ${kernel}
line 2, 
line 3, ${distro}
line 4 line
... 
EOL

cat /etc/myconfig.conf

This construction is referred to as a Here Document and can be found in the Bash man pages under man --pager='less -p "\s*Here Documents"' bash.

Vim multiline editing like in sublimetext?

if you use the "global" command, you can repeat what you can do on one online an any number of lines.

:g/<search>/.<your ex command>

example:

:g/foo/.s/bar/baz/g

The above command finds all lines that have foo, and replace all occurrences of bar on that line with baz.

:g/.*/

will do on every line

Why doesn't java.io.File have a close method?

A BufferedReader can be opened and closed but a File is never opened, it just represents a path in the filesystem.

What exactly are iterator, iterable, and iteration?

I don’t know if it helps anybody but I always like to visualize concepts in my head to better understand them. So as I have a little son I visualize iterable/iterator concept with bricks and white paper.

Suppose we are in the dark room and on the floor we have bricks for my son. Bricks of different size, color, does not matter now. Suppose we have 5 bricks like those. Those 5 bricks can be described as an object – let’s say bricks kit. We can do many things with this bricks kit – can take one and then take second and then third, can change places of bricks, put first brick above the second. We can do many sorts of things with those. Therefore this bricks kit is an iterable object or sequence as we can go through each brick and do something with it. We can only do it like my little son – we can play with one brick at a time. So again I imagine myself this bricks kit to be an iterable.

Now remember that we are in the dark room. Or almost dark. The thing is that we don’t clearly see those bricks, what color they are, what shape etc. So even if we want to do something with them – aka iterate through them – we don’t really know what and how because it is too dark.

What we can do is near to first brick – as element of a bricks kit – we can put a piece of white fluorescent paper in order for us to see where the first brick-element is. And each time we take a brick from a kit, we replace the white piece of paper to a next brick in order to be able to see that in the dark room. This white piece of paper is nothing more than an iterator. It is an object as well. But an object with what we can work and play with elements of our iterable object – bricks kit.

That by the way explains my early mistake when I tried the following in an IDLE and got a TypeError:

 >>> X = [1,2,3,4,5]
 >>> next(X)
 Traceback (most recent call last):
    File "<pyshell#19>", line 1, in <module>
      next(X)
 TypeError: 'list' object is not an iterator

List X here was our bricks kit but NOT a white piece of paper. I needed to find an iterator first:

>>> X = [1,2,3,4,5]
>>> bricks_kit = [1,2,3,4,5]
>>> white_piece_of_paper = iter(bricks_kit)
>>> next(white_piece_of_paper)
1
>>> next(white_piece_of_paper)
2
>>>

Don’t know if it helps, but it helped me. If someone could confirm/correct visualization of the concept, I would be grateful. It would help me to learn more.

What is the best java image processing library/approach?

For commercial tools, you might want to try Snowbound.

http://www.snowbound.com/

My experience with them is somewhat dated, but I found their Java Imaging API to be a lot easier to use than JAI and a lot faster.

Their customer support and code samples were very good too.

Difference between opening a file in binary vs text

The link you gave does actually describe the differences, but it's buried at the bottom of the page:

http://www.cplusplus.com/reference/cstdio/fopen/

Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.

The conversion could be to normalize \r\n to \n (or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.

What can cause a “Resource temporarily unavailable” on sock send() command

That's because you're using a non-blocking socket and the output buffer is full.

From the send() man page

   When the message does not fit into  the  send  buffer  of  the  socket,
   send() normally blocks, unless the socket has been placed in non-block-
   ing I/O mode.  In non-blocking mode it  would  return  EAGAIN  in  this
   case.  

EAGAIN is the error code tied to "Resource temporarily unavailable"

Consider using select() to get a better control of this behaviours

"FATAL: Module not found error" using modprobe

i think there should be entry of your your_module.ko in /lib/modules/uname -r/modules.dep and in /lib/modules/uname -r/modules.dep.bin for "modprobe your_module" command to work

How to return part of string before a certain character?

And note that first argument of subString is 0 based while second is one based.

Example:

String str= "0123456";
String sbstr= str.substring(0,5);

Output will be sbstr= 01234 and not sbstr = 012345

excel delete row if column contains value from to-remove-list

Given sheet 2:

ColumnA
-------
apple
orange

You can flag the rows in sheet 1 where a value exists in sheet 2:

ColumnA  ColumnB
-------  --------------
pear     =IF(ISERROR(VLOOKUP(A1,Sheet2!A:A,1,FALSE)),"Keep","Delete")
apple    =IF(ISERROR(VLOOKUP(A2,Sheet2!A:A,1,FALSE)),"Keep","Delete")
cherry   =IF(ISERROR(VLOOKUP(A3,Sheet2!A:A,1,FALSE)),"Keep","Delete")
orange   =IF(ISERROR(VLOOKUP(A4,Sheet2!A:A,1,FALSE)),"Keep","Delete")
plum     =IF(ISERROR(VLOOKUP(A5,Sheet2!A:A,1,FALSE)),"Keep","Delete")

The resulting data looks like this:

ColumnA  ColumnB
-------  --------------
pear     Keep
apple    Delete
cherry   Keep
orange   Delete
plum     Keep

You can then easily filter or sort sheet 1 and delete the rows flagged with 'Delete'.

MS Access - execute a saved query by name in VBA

To use CurrentDb.Execute, your query must be an action query, AND in quotes.

CurrentDb.Execute "queryname"

Getting the size of an array in an object

Arrays have a property .length that returns the number of elements.

var st =
    {
        "itema":{},
        "itemb":
        [
            {"id":"s01","cd":"c01","dd":"d01"},
            {"id":"s02","cd":"c02","dd":"d02"}
        ]
    };

st.itemb.length // 2

how to get yesterday's date in C#

You don't need to call DateTime.Today multiple times, just use it single time and format the date object in your desire format.. like that

 string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");

OR

 string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");

TypeError: 'float' object is not callable

There is an operator missing, likely a *:

-3.7 need_something_here (prof[x])

The "is not callable" occurs because the parenthesis -- and lack of operator which would have switched the parenthesis into precedence operators -- make Python try to call the result of -3.7 (a float) as a function, which is not allowed.

The parenthesis are also not needed in this case, the following may be sufficient/correct:

-3.7 * prof[x]

As Legolas points out, there are other things which may need to be addressed:

2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25)))
                                  ^-- op missing
                                                    extra parenthesis --^
               valid but questionable float*tuple --^
                                     expression yields 0.0 always --^

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

How do you install GLUT and OpenGL in Visual Studio 2012?

Download the GLUT library. At first step Copy the glut32.dll and paste it in C:\Windows\System32 folder.Second step copy glut.h file and paste it in C:\Program Files\Microsoft Visual Studio\VC\include folder and third step copy glut32.lib and paste it in c:\Program Files\Microsoft Visual Studio\VC\lib folder. Now you can create visual c++ console application project and include glut.h header file then you can write code for GLUT project. If you are using 64 bit windows machine then path and glut library may be different but process is similar.

how to File.listFiles in alphabetical order?

I think the previous answer is the best way to do it here is another simple way. just to print the sorted results.

 String path="/tmp";
 String[] dirListing = null;
 File dir = new File(path);
 dirListing = dir.list();
 Arrays.sort(dirListing);
 System.out.println(Arrays.deepToString(dirListing));

Combining two sorted lists in Python

from datetime import datetime
from itertools import chain
from operator import attrgetter

class DT:
    def __init__(self, dt):
        self.dt = dt

list1 = [DT(datetime(2008, 12, 5, 2)),
         DT(datetime(2009, 1, 1, 13)),
         DT(datetime(2009, 1, 3, 5))]

list2 = [DT(datetime(2008, 12, 31, 23)),
         DT(datetime(2009, 1, 2, 12)),
         DT(datetime(2009, 1, 4, 15))]

list3 = sorted(chain(list1, list2), key=attrgetter('dt'))
for item in list3:
    print item.dt

The output:

2008-12-05 02:00:00
2008-12-31 23:00:00
2009-01-01 13:00:00
2009-01-02 12:00:00
2009-01-03 05:00:00
2009-01-04 15:00:00

I bet this is faster than any of the fancy pure-Python merge algorithms, even for large data. Python 2.6's heapq.merge is a whole another story.

Decreasing height of bootstrap 3.0 navbar

Simply override the min-height set in .navbar like so:

.navbar{
  min-height:20px; //* or whatever height you require
}

Altering an elements height to something smaller than the min-height won't make a difference...

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

Capitalize the first letter of string in AngularJs

{{ uppercase_expression | capitaliseFirst}} should work

Page redirect after certain time PHP

Redirect PHP time programming:

 <?php
 header("Refresh:10;url=***-----índex.php--OR----URL-----");
 ?>

Maven Jacoco Configuration - Exclude classes/packages from report not working

Another solution:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.7.5.201505241946</version>
    <executions>
        <execution>
            <id>default-prepare-agent</id>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
        </execution>
        <execution>
            <id>default-report</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>report</goal>
            </goals>
        </execution>
        <execution>
            <id>default-check</id>
            <goals>
                <goal>check</goal>
            </goals>
            <configuration>
                <rules>
                    <rule implementation="org.jacoco.maven.RuleConfiguration">
                        <excludes>
                            <exclude>com.mypackage1</exclude
                            <exclude>com.mypackage2</exclude>
                        </excludes>
                        <element>PACKAGE</element>
                        <limits>
                            <limit implementation="org.jacoco.report.check.Limit">
                                <counter>COMPLEXITY</counter>
                                <value>COVEREDRATIO</value>
                                <minimum>0.85</minimum>
                            </limit>
                        </limits>
                    </rule>
                </rules>
            </configuration>
        </execution>
    </executions>
</plugin>

Please note that, we are using "<element>PACKAGE</element>" in the configuration which then helps us to exclude at package level.

How can I iterate JSONObject to get individual items

You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .

public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
    Iterator<String> keys = json.keys();
    while(keys.hasNext()){
        String key = keys.next();
        String val = null;
        try{
             JSONObject value = json.getJSONObject(key);
             parse(value,out);
        }catch(Exception e){
            val = json.getString(key);
        }

        if(val != null){
            out.put(key,val);
        }
    }
    return out;
}

 public static void main(String[] args) throws JSONException {

    String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";

    JSONObject object = new JSONObject(json);

    JSONObject info = object.getJSONObject("ipinfo");

    Map<String,String> out = new HashMap<String, String>();

    parse(info,out);

    String latitude = out.get("latitude");
    String longitude = out.get("longitude");
    String city = out.get("city");
    String state = out.get("state");
    String country = out.get("country");
    String postal = out.get("postal_code");

    System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);

    System.out.println("ALL VALUE " + out);

}

Output:

    Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}

Leader Not Available Kafka in Console Producer

Another possibility for this warning (in 0.10.2.1) is that you try to poll on a topic that has just been created and the leader for this topic-partition is not yet available, you are in the middle of a leadership election.

Waiting a second between topic creation and polling is a workaround.

What does the Ellipsis object do?

Summing up what others have said, as of Python 3, Ellipsis is essentially another singleton constant similar to None, but without a particular intended use. Existing uses include:

  • In slice syntax to represent the full slice in remaining dimensions
  • In type hinting to indicate only part of a type(Callable[..., int] or Tuple[str, ...])
  • In type stub files to indicate there is a default value without specifying it

Possible uses could include:

  • As a default value for places where None is a valid option
  • As the content for a function you haven't implemented yet

Sublime Text 3 how to change the font size of the file sidebar?

I followed these instructions but then found that the menu hover color was wrong.

I am using the Spacegray theme in Sublime 3 beta 3074. So to accomplish the sidebar font color change and also hover color change, on OSX, I created a new file ~/Library/"Application Support"/"Sublime Text 3"/Packages/User/Spacegray.sublime-theme

then added this code to it:

[
    {
        "class": "sidebar_label",
        "color": [192,197,203],
        "font.bold": false,
        "font.size": 15
    },
     {
        "class": "sidebar_label",
        "parents": [{"class": "tree_row","attributes": ["hover"]}],
        "color": [255,255,255] 
    },
]

It is possible to tweak many other settings for your theme if you can see the original default:

https://gist.github.com/nateflink/0355eee823b89fe7681e

I extracted this file from the sublime package zip file by installing the PackageResourceViewer following MattDMo's instructions (https://stackoverflow.com/users/1426065/mattdmo) here:

How to change default code snippets in Sublime Text 3?

Floating point vs integer calculations on modern hardware

The floating point version will be much slower, if there is no remainder operation. Since all the adds are sequential, the cpu will not be able to parallelise the summation. The latency will be critical. FPU add latency is typically 3 cycles, while integer add is 1 cycle. However, the divider for the remainder operator will probably the critical part, as it is not fully pipelined on modern cpu's. so, assuming the divide/remainder instruction will consume the bulk of the time, the difference due to add latency will be small.

Eclipse reported "Failed to load JNI shared library"

First, ensure that your version of Eclipse and JDK match, either both 64-bit or both 32-bit (you can't mix-and-match 32-bit with 64-bit).

Second, the -vm argument in eclipse.ini should point to the java executable. See http://wiki.eclipse.org/Eclipse.ini for examples.

If you're unsure of what version (64-bit or 32-bit) of Eclipse you have installed, you can determine that a few different ways. See How to find out if an installed Eclipse is 32 or 64 bit version?

Restoring MySQL database from physical files

In my case, simply removing the tc.log in /var/lib/mysql was enough to start mariadb/mysql again.

Create space at the beginning of a UITextField

Such margin can be achieved by setting leftView / rightView to UITextField.

Updated For Swift 4

// Create a padding view for padding on left
textField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: textField.frame.height))
textField.leftViewMode = .always

// Create a padding view for padding on right
textField.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: textField.frame.height))
textField.rightViewMode = .always

I just added/placed an UIView to left and right side of the textfield. So now the typing will start after the view.

Thanks

Hope this helped...

Triggering change detection manually in Angular

In Angular 2+, try the @Input decorator

It allows for some nice property binding between parent and child components.

First create a global variable in the parent to hold the object/property that will be passed to the child.

Next create a global variable in the child to hold the object/property passed from the parent.

Then in the parent html, where the child template is used, add square brackets notation with the name of the child variable, then set it equal to the name of the parent variable. Example:

<child-component-template [childVariable] = parentVariable>
</child-component-template>

Finally, where the child property is defined in the child component, add the Input decorator:

@Input()
public childVariable: any

When your parent variable is updated, it should pass the updates to the child component, which will update its html.

Also, to trigger a function in the child component, take a look at ngOnChanges.

Keytool is not recognized as an internal or external command

A simple solution of error is that you first need to change the folder directory in command prompt. By default in command prompt or in terminal(Inside Android studio in the bottom)tab the path is set to C:\Users#Name of your PC that you selected\AndroidStudioProjects#app name\flutter_app> Change accordingly:- C:\Users#Name of your PC that you selected\AndroidStudioProjects#app name\flutter_app>cd\

type **cd** (#after flutter_app>), type only cd\ not comma's

then type cd Program Files\Java\jre1.8.0_251\bin (#remember to check the file name of jre properly)

now type keytool -list -v -keystore "%USERPROFILE%.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android (without anyspace type the command).

screenshot of the codes to run

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

How to download excel (.xls) file from API in postman?

If the endpoint really is a direct link to the .xls file, you can try the following code to handle downloading:

public static boolean download(final File output, final String source) {
    try {
        if (!output.createNewFile()) {
            throw new RuntimeException("Could not create new file!");
        }
        URL url = new URL(source);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // Comment in the code in the following line in case the endpoint redirects instead of it being a direct link
        // connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("AUTH-KEY-PROPERTY-NAME", "yourAuthKey");
        final ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
        final FileOutputStream fos = new FileOutputStream(output);
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
        fos.close();
        return true;
    } catch (final Exception e) {
        e.printStackTrace();
    }
    return false;
}

All you should need to do is set the proper name for the auth token and fill it in.

Example usage:

download(new File("C:\\output.xls"), "http://www.website.com/endpoint");

MVC 4 Razor File Upload

I think, better way is use HttpPostedFileBase in your controller or API. After this you can simple detect size, type etc.

File properties you can find here:

MVC3 How to check if HttpPostedFileBase is an image

For example ImageApi:

[HttpPost]
[Route("api/image")]  
public ActionResult Index(HttpPostedFileBase file)  
{  
    if (file != null && file.ContentLength > 0)  
        try 
        {  
            string path = Path.Combine(Server.MapPath("~/Images"),  
               Path.GetFileName(file.FileName));

            file.SaveAs(path);  
            ViewBag.Message = "Your message for success";  
        }  
        catch (Exception ex)  
        {  
            ViewBag.Message = "ERROR:" + ex.Message.ToString();  
        }  
    else 
    {  
        ViewBag.Message = "Please select file";  
    }  
    return View();  
}

Hope it help.

afxwin.h file is missing in VC++ Express Edition

I see the question is about Express Edition, but this topic is easy to pop up in Google Search, and doesn't have a solution for other editions.

So. If you run into this problem with any VS Edition except Express, you can rerun installation and include MFC files.

How to remove unused C/C++ symbols with GCC and ld?

The answer is -flto. You have to pass it to both your compilation and link steps, otherwise it doesn't do anything.

It actually works very well - reduced the size of a microcontroller program I wrote to less than 50% of its previous size!

Unfortunately it did seem a bit buggy - I had instances of things not being built correctly. It may have been due to the build system I'm using (QBS; it's very new), but in any case I'd recommend you only enable it for your final build if possible, and test that build thoroughly.

How to debug apk signed for release?

Besides Manuel's way, you can still use the Manifest.

In Android Studio stable, you have to add the following 2 lines to application in the AndroidManifest file:

    android:debuggable="true"
    tools:ignore="HardcodedDebugMode"

The first one will enable debugging of signed APK, and the second one will prevent compile-time error.

After this, you can attach to the process via "Attach debugger to Android process" button.

How to get a shell environment variable in a makefile?

all:
    echo ${PATH}

Or change PATH just for one command:

all:
    PATH=/my/path:${PATH} cmd

TypeError: $(...).DataTable is not a function

CAUSE

There could be multiple reasons for this error.

  • jQuery DataTables library is missing.
  • jQuery library is loaded after jQuery DataTables.
  • Multiple versions of jQuery library is loaded.

SOLUTION

Include only one version of jQuery library version 1.7 or newer before jQuery DataTables.

For example:

<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.min.js" type="text/javascript"></script>

See jQuery DataTables: Common JavaScript console errors for more information on this and other common console errors.

Delete last N characters from field in a SQL Server database

I got the answer to my own question, ant this is:

select reverse(stuff(reverse('a,b,c,d,'), 1, N, ''))

Where N is the number of characters to remove. This avoids to write the complex column/string twice

How to mock private method for testing using PowerMock?

For some reason Brice's answer is not working for me. I was able to manipulate it a bit to get it to work. It might just be because I have a newer version of PowerMock. I'm using 1.6.5.

import java.util.Random;

public class CodeWithPrivateMethod {

    public void meaningfulPublicApi() {
        if (doTheGamble("Whatever", 1 << 3)) {
            throw new RuntimeException("boom");
        }
    }

    private boolean doTheGamble(String whatever, int binary) {
        Random random = new Random(System.nanoTime());
        boolean gamble = random.nextBoolean();
        return gamble;
    }
}

The test class looks as follows:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.doReturn;

@RunWith(PowerMockRunner.class)
@PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {
    private CodeWithPrivateMethod classToTest;

    @Test(expected = RuntimeException.class)
    public void when_gambling_is_true_then_always_explode() throws Exception {
        classToTest = PowerMockito.spy(classToTest);

        doReturn(true).when(classToTest, "doTheGamble", anyString(), anyInt());

        classToTest.meaningfulPublicApi();
    }
}

How to redirect stderr and stdout to different files in the same line in script?

Just add them in one line command 2>> error 1>> output

However, note that >> is for appending if the file already has data. Whereas, > will overwrite any existing data in the file.

So, command 2> error 1> output if you do not want to append.

Just for completion's sake, you can write 1> as just > since the default file descriptor is the output. so 1> and > is the same thing.

So, command 2> error 1> output becomes, command 2> error > output

Why does python use 'else' after for and while loops?

A common construct is to run a loop until something is found and then to break out of the loop. The problem is that if I break out of the loop or the loop ends I need to determine which case happened. One method is to create a flag or store variable that will let me do a second test to see how the loop was exited.

For example assume that I need to search through a list and process each item until a flag item is found and then stop processing. If the flag item is missing then an exception needs to be raised.

Using the Python for...else construct you have

for i in mylist:
    if i == theflag:
        break
    process(i)
else:
    raise ValueError("List argument missing terminal flag.")

Compare this to a method that does not use this syntactic sugar:

flagfound = False
for i in mylist:
    if i == theflag:
        flagfound = True
        break
    process(i)

if not flagfound:
    raise ValueError("List argument missing terminal flag.")

In the first case the raise is bound tightly to the for loop it works with. In the second the binding is not as strong and errors may be introduced during maintenance.

Table with 100% width with equal size columns

Just add style="table-layout: fixed ; width: 100%;" inside <table> tag and also if you do not specify any styles and add just style=" width: 100%;" inside <table> You will be able to resolve it.

How can I get the max (or min) value in a vector?

#include <stdlib.h>
#include <stdio.h>

int main()
{

    int vector[500];

    vector[0] = 100;
    vector[1] = 2;
    vector[2] = 1239;
    vector[3] = 5;
    vector[4] = 10;
    vector[5] = 1;
    vector[6] = 123;
    vector[7] = 1000;
    vector[8] = 9;
    vector[9] = 123;
    vector[10] = 10;

    int i = 0;

    int winner = vector[0];

    for(i=0;i < 10; i++)
    {
        printf("vector = %d \n", vector[i]);

        if(winner > vector[i])
        {
            printf("winner was %d \n", winner);
            winner = vector[i];
            printf("but now is %d \n", winner);
        }
    }

    printf("the minimu is %d", winner);
}

The complet nooby way... in C

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

There is no difference until you compile to same target architecture. I suppose you are compiling for 32 bit architecture in both cases.

It's worth mentioning that OutOfMemoryException can also be raised if you get 2GB of memory allocated by a single collection in CLR (say List<T>) on both architectures 32 and 64 bit.

To be able to benefit from memory goodness on 64 bit architecture, you have to compile your code targeting 64 bit architecture. After that, naturally, your binary will run only on 64 bit, but will benefit from possibility having more space available in RAM.

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

Laravel Pagination links not including other GET parameters

In Laravel 7.x you can use it like this:

{{ $results->withQueryString()->links() }}

SSRS custom number format

You can use

 =Format(Fields!myField.Value,"F2") 

How to start Apache and MySQL automatically when Windows 8 comes up

If on your system User Control Account is Off then you can run the XAMPP as Administrator and check the boxes for run as service.

And if on your system User Control Account is On then it may not work. You have go to Configuration files and manually install as a service or run apache_installservice.bat for Apache and mysql_installservice.bat for MySQL at the path

  1. C:\xampp\apache
  2. C:\xampp\mysql

if path is the default path.

What is the difference between properties and attributes in HTML?

The answers already explain how attributes and properties are handled differently, but I really would like to point out how totally insane this is. Even if it is to some extent the spec.

It is crazy, to have some of the attributes (e.g. id, class, foo, bar) to retain only one kind of value in the DOM, while some attributes (e.g. checked, selected) to retain two values; that is, the value "when it was loaded" and the value of the "dynamic state". (Isn't the DOM supposed to be to represent the state of the document to its full extent?)

It is absolutely essential, that two input fields, e.g. a text and a checkbox behave the very same way. If the text input field does not retain a separate "when it was loaded" value and the "current, dynamic" value, why does the checkbox? If the checkbox does have two values for the checked attribute, why does it not have two for its class and id attributes? If you expect to change the value of a text *input* field, and you expect the DOM (i.e. the "serialized representation") to change, and reflect this change, why on earth would you not expect the same from an input field of type checkbox on the checked attribute?

The differentiation, of "it is a boolean attribute" just does not make any sense to me, or is, at least not a sufficient reason for this.

Installing RubyGems in Windows

Installing Ruby

Go to http://rubyinstaller.org/downloads/

Make sure that you check "Add ruby ... to your PATH". enter image description here

Now you can use "ruby" in your "cmd".

If you installed ruby 1.9.3 I expect that the ruby is downloaded in C:\Ruby193.

Installing Gem

install Development Kit in rubyinstaller. Make new folder such as C:\RubyDevKit and unzip.

Go to the devkit directory and type ruby dk.rb init to generate config.yml.

If you installed devkit for 1.9.3, I expect that the config.yml will be written as C:\Ruby193.

If not, please correct path to your ruby folders.

After reviewing the config.yml, you can finally type ruby dk.rb install.

Now you can use "gem" in your "cmd". It's done!

How to convert integer to decimal in SQL Server query?

select cast (height as decimal)/10 as HeightDecimal

How to solve the memory error in Python

Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:

In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75

Doing some rough math:

75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB

So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.

If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.

How to use pip on windows behind an authenticating proxy

install cntlm: Cntlm: Fast NTLM Authentication Proxy in C

Config cntlm.ini:

Username ob66759

Domain NAM

Password secret

Proxy proxy1.net:8080

Proxy proxy2.net:8080

NoProxy localhost, 127.0.0.*, 10.*, 192.168.*

Listen 3128

Allow 127.0.0.1

#your IP

Allow 10.106.18.138

start it:

cntlm -v -c cntlm.ini

Now in cmd.exe:

pip install --upgrade pip --proxy 127.0.0.1:3128

Collecting pip
  Downloading https://files.pythonhosted.
44c8a6e917c1820365cbebcb6a8974d1cd045ab4/

    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦
Installing collected packages: pip
  Found existing installation: pip 9.0.1
    Uninstalling pip-9.0.1:
      Successfully uninstalled pip-9.0.1

Successfully installed pip-10.0.1

works!

You can also hide password: https://stormpoopersmith.com/2012/03/20/using-applications-behind-a-corporate-proxy/

X close button only using css

Try This Cross In CSS

_x000D_
_x000D_
.close {_x000D_
  position: absolute;_x000D_
  right: 32px;_x000D_
  top: 32px;_x000D_
  width: 32px;_x000D_
  height: 32px;_x000D_
  opacity: 0.3;_x000D_
}_x000D_
.close:hover {_x000D_
  opacity: 1;_x000D_
}_x000D_
.close:before, .close:after {_x000D_
  position: absolute;_x000D_
  left: 15px;_x000D_
  content: ' ';_x000D_
  height: 33px;_x000D_
  width: 2px;_x000D_
  background-color: #333;_x000D_
}_x000D_
.close:before {_x000D_
  transform: rotate(45deg);_x000D_
}_x000D_
.close:after {_x000D_
  transform: rotate(-45deg);_x000D_
}
_x000D_
<a href="#" class="close">
_x000D_
_x000D_
_x000D_

Creating a Shopping Cart using only HTML/JavaScript

You simply need to use simpleCart

It is a free and open-source javascript shopping cart that easily integrates with your current website.

You will get the full source code at github

Built in Python hash() function

The value of PYTHONHASHSEED might be used to initialize the hash values.

Try:

PYTHONHASHSEED python -c 'print(hash('http://stackoverflow.com'))'

How to add screenshot to READMEs in github repository?

JUNE 3, 2020 : WORKING ANSWER-

  1. Upload your image to postimage.org
  2. Copy Github-Markdown-Url after uploading Image
  3. Insert in your ReadMe

How to select a radio button by default?

Use the checked attribute.

<input type="radio" name="imgsel"  value="" checked /> 

or

<input type="radio" name="imgsel"  value="" checked="checked" /> 

How do I reverse a commit in git?

Unable to comment on others answers, I'll provide a bit of extra information.

If you want to revert the last commit, you can use git revert head. head refers to the most recent commit in your branch.

The reason you use head~1 when using reset is that you are telling Git to "remove all changes in the commits after" (reset --hard) "the commit one before head" (head~1).

reset is to a commit, revert is on a commit.

As AmpT pointed out, you can also use the commit SHA to identify it, rather than counting how far away from head it is. The SHA can be found in the logs (git log) and a variety of other ways.

You can also always use any other pointers in Git. e.g. a tag or branch. And can also use all of these fun other ways to reference commits https://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html#_specifying_revisions