Programs & Examples On #Structlayout

Failed to build gem native extension (installing Compass)

On Mac OS X 10.9, if you try xcode-select --install, you will get the following error :

Can't install the software because it is not currently available from the Software Update server.

The solution is to download Command Line Tools (OS X 10.9) directly from Apple website : https://developer.apple.com/downloads/index.action?name=for%20Xcode%20-

You will then be able to install the last version of Command Line Tools.

Bulk create model objects in django

Using create will cause one query per new item. If you want to reduce the number of INSERT queries, you'll need to use something else.

I've had some success using the Bulk Insert snippet, even though the snippet is quite old. Perhaps there are some changes required to get it working again.

http://djangosnippets.org/snippets/446/

jquery stop child triggering parent event

The answers here took the OP's question too literally. How can these answers be expanded into a scenario where there are MANY child elements, not just a single <a> tag? Here's one way.

Let's say you have a photo gallery with a blacked out background and the photos centered in the browser. When you click the black background (but not anything inside of it) you want the overlay to close.

Here's some possible HTML:

<div class="gallery" style="background: black">
    <div class="contents"> <!-- Let's say this div is 50% wide and centered -->
        <h1>Awesome Photos</h1>
        <img src="img1.jpg"><br>
        <img src="img2.jpg"><br>
        <img src="img3.jpg"><br>
        <img src="img4.jpg"><br>
        <img src="img5.jpg">
    </div>
</div>

And here's how the JavaScript would work:

$('.gallery').click(
    function()
    {
        $(this).hide();
    }
);

$('.gallery > .contents').click(
    function(e) {
        e.stopPropagation();
    }
);

This will stop the click events from elements inside .contents from every research .gallery so the gallery will close only when you click in the faded black background area, but not when you click in the content area. This can be applied to many different scenarios.

How to iterate over the keys and values with ng-repeat in AngularJS?

we can follow below procedure to avoid display of key-values in alphabetical order.

Javascript

$scope.data = {
   "id": 2,
   "project": "wewe2012",
   "date": "2013-02-26",
   "description": "ewew",
   "eet_no": "ewew",
};
var array = [];
for(var key in $scope.data){
    var test = {};
    test[key]=$scope.data[key];
    array.push(test);
}
$scope.data = array;

HTML

<p ng-repeat="obj in data">
   <font ng-repeat="(key, value) in obj">
      {{key}} : {{value}}
   </font>
</p>

How can we print line numbers to the log in java

The code posted by @simon.buchan will work...

Thread.currentThread().getStackTrace()[2].getLineNumber()

But if you call it in a method it will always return the line number of the line in the method so rather use the code snippet inline.

Equals(=) vs. LIKE

Besides the wildcards, the difference between = AND LIKE will depend on both the kind of SQL server and on the column type.

Take this example:

CREATE TABLE testtable (
  varchar_name VARCHAR(10),
  char_name CHAR(10),
  val INTEGER
);

INSERT INTO testtable(varchar_name, char_name, val)
    VALUES ('A', 'A', 10), ('B', 'B', 20);

SELECT 'VarChar Eq Without Space', val FROM testtable WHERE varchar_name='A'
UNION ALL
SELECT 'VarChar Eq With Space', val FROM testtable WHERE varchar_name='A '
UNION ALL
SELECT 'VarChar Like Without Space', val FROM testtable WHERE varchar_name LIKE 'A'
UNION ALL
SELECT 'VarChar Like Space', val FROM testtable WHERE varchar_name LIKE 'A '
UNION ALL
SELECT 'Char Eq Without Space', val FROM testtable WHERE char_name='A'
UNION ALL
SELECT 'Char Eq With Space', val FROM testtable WHERE char_name='A '
UNION ALL
SELECT 'Char Like Without Space', val FROM testtable WHERE char_name LIKE 'A'
UNION ALL
SELECT 'Char Like With Space', val FROM testtable WHERE char_name LIKE 'A '
  • Using MS SQL Server 2012, the trailing spaces will be ignored in the comparison, except with LIKE when the column type is VARCHAR.

  • Using MySQL 5.5, the trailing spaces will be ignored for =, but not for LIKE, both with CHAR and VARCHAR.

  • Using PostgreSQL 9.1, spaces are significant with both = and LIKE using VARCHAR, but not with CHAR (see documentation).

    The behaviour with LIKE also differs with CHAR.

    Using the same data as above, using an explicit CAST on the column name also makes a difference:

    SELECT 'CAST none', val FROM testtable WHERE char_name LIKE 'A'
    UNION ALL
    SELECT 'CAST both', val FROM testtable WHERE
        CAST(char_name AS CHAR) LIKE CAST('A' AS CHAR)
    UNION ALL
    SELECT 'CAST col', val FROM testtable WHERE CAST(char_name AS CHAR) LIKE 'A'
    UNION ALL
    SELECT 'CAST value', val FROM testtable WHERE char_name LIKE CAST('A' AS CHAR)
    

    This only returns rows for "CAST both" and "CAST col".

AngularJS: How can I pass variables between controllers?

There are two ways to do this

1) Use get/set service

2) $scope.$emit('key', {data: value}); //to set the value

 $rootScope.$on('key', function (event, data) {}); // to get the value

Validate SSL certificates with Python

Here's an example script which demonstrates certificate validation:

import httplib
import re
import socket
import sys
import urllib2
import ssl

class InvalidCertificateException(httplib.HTTPException, urllib2.URLError):
    def __init__(self, host, cert, reason):
        httplib.HTTPException.__init__(self)
        self.host = host
        self.cert = cert
        self.reason = reason

    def __str__(self):
        return ('Host %s returned an invalid certificate (%s) %s\n' %
                (self.host, self.reason, self.cert))

class CertValidatingHTTPSConnection(httplib.HTTPConnection):
    default_port = httplib.HTTPS_PORT

    def __init__(self, host, port=None, key_file=None, cert_file=None,
                             ca_certs=None, strict=None, **kwargs):
        httplib.HTTPConnection.__init__(self, host, port, strict, **kwargs)
        self.key_file = key_file
        self.cert_file = cert_file
        self.ca_certs = ca_certs
        if self.ca_certs:
            self.cert_reqs = ssl.CERT_REQUIRED
        else:
            self.cert_reqs = ssl.CERT_NONE

    def _GetValidHostsForCert(self, cert):
        if 'subjectAltName' in cert:
            return [x[1] for x in cert['subjectAltName']
                         if x[0].lower() == 'dns']
        else:
            return [x[0][1] for x in cert['subject']
                            if x[0][0].lower() == 'commonname']

    def _ValidateCertificateHostname(self, cert, hostname):
        hosts = self._GetValidHostsForCert(cert)
        for host in hosts:
            host_re = host.replace('.', '\.').replace('*', '[^.]*')
            if re.search('^%s$' % (host_re,), hostname, re.I):
                return True
        return False

    def connect(self):
        sock = socket.create_connection((self.host, self.port))
        self.sock = ssl.wrap_socket(sock, keyfile=self.key_file,
                                          certfile=self.cert_file,
                                          cert_reqs=self.cert_reqs,
                                          ca_certs=self.ca_certs)
        if self.cert_reqs & ssl.CERT_REQUIRED:
            cert = self.sock.getpeercert()
            hostname = self.host.split(':', 0)[0]
            if not self._ValidateCertificateHostname(cert, hostname):
                raise InvalidCertificateException(hostname, cert,
                                                  'hostname mismatch')


class VerifiedHTTPSHandler(urllib2.HTTPSHandler):
    def __init__(self, **kwargs):
        urllib2.AbstractHTTPHandler.__init__(self)
        self._connection_args = kwargs

    def https_open(self, req):
        def http_class_wrapper(host, **kwargs):
            full_kwargs = dict(self._connection_args)
            full_kwargs.update(kwargs)
            return CertValidatingHTTPSConnection(host, **full_kwargs)

        try:
            return self.do_open(http_class_wrapper, req)
        except urllib2.URLError, e:
            if type(e.reason) == ssl.SSLError and e.reason.args[0] == 1:
                raise InvalidCertificateException(req.host, '',
                                                  e.reason.args[1])
            raise

    https_request = urllib2.HTTPSHandler.do_request_

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print "usage: python %s CA_CERT URL" % sys.argv[0]
        exit(2)

    handler = VerifiedHTTPSHandler(ca_certs = sys.argv[1])
    opener = urllib2.build_opener(handler)
    print opener.open(sys.argv[2]).read()

Downloading a picture via urllib and python

I have found this answer and I edit that in more reliable way

def download_photo(self, img_url, filename):
    try:
        image_on_web = urllib.urlopen(img_url)
        if image_on_web.headers.maintype == 'image':
            buf = image_on_web.read()
            path = os.getcwd() + DOWNLOADED_IMAGE_PATH
            file_path = "%s%s" % (path, filename)
            downloaded_image = file(file_path, "wb")
            downloaded_image.write(buf)
            downloaded_image.close()
            image_on_web.close()
        else:
            return False    
    except:
        return False
    return True

From this you never get any other resources or exceptions while downloading.

Spring Boot application as a Service

I don't know of a "standard" shrink-wrapped way to do that with a Java app, but it's definitely a good idea (you want to benefit from the keep-alive and monitoring capabilities of the operating system if they are there). It's on the roadmap to provide something from the Spring Boot tool support (maven and gradle), but for now you are probably going to have to roll your own. The best solution I know of right now is Foreman, which has a declarative approach and one line commands for packaging init scripts for various standard OS formats (monit, sys V, upstart etc.). There is also evidence of people having set stuff up with gradle (e.g. here).

mysql: see all open connections to a given database?

As well you can use:

mysql> show status like '%onn%';
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| Aborted_connects         | 0     |
| Connections              | 303   |
| Max_used_connections     | 127   |
| Ssl_client_connects      | 0     |
| Ssl_connect_renegotiates | 0     |
| Ssl_finished_connects    | 0     |
| Threads_connected        | 127   |
+--------------------------+-------+
7 rows in set (0.01 sec)

Feel free to use Mysql-server-status-variables or Too-many-connections-problem

fast way to copy formatting in excel

For me, you can't. But if that suits your needs, you could have speed and formatting by copying the whole range at once, instead of looping:

range("B2:B5002").Copy Destination:=Sheets("Output").Cells(startrow, 2)

And, by the way, you can build a custom range string, like Range("B2:B4, B6, B11:B18")


edit: if your source is "sparse", can't you just format the destination at once when the copy is finished ?

What's the difference between all the Selection Segues?

Here is a quick summary of the segues and an example for each type.

Show - Pushes the destination view controller onto the navigation stack, sliding overtop from right to left, providing a back button to return to the source - or if not embedded in a navigation controller it will be presented modally
Example: Navigating inboxes/folders in Mail

Show Detail - For use in a split view controller, replaces the detail/secondary view controller when in an expanded 2 column interface, otherwise if collapsed to 1 column it will push in a navigation controller
Example: In Messages, tapping a conversation will show the conversation details - replacing the view controller on the right when in a two column layout, or push the conversation when in a single column layout

Present Modally - Presents a view controller in various animated fashions as defined by the Presentation option, covering the previous view controller - most commonly used to present a view controller that animates up from the bottom and covers the entire screen on iPhone, or on iPad it's common to present it as a centered box that darkens the presenting view controller
Example: Selecting Touch ID & Passcode in Settings

Popover Presentation - When run on iPad, the destination appears in a popover, and tapping anywhere outside of this popover will dismiss it, or on iPhone popovers are supported as well but by default it will present the destination modally over the full screen
Example: Tapping the + button in Calendar

Custom - You may implement your own custom segue and have control over its behavior

The deprecated segues are essentially the non-adaptive equivalents of those described above. These segue types were deprecated in iOS 8: Push, Modal, Popover, Replace.

For more info, you may read over the Using Segues documentation which also explains the types of segues and how to use them in a Storyboard. Also check out Session 216 Building Adaptive Apps with UIKit from WWDC 2014. They talked about how you can build adaptive apps using these new Adaptive Segues, and they built a demo project that utilizes these segues.

String split on new line, tab and some number of spaces

You can kill two birds with one regex stone:

>>> r = """
... \n\tName: John Smith
... \n\t  Home: Anytown USA
... \n\t    Phone: 555-555-555
... \n\t  Other Home: Somewhere Else
... \n\t Notes: Other data
... \n\tName: Jane Smith
... \n\t  Misc: Data with spaces
... """
>>> import re
>>> print re.findall(r'(\S[^:]+):\s*(.*\S)', r)
[('Name', 'John Smith'), ('Home', 'Anytown USA'), ('Phone', '555-555-555'), ('Other Home', 'Somewhere Else'), ('Notes', 'Other data'), ('Name', 'Jane Smith'), ('Misc', 'Data with spaces')]
>>> 

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

Echo newline in Bash prints literal \n

echo $'hello\nworld'

prints

hello
world

$'' strings use ANSI C Quoting:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.

how can I set visible back to true in jquery

Depends, if i remember correctly i think asp.net won't render the html object out when you set visible to false.

If you want to be able to control it from the client side, then you better just include the css value to set it invisible rather than using visible =false.

React-Native: Application has not been registered error

you need to register it in index.android.js / index.ios.js

like this:

'use strict';

import {
    AppRegistry
} from 'react-native';

import app from "./app";

AppRegistry.registerComponent('test', () => app);

PHP Array to JSON Array using json_encode();

If you don't specify indexes on your initial array, you get the regular numric ones. Arrays must have some form of unique index

Writing unit tests in Python: How do I start?

If you're brand new to using unittests, the simplest approach to learn is often the best. On that basis along I recommend using py.test rather than the default unittest module.

Consider these two examples, which do the same thing:

Example 1 (unittest):

import unittest

class LearningCase(unittest.TestCase):
    def test_starting_out(self):
        self.assertEqual(1, 1)

def main():
    unittest.main()

if __name__ == "__main__":
    main()

Example 2 (pytest):

def test_starting_out():
    assert 1 == 1

Assuming that both files are named test_unittesting.py, how do we run the tests?

Example 1 (unittest):

cd /path/to/dir/
python test_unittesting.py

Example 2 (pytest):

cd /path/to/dir/
py.test

Using Vim's tabs like buffers

If you want buffers to work like tabs, check out the tabline plugin.

That uses a single window, and adds a line on the top to simulate the tabs (just showing the list of buffers). This came out a long time ago when tabs were only supported in GVim but not in the command line vim. Since it is only operating with buffers, everything integrates well with the rest of vim.

Selecting only numeric columns from a data frame

Filter() from the base package is the perfect function for that use-case: You simply have to code:

Filter(is.numeric, x)

It is also much faster than select_if():

library(microbenchmark)
microbenchmark(
    dplyr::select_if(mtcars, is.numeric),
    Filter(is.numeric, mtcars)
)

returns (on my computer) a median of 60 microseconds for Filter, and 21 000 microseconds for select_if (350x faster).

Dynamic function name in javascript?

If you want to have a dynamic function like the __call function in PHP, you could use Proxies.

const target = {};

const handler = {
  get: function (target, name) {
    return (myArg) => {
      return new Promise(resolve => setTimeout(() => resolve('some' + myArg), 600))
    }
  }
};

const proxy = new Proxy(target, handler);

(async function() {
  const result = await proxy.foo('string')
  console.log('result', result) // 'result somestring' after 600 ms
})()

Printing to the console in Google Apps Script?

Updated for 2020

In February of 2020, Google announced a major upgrade to the built-in Google Apps Script IDE, and it now supports console.log(). So, you can now use both:

  1. Logger.log()
  2. console.log()

Happy coding!

When to use pthread_exit() and when to use pthread_join() in Linux?

  #include<stdio.h>
  #include<pthread.h>
  #include<semaphore.h>
 
   sem_t st;
   void *fun_t(void *arg);
   void *fun_t(void *arg)
   {
       printf("Linux\n");
       sem_post(&st);
       //pthread_exit("Bye"); 
       while(1);
       pthread_exit("Bye");
   }
   int main()
   {
       pthread_t pt;
       void *res_t;
       if(pthread_create(&pt,NULL,fun_t,NULL) == -1)
           perror("pthread_create");
       if(sem_init(&st,0,0) != 0)
           perror("sem_init");
       if(sem_wait(&st) != 0)
           perror("sem_wait");
       printf("Sanoundry\n");
       //Try commenting out join here.
       if(pthread_join(pt,&res_t) == -1)
           perror("pthread_join");
       if(sem_destroy(&st) != 0)
           perror("sem_destroy");
       return 0;
   }

Copy and paste this code on a gdb. Onlinegdb would work and see for yourself.

Make sure you understand once you have created a thread, the process run along with main together at the same time.

  1. Without the join, main thread continue to run and return 0
  2. With the join, main thread would be stuck in the while loop because it waits for the thread to be done executing.
  3. With the join and delete the commented out pthread_exit, the thread will terminate before running the while loop and main would continue
  4. Practical usage of pthread_exit can be used as an if conditions or case statements to ensure 1 version of some code runs before exiting.
void *fun_t(void *arg)
   {
       printf("Linux\n");
       sem_post(&st); 
       if(2-1 == 1)  
           pthread_exit("Bye");
       else
       { 
           printf("We have a problem. Computer is bugged");
           pthread_exit("Bye"); //This is redundant since the thread will exit at the end
                                //of scope. But there are instances where you have a bunch
                                //of else if here.
       }
   }

I would want to demonstrate how sometimes you would need to have a segment of code running first using semaphore in this example.

#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>

sem_t st;

void* fun_t (void* arg)
{
    printf("I'm thread\n");
    sem_post(&st);
}

int main()
{
    pthread_t pt;
    pthread_create(&pt,NULL,fun_t,NULL);
    sem_init(&st,0,0);
    sem_wait(&st);
    printf("before_thread\n");
    pthread_join(pt,NULL);
    printf("After_thread\n");
    
}

Noticed how fun_t is being ran after "before thread" The expected output if it is linear from top to bottom would be before thread, I'm thread, after thread. But under this circumstance, we block the main from running any further until the semaphore is released by func_t. The result can be verified with https://www.onlinegdb.com/

Is there a way to use two CSS3 box shadows on one element?

You can comma-separate shadows:

box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;

How do I create directory if it doesn't exist to create a file?

You can use File.Exists to check if the file exists and create it using File.Create if required. Make sure you check if you have access to create files at that location.

Once you are certain that the file exists, you can write to it safely. Though as a precaution, you should put your code into a try...catch block and catch for the exceptions that function is likely to raise if things don't go exactly as planned.

Additional information for basic file I/O concepts.

Detecting a mobile browser

According to MDN's article on Browser detection using the user agent, it is encouraged to avoid this approach if possible and suggest other avenues such as feature detection.

However, if one must use the user agent as a means to detect if the device is mobile, they suggest:

In summary, we recommend looking for the string “Mobi” anywhere in the User Agent to detect a mobile device.

Therefore, this one-liner will suffice:

const isMobileDevice = window.navigator.userAgent.toLowerCase().includes("mobi");

[UPDATE]:

As @zenw0lf suggests in the comments, using a Regular Expression would be better:

const isMobileDevice = /Mobi/i.test(window.navigator.userAgent)

What are best practices for REST nested resources?

I've read all of the above answers but it seems like they have no common strategy. I found a good article about best practices in Design API from Microsoft Documents. I think you should refer.

In more complex systems, it can be tempting to provide URIs that enable a client to navigate through several levels of relationships, such as /customers/1/orders/99/products. However, this level of complexity can be difficult to maintain and is inflexible if the relationships between resources change in the future. Instead, try to keep URIs relatively simple. Once an application has a reference to a resource, it should be possible to use this reference to find items related to that resource. The preceding query can be replaced with the URI /customers/1/orders to find all the orders for customer 1, and then /orders/99/products to find the products in this order.

.

Tip

Avoid requiring resource URIs more complex than collection/item/collection.

Select Specific Columns from Spark DataFrame

Just by using select select you can select particular columns, give them readable names and cast them. For example like this:

spark.read.csv(path).select(
          '_c0.alias("stn").cast(StringType),
          '_c1.alias("wban").cast(StringType),
          '_c2.alias("lat").cast(DoubleType),
          '_c3.alias("lon").cast(DoubleType)
        )
          .where('_c2.isNotNull && '_c3.isNotNull && '_c2 =!= 0.0 && '_c3 =!= 0.0)

Take multiple lists into dataframe

I think you're almost there, try removing the extra square brackets around the lst's (Also you don't need to specify the column names when you're creating a dataframe from a dict like this):

import pandas as pd
lst1 = range(100)
lst2 = range(100)
lst3 = range(100)
percentile_list = pd.DataFrame(
    {'lst1Title': lst1,
     'lst2Title': lst2,
     'lst3Title': lst3
    })

percentile_list
    lst1Title  lst2Title  lst3Title
0          0         0         0
1          1         1         1
2          2         2         2
3          3         3         3
4          4         4         4
5          5         5         5
6          6         6         6
...

If you need a more performant solution you can use np.column_stack rather than zip as in your first attempt, this has around a 2x speedup on the example here, however comes at bit of a cost of readability in my opinion:

import numpy as np
percentile_list = pd.DataFrame(np.column_stack([lst1, lst2, lst3]), 
                               columns=['lst1Title', 'lst2Title', 'lst3Title'])

How to check if a process is in hang state (Linux)

What do you mean by ‘hang state’? Typically, a process that is unresponsive and using 100% of a CPU is stuck in an endless loop. But there's no way to determine whether that has happened or whether the process might not eventually reach a loop exit state and carry on.

Desktop hang detectors just work by sending a message to the application's event loop and seeing if there's any response. If there's not for a certain amount of time they decide the app has ‘hung’... but it's entirely possible it was just doing something complicated and will come back to life in a moment once it's done. Anyhow, that's not something you can use for any arbitrary process.

Find the location of a character in string

You can use gregexpr

 gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired")


[[1]]
[1]  4 24
attr(,"match.length")
[1] 1 1
attr(,"useBytes")
[1] TRUE

or perhaps str_locate_all from package stringr which is a wrapper for gregexpr stringi::stri_locate_all (as of stringr version 1.0)

library(stringr)
str_locate_all(pattern ='2', "the2quickbrownfoxeswere2tired")

[[1]]
     start end
[1,]     4   4
[2,]    24  24

note that you could simply use stringi

library(stringi)
stri_locate_all(pattern = '2', "the2quickbrownfoxeswere2tired", fixed = TRUE)

Another option in base R would be something like

lapply(strsplit(x, ''), function(x) which(x == '2'))

should work (given a character vector x)

How can I sort one set of data to match another set of data in Excel?

You can use VLOOKUP.

Assuming those are in columns A and B in Sheet1 and Sheet2 each, 22350 is in cell A2 of Sheet1, you can use:

=VLOOKUP(A2, Sheet2!A:B, 2, 0)

This will return you #N/A if there are no matches. Drag/Fill/Copy&Paste the formula to the bottom of your table and that should do it.

Randomize a List<T>

A very simple approach to this kind of problem is to use a number of random element swap in the list.

In pseudo-code this would look like this:

do 
    r1 = randomPositionInList()
    r2 = randomPositionInList()
    swap elements at index r1 and index r2 
for a certain number of times

What is bootstrapping?

The term "bootstrapping" usually applies to a situation where a system depends on itself to start, sort of a chicken and egg problem.

For instance:

  • How do you compile a C compiler written in C?
  • How do you start an OS initialization process if you don't have the OS running yet?
  • How do you start a distributed (peer-to-peer) system where the clients depend on their currently known peers to find out about new peers in the system?

In that case, bootstrapping refers to a way of breaking the circular dependency, usually with the help of an external entity, e.g.

  • You can use another C compiler to compile (bootstrap) your own compiler, and then you can use it to recompile itself
  • You use a separate piece of code that sets up the initial process without depending on any functions provided by the OS
  • You use a hard-coded list of initial peers or a hard-coded tracker URL that supplies the peer list

etc.

Reading output of a command into an array in Bash

Here is an example. Imagine that you are going to put the files and directory names (under the current folder) to an array and count its items. The script would be like;

my_array=( `ls` )
my_array_length=${#my_array[@]}
echo $my_array_length

Or, you can iterate over this array by adding the following script:

for element in "${my_array[@]}"
do
   echo "${element}"
done

Please note that this is the core concept and the input is considered to be sanitized before, i.e. removing extra characters, handling empty Strings, and etc. (which is out of the topic of this thread).

Nginx no-www to www and www to no-www

You may find out you want to use the same config for more domains.

Following snippet removes www before any domain:

if ($host ~* ^www\.(.*)$) {
    rewrite / $scheme://$1 permanent;
}

Find all table names with column name?

Please try the below query. Use sys.columns to get the details :-

SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%MyCol%';

Java compiler level does not match the version of the installed Java project facet

In Eclipse, right click on your project, go to Maven> Update projetc. Wait and the error will disappear. This is already configured correctly the version of Java for this project.

enter image description here

How can I insert data into Database Laravel?

First method you can try this

$department->department_name = $request->department_name;
$department->status = $request->status;
$department->save();

Another way to insert records into the database with create function

$department = new Department;           
// Another Way to insert records
$department->create($request->all());

return redirect('admin/departments');

You need to set the filledby in Department model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model
{
    protected $fillable = ['department_name','status'];
} 

Importing json file in TypeScript

In your TS Definition file, e.g. typings.d.ts`, you can add this line:

declare module "*.json" {
const value: any;
export default value;
}

Then add this in your typescript(.ts) file:-

import * as data from './colors.json';
const word = (<any>data).name;

SQL Server - NOT IN

SELECT [T1].*
FROM [Table1] AS [T1]
WHERE  NOT EXISTS (SELECT 
    1 AS [C1]
    FROM [Table2] AS [T2]
    WHERE ([T2].[MAKE] = [T1].[MAKE]) AND
        ([T2].[MODEL] = [T1].[MODEL]) AND
        ([T2].[Serial Number] = [T1].[Serial Number])
);

What's in an Eclipse .classpath/.project file?

Eclipse is a runtime environment for plugins. Virtually everything you see in Eclipse is the result of plugins installed on Eclipse, rather than Eclipse itself.

The .project file is maintained by the core Eclipse platform, and its goal is to describe the project from a generic, plugin-independent Eclipse view. What's the project's name? what other projects in the workspace does it refer to? What are the builders that are used in order to build the project? (remember, the concept of "build" doesn't pertain specifically to Java projects, but also to other types of projects)

The .classpath file is maintained by Eclipse's JDT feature (feature = set of plugins). JDT holds multiple such "meta" files in the project (see the .settings directory inside the project); the .classpath file is just one of them. Specifically, the .classpath file contains information that the JDT feature needs in order to properly compile the project: the project's source folders (that is, what to compile); the output folders (where to compile to); and classpath entries (such as other projects in the workspace, arbitrary JAR files on the file system, and so forth).

Blindly copying such files from one machine to another may be risky. For example, if arbitrary JAR files are placed on the classpath (that is, JAR files that are located outside the workspace and are referred-to by absolute path naming), the .classpath file is rendered non-portable and must be modified in order to be portable. There are certain best practices that can be followed to guarantee .classpath file portability.

Resizing image in Java

If you have an java.awt.Image, rezising it doesn't require any additional libraries. Just do:

Image newImage = yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);

Ovbiously, replace newWidth and newHeight with the dimensions of the specified image.
Notice the last parameter: it tells to the runtime the algorithm you want to use for resizing.

There are algorithms that produce a very precise result, however these take a large time to complete.
You can use any of the following algorithms:

See the Javadoc for more info.

Removing empty lines in Notepad++

In notepad++ press CTRL+H , in search mode click on the "Extended (\n, \r, \t ...)" radio button then type in the "Find what" box: \r\n (short for CR LF) and leave the "Replace with" box empty..

Finally hit replace all

Finish all activities at a time

If rooted:

Runtime.getRuntime().exec("su -c service call activity 42 s16 com.example.your_app");

MySQL high CPU usage

As this is the top post if you google for MySQL high CPU usage or load, I'll add an additional answer:

On the 1st of July 2012, a leap second was added to the current UTC-time to compensate for the slowing rotation of the earth due to the tides. When running ntp (or ntpd) this second was added to your computer's/server's clock. MySQLd does not seem to like this extra second on some OS'es, and yields a high CPU load. The quick fix is (as root):

$ /etc/init.d/ntpd stop
$ date -s "`date`"
$ /etc/init.d/ntpd start

Printing all global variables/local variables?

In case you want to see the local variables of a calling function use select-frame before info locals

E.g.:

(gdb) bt
#0  0xfec3c0b5 in _lwp_kill () from /lib/libc.so.1
#1  0xfec36f39 in thr_kill () from /lib/libc.so.1
#2  0xfebe3603 in raise () from /lib/libc.so.1
#3  0xfebc2961 in abort () from /lib/libc.so.1
#4  0xfebc2bef in _assert_c99 () from /lib/libc.so.1
#5  0x08053260 in main (argc=1, argv=0x8047958) at ber.c:480
(gdb) info locals
No symbol table info available.
(gdb) select-frame 5
(gdb) info locals
i = 28
(gdb) 

Testing web application on Mac/Safari when I don't own a Mac

Meanwhile, MacOS High Sierra can be run in VirtualBox (on a PC) for Free. It's not really fast but it works for general browser testing.

How to setup see here: https://www.howtogeek.com/289594/how-to-install-macos-sierra-in-virtualbox-on-windows-10/

I'm using this for a while now and it works quite well

How do I add an "Add to Favorites" button or link on my website?

I have faced some problems with rel="sidebar". when I add it in link tag bookmarking will work on FF but stop working in other browser. so I fix that by adding rel="sidebar" dynamic by code:

jQuery('.bookmarkMeLink').click(function() {
    if (window.sidebar && window.sidebar.addPanel) { 
        // Mozilla Firefox Bookmark
        window.sidebar.addPanel(document.title,window.location.href,'');
    }
    else if(window.sidebar && jQuery.browser.mozilla){
        //for other version of FF add rel="sidebar" to link like this:
        //<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
        jQuery(this).attr('rel', 'sidebar');
    }
    else if(window.external && ('AddFavorite' in window.external)) { 
        // IE Favorite
        window.external.AddFavorite(location.href,document.title); 
    } else if(window.opera && window.print) { 
        // Opera Hotlist
        this.title=document.title;
        return true;
    } else { 
        // webkit - safari/chrome
        alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');

    }
});

AngularJS accessing DOM elements inside directive template

This answer comes a little bit late, but I just was in a similar need.

Observing the comments written by @ganaraj in the question, One use case I was in the need of is, passing a classname via a directive attribute to be added to a ng-repeat li tag in the template.

For example, use the directive like this:

<my-directive class2add="special-class" />

And get the following html:

<div>
    <ul>
       <li class="special-class">Item 1</li>
       <li class="special-class">Item 2</li>
    </ul>
</div>

The solution found here applied with templateUrl, would be:

app.directive("myDirective", function() {
    return {
        template: function(element, attrs){
            return '<div><ul><li ng-repeat="item in items" class="'+attrs.class2add+'"></ul></div>';
        },
        link: function(scope, element, attrs) {
            var list = element.find("ul");
        }
    }
});

Just tried it successfully with AngularJS 1.4.9.

Hope it helps.

How to use mod operator in bash?

You must put your mathematical expressions inside $(( )).

One-liner:

for i in {1..600}; do wget http://example.com/search/link$(($i % 5)); done;

Multiple lines:

for i in {1..600}; do
    wget http://example.com/search/link$(($i % 5))
done

Make a UIButton programmatically in Swift

In iOS 12, Swift 4.2 & XCode 10.1

//For system type button
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 250, width: 100, height: 50)
//        button.backgroundColor = .blue
button.setTitle("Button", for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13.0)
button.titleLabel?.textAlignment = .center//Text alighment center
button.titleLabel?.numberOfLines = 0//To display multiple lines in UIButton
button.titleLabel?.lineBreakMode = .byWordWrapping//By word wrapping
button.tag = 1//To assign tag value
button.btnProperties()//Call UIButton properties from extension function
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

//For custom type button (add image to your button)
let button2 = UIButton(type: .custom)
button2.frame = CGRect(x: 100, y: 400, width: 100, height: 50)
//        button2.backgroundColor = .blue
button2.setImage(UIImage.init(named: "img.png"), for: .normal)
button2.tag = 2
button2.btnProperties()//Call UIButton properties from extension function
button2.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button2)

@objc func buttonClicked(sender:UIButton) {
    print("Button \(sender.tag) clicked")
}

//You can add UIButton properties like this also
extension UIButton {
    func btnProperties() {
        layer.cornerRadius = 10//Set button corner radious
        clipsToBounds = true
        backgroundColor = .blue//Set background colour
        //titleLabel?.textAlignment = .center//add properties like this
    }
}

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

One possibility is, if you are familiar with PDF format:

  1. Create some simply PDF with one page (Page should be contained within one object)
  2. Copy object multiply times
  3. Add references to the copied objects to the page catalog
  4. Fix xref table

You get an valid document of any size, entire file will be processed by a reader.

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

In my case the answer is pretty simple. Please check carefully the hardcoded url port: it is 8080. For some reason the value has changed to: for example 3030.

Just refresh the port in your ajax url string to the appropriate one.

conn = new WebSocket('ws://localhost:3030'); //should solve the issue

Windows batch script launch program and exit console

The simplest way ist just to start it with start

start notepad.exe

Here you can find more information about start

Sequence contains no matching element

For those of you who faced this issue while creating a controller through the context menu, reopening Visual Studio as an administrator fixed it.

Disable scrolling in all mobile devices

I suspect most everyone really wants to disable zoom/scroll in order to put together a more app-like experience; because the answers seem to contain elements of solutions for both zooming and scrolling, but nobody's really nailed either one down.

Scrolling

To answer OP, the only thing you seem to need to do to disable scrolling is intercept the window's scroll and touchmove events and call preventDefault and stopPropagation on the events they generate; like so

window.addEventListener("scroll", preventMotion, false);
window.addEventListener("touchmove", preventMotion, false);

function preventMotion(event)
{
    window.scrollTo(0, 0);
    event.preventDefault();
    event.stopPropagation();
}

And in your stylesheet, make sure your body and html tags include the following:

html:
{
    overflow: hidden;
}

body
{
    overflow: hidden;
    position: relative;
    margin: 0;
    padding: 0;
}

Zooming

However, scrolling is one thing, but you probably want to disable zoom as well. Which you do with the meta tag in your markup:

<meta name="viewport" content="user-scalable=no" />

All of these put together give you an app-like experience, probably a best fit for canvas.

(Be wary of the advice of some to add attributes like initial-scale and width to the meta tag if you're using a canvas, because canvasses scale their contents, unlike block elements, and you'll wind up with an ugly canvas, more often than not).

Syntax for a single-line Bash infinite while loop

Colon is always "true":

while :; do foo; sleep 2; done

Where is Developer Command Prompt for VS2013?

For some reason, it doesn't properly add an icon when running Windows 8+. Here's how I solved it:

Using Windows Explorer, navigate to:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2013

In that folder, you'll see a shortcut named Visual Studio Tools that maps to (assuming default installation):

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts

Double-click the shortcut (or go to the folder above).

From that folder, copy the shortcut named Developer Command Prompt for VS2013 (and any others you find useful) to the first directory (for the Start Menu). You'll likely be prompted for administrative access (do so).

Once you've done that, you'll now have an icon available for the 2013 command prompt.

Check if record exists from controller in Rails

I would do it this way if you needed an instance variable of the object to work with:

if @business = Business.where(:user_id => current_user.id).first
  #Do stuff
else
  #Do stuff
end

Functional programming vs Object Oriented programming

Object Oriented Programming offers:

  1. Encapsulation, to
    • control mutation of internal state
    • limit coupling to internal representation
  2. Subtyping, allowing:
    • substitution of compatible types (polymorphism)
    • a crude means of sharing implementation between classes (implementation inheritance)

Functional Programming, in Haskell or even in Scala, can allow substitution through more general mechanism of type classes. Mutable internal state is either discouraged or forbidden. Encapsulation of internal representation can also be achieved. See Haskell vs OOP for a good comparison.

Norman's assertion that "Adding a new kind of thing to a functional program may require editing many function definitions to add a new case." depends on how well the functional code has employed type classes. If Pattern Matching on a particular Abstract Data Type is spread throughout a codebase, you will indeed suffer from this problem, but it is perhaps a poor design to start with.

EDITED Removed reference to implicit conversions when discussing type classes. In Scala, type classes are encoded with implicit parameters, not conversions, although implicit conversions are another means to acheiving substitution of compatible types.

How to pass in parameters when use resource service?

I think I see your problem, you need to use the @ syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?

This is what I can suggest based on what I see so far:

.factory('MagComments', function ($resource) {
    return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
      loginID : organEntity,
      password : organCommpassword,
      id : '@magId'
    });
  })

The @magId string will tell the resource to replace :id with the property magId on the object you pass it as parameters.

I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.

Javascript checkbox onChange

Javascript

  // on toggle method
  // to check status of checkbox
  function onToggle() {
    // check if checkbox is checked
    if (document.querySelector('#my-checkbox').checked) {
      // if checked
      console.log('checked');
    } else {
      // if unchecked
      console.log('unchecked');
    }
  }

HTML

<input id="my-checkbox" type="checkbox" onclick="onToggle()">

How to generate entire DDL of an Oracle schema (scriptable)?

The output of this query is very clean (original here)

clear screen
accept uname prompt 'Enter User Name : '
accept outfile prompt  ' Output filename : '

spool &&outfile..gen

SET LONG 20000 LONGCHUNKSIZE 20000 PAGESIZE 0 LINESIZE 1000 FEEDBACK OFF VERIFY OFF TRIMSPOOL ON

BEGIN
   DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'SQLTERMINATOR', true);
   DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'PRETTY', true);
END;
/

SELECT dbms_metadata.get_ddl('USER','&&uname') FROM dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT','&&uname') from dual;

spool off

How to playback MKV video in web browser?

HTML5 and the VLC web plugin were a no go for me but I was able to get this work using the following setup:

DivX Web Player (NPAPI browsers only)

AC3 Audio Decoder

And here is the HTML:

<embed id="divxplayer" type="video/divx" width="1024" height="768" 
src ="path_to_file" autoPlay=\"true\" 
pluginspage=\"http://go.divx.com/plugin/download/\"></embed>

The DivX player seems to allow for a much wider array of video and audio options than the native HTML5, so far I am very impressed by it.

How many bytes is unsigned long long?

Executive summary: it's 64 bits, or larger.

unsigned long long is the same as unsigned long long int. Its size is platform-dependent, but guaranteed by the C standard (ISO C99) to be at least 64 bits. There was no long long in C89, but apparently even MSVC supports it, so it's quite portable.

In the current C++ standard (issued in 2003), there is no long long, though many compilers support it as an extension. The upcoming C++0x standard will support it and its size will be the same as in C, so at least 64 bits.

You can get the exact size, in bytes (8 bits on typical platforms) with the expression sizeof(unsigned long long). If you want exactly 64 bits, use uint64_t, which is defined in the header <stdint.h> along with a bunch of related types (available in C99, C++11 and some current C++ compilers).

How to detect a docker daemon port

Try add -H tcp://0.0.0.0:2375(at end of Execstart line) instead of -H 0.0.0.0:2375.

How can I get phone serial number (IMEI)

Use below code for IMEI:

TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String imei= tm.getDeviceId();

Arduino IDE can't find ESP8266WiFi.h file

When programming the NODEMCU card with the Arduino IDE, you need to customize it and you must have selected the correct card.

Open Arduino IDE and go to files and click on the preference in the Arduino IDE.

Add the following link to the Additional Manager URLS section: "http://arduino.esp8266.com/stable/package_esp8266com_index.json" and press the OK button.

Then click Tools> Board Manager. Type "ESP8266" in the text box to search and install the ESP8266 software for Arduino IDE.

You will be successful when you try to program again by selecting the NodeMCU card after these operations. I hope I could help.

Data access object (DAO) in Java

I just want to explain it in my own way with a small story that I experienced in one of my projects. First I want to explain Why DAO is important? rather than go to What is DAO? for better understanding.

Why DAO is important?
In my one project of my project, I used Client.class which contains all the basic information of our system users. Where I need client then every time I need to do an ugly query where it is needed. Then I felt that decreases the readability and made a lot of redundant boilerplate code.

Then one of my senior developers introduced a QueryUtils.class where all queries are added using public static access modifier and then I don't need to do query everywhere. Suppose when I needed activated clients then I just call -

QueryUtils.findAllActivatedClients();

In this way, I made some optimizations of my code.

But there was another problem !!!

I felt that the QueryUtils.class was growing very highly. 100+ methods were included in that class which was also very cumbersome to read and use. Because this class contains other queries of another domain models ( For example- products, categories locations, etc ).

Then the superhero Mr. CTO introduced a new solution named DAO which solved the problem finally. I felt DAO is very domain-specific. For example, he created a DAO called ClientDAO.class where all Client.class related queries are found which seems very easy for me to use and maintain. The giant QueryUtils.class was broken down into many other domain-specific DAO for example - ProductsDAO.class, CategoriesDAO.class, etc which made the code more Readable, more Maintainable, more Decoupled.

What is DAO?

It is an object or interface, which made an easy way to access data from the database without writing complex and ugly queries every time in a reusable way.

How to check whether a string contains a substring in Ruby

Expanding on Clint Pachl's answer:

Regex matching in Ruby returns nil when the expression doesn't match. When it does, it returns the index of the character where the match happens. For example:

"foobar" =~ /bar/  # returns 3
"foobar" =~ /foo/  # returns 0
"foobar" =~ /zzz/  # returns nil

It's important to note that in Ruby only nil and the boolean expression false evaluate to false. Everything else, including an empty Array, empty Hash, or the Integer 0, evaluates to true.

That's why the /foo/ example above works, and why.

if "string" =~ /regex/

works as expected, only entering the 'true' part of the if block if a match occurred.

Importing Excel spreadsheet data into another Excel spreadsheet containing VBA

This should get you started: Using VBA in your own Excel workbook, have it prompt the user for the filename of their data file, then just copy that fixed range into your target workbook (that could be either the same workbook as your macro enabled one, or a third workbook). Here's a quick vba example of how that works:

' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook

' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook

' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)

Set customerWorkbook = Application.Workbooks.Open(customerFilename)

' assume range is A1 - C10 in sheet1
' copy data from customer to target workbook
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets(1)
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.Worksheets(1)

targetSheet.Range("A1", "C10").Value = sourceSheet.Range("A1", "C10").Value

' Close customer workbook
customerWorkbook.Close

How to get a reversed list view on a list in Java?

java.util.Deque has descendingIterator() - if your List is a Deque, you can use that.

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

The biggest clue is the rows are all being returned on one line. This indicates line terminators are being ignored or are not present.

You can specify the line terminator for csv_reader. If you are on a mac the lines created will end with \rrather than the linux standard \n or better still the suspenders and belt approach of windows with \r\n.

pandas.read_csv(filename, sep='\t', lineterminator='\r')

You could also open all your data using the codecs package. This may increase robustness at the expense of document loading speed.

import codecs

doc = codecs.open('document','rU','UTF-16') #open for reading with "universal" type set

df = pandas.read_csv(doc, sep='\t')

What is the standard Python docstring format?

PEP-8 is the official python coding standard. It contains a section on docstrings, which refers to PEP-257 -- a complete specification for docstrings.

How to use the unsigned Integer in Java 8 and Java 9?

Per the documentation you posted, and this blog post - there's no difference when declaring the primitive between an unsigned int/long and a signed one. The "new support" is the addition of the static methods in the Integer and Long classes, e.g. Integer.divideUnsigned. If you're not using those methods, your "unsigned" long above 2^63-1 is just a plain old long with a negative value.

From a quick skim, it doesn't look like there's a way to declare integer constants in the range outside of +/- 2^31-1, or +/- 2^63-1 for longs. You would have to manually compute the negative value corresponding to your out-of-range positive value.

How to print without newline or space?

python 2.6+:

from __future__ import print_function # needs to be first statement in file
print('.', end='')

python 3:

print('.', end='')

python <= 2.5:

import sys
sys.stdout.write('.')

if extra space is OK after each print, in python 2

print '.',

misleading in python 2 - avoid:

print('.'), # avoid this if you want to remain sane
# this makes it look like print is a function but it is not
# this is the `,` creating a tuple and the parentheses enclose an expression
# to see the problem, try:
print('.', 'x'), # this will print `('.', 'x') `

Sort array of objects by string property value

It's easy enough to write your own comparison function:

function compare( a, b ) {
  if ( a.last_nom < b.last_nom ){
    return -1;
  }
  if ( a.last_nom > b.last_nom ){
    return 1;
  }
  return 0;
}

objs.sort( compare );

Or inline (c/o Marco Demaio):

objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0))

In Angular, What is 'pathmatch: full' and what effect does it have?

RouterModule.forRoot([
      { path: 'welcome', component: WelcomeComponent },
      { path: '', redirectTo: 'welcome', pathMatch: 'full' },
      { path: '**', component: 'pageNotFoundComponent' }
    ])

Case 1 pathMatch:'full': In this case, when app is launched on localhost:4200 (or some server) the default page will be welcome screen, since the url will be https://localhost:4200/

If https://localhost:4200/gibberish this will redirect to pageNotFound screen because of path:'**' wildcard

Case 2 pathMatch:'prefix':

If the routes have { path: '', redirectTo: 'welcome', pathMatch: 'prefix' }, now this will never reach the wildcard route since every url would match path:'' defined.

How to compile Tensorflow with SSE4.2 and AVX instructions?

I compiled a small Bash script for Mac (easily can be ported to Linux) to retrieve all CPU features and apply some of them to build TF. Im on TF master and use kinda often (couple times in a month).

https://gist.github.com/venik/9ba962c8b301b0e21f99884cbd35082f

Angular 2 - innerHTML styling

If you are using sass as style preprocessor, you can switch back to native Sass compiler for dev dependency by:

npm install node-sass --save-dev

So that you can keep using /deep/ for development.

SQL Server SELECT into existing table

SELECT ... INTO ... only works if the table specified in the INTO clause does not exist - otherwise, you have to use:

INSERT INTO dbo.TABLETWO
SELECT col1, col2
  FROM dbo.TABLEONE
 WHERE col3 LIKE @search_key

This assumes there's only two columns in dbo.TABLETWO - you need to specify the columns otherwise:

INSERT INTO dbo.TABLETWO
  (col1, col2)
SELECT col1, col2
  FROM dbo.TABLEONE
 WHERE col3 LIKE @search_key

Django 1.7 - makemigrations not detecting changes

I recently upgraded Django from 1.6 to 1.8 and had few apps and migrations for them. I used south and schemamigrations for creating migrations in Django 1.6, which is dropped in Django 1.8.

When I added new models after upgrade, the makemigrations command wasn't detecting any changes. And then I tried the solution suggested by @drojf (1st answer), it worked fine, but failed to apply fake initial migration (python manage.py --fake-initial). I was doing this as my tables (old tables) were already created.

Finally this worked for me, removed new models (or model changes) from models.py and then had to delete (or rename for safety backup) migrations folder of all apps and run python manage.py makemigrations for all apps, then did python manage.py migrate --fake-initial. This worked like a charm. Once initial migration is created for all apps and fake initial migrated, then added new models and followed regular process of makemigrations and migrate on that app. The changes were detected now and everything went fine.

I just thought of sharing it here, if someone faces same problem (having schemamigrations of south for their apps), it might help them :)

Running Python code in Vim

The accepted answer works for me (on Linux), but I wanted this command to also save the buffer before running, so I modified it slightly:

nnoremap <buffer> <F9> :w <bar> :exec '!python' shellescape(@%, 1)<cr>

The :w <bar> saves the buffer THEN runs the code in it.

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

How do you completely remove Ionic and Cordova installation from mac?

command to remove cordova and ionic

sudo npm uninstall -g ionic

Why am I getting AttributeError: Object has no attribute

These kind of bugs are common when Python multi-threading. What happens is that, on interpreter tear-down, the relevant module (myThread in this case) goes through a sort-of del myThread.

The call self.sample() is roughly equivalent to myThread.__dict__["sample"](self). But if we're during the interpreter's tear-down sequence, then its own dictionary of known types might've already had myThread deleted, and now it's basically a NoneType - and has no 'sample' attribute.

How to parse an RSS feed using JavaScript?

If you are looking for a simple and free alternative to Google Feed API for your rss widget then rss2json.com could be a suitable solution for that.

You may try to see how it works on a sample code from the api documentation below:

_x000D_
_x000D_
google.load("feeds", "1");_x000D_
_x000D_
    function initialize() {_x000D_
      var feed = new google.feeds.Feed("https://news.ycombinator.com/rss");_x000D_
      feed.load(function(result) {_x000D_
        if (!result.error) {_x000D_
          var container = document.getElementById("feed");_x000D_
          for (var i = 0; i < result.feed.entries.length; i++) {_x000D_
            var entry = result.feed.entries[i];_x000D_
            var div = document.createElement("div");_x000D_
            div.appendChild(document.createTextNode(entry.title));_x000D_
            container.appendChild(div);_x000D_
          }_x000D_
        }_x000D_
      });_x000D_
    }_x000D_
    google.setOnLoadCallback(initialize);
_x000D_
<html>_x000D_
  <head>    _x000D_
     <script src="https://rss2json.com/gfapi.js"></script>_x000D_
  </head>_x000D_
  <body>_x000D_
    <p><b>Result from the API:</b></p>_x000D_
    <div id="feed"></div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Allow docker container to connect to a local/host postgres database

Simple Solution for mac:

The newest version of docker (18.03) offers a built in port forwarding solution. Inside your docker container simply have the db host set to host.docker.internal. This will be forwarded to the host the docker container is running on.

Documentation for this is here: https://docs.docker.com/docker-for-mac/networking/#i-want-to-connect-from-a-container-to-a-service-on-the-host

What does @@variable mean in Ruby?

@ and @@ in modules also work differently when a class extends or includes that module.

So given

module A
    @a = 'module'
    @@a = 'module'

    def get1
        @a          
    end     

    def get2
        @@a         
    end     

    def set1(a) 
        @a = a      
    end     

    def set2(a) 
        @@a = a     
    end     

    def self.set1(a)
        @a = a      
    end     

    def self.set2(a)
        @@a = a     
    end     
end 

Then you get the outputs below shown as comments

class X
    extend A

    puts get1.inspect # nil
    puts get2.inspect # "module"

    @a = 'class' 
    @@a = 'class' 

    puts get1.inspect # "class"
    puts get2.inspect # "module"

    set1('set')
    set2('set')

    puts get1.inspect # "set" 
    puts get2.inspect # "set" 

    A.set1('sset')
    A.set2('sset')

    puts get1.inspect # "set" 
    puts get2.inspect # "sset"
end 

class Y
    include A

    def doit
        puts get1.inspect # nil
        puts get2.inspect # "module"

        @a = 'class'
        @@a = 'class'

        puts get1.inspect # "class"
        puts get2.inspect # "class"

        set1('set')
        set2('set')

        puts get1.inspect # "set"
        puts get2.inspect # "set"

        A.set1('sset')
        A.set2('sset')

        puts get1.inspect # "set"
        puts get2.inspect # "sset"
    end
end

Y.new.doit

So use @@ in modules for variables you want common to all their uses, and use @ in modules for variables you want separate for every use context.

How does Content Security Policy (CSP) work?

The Content-Security-Policy meta-tag allows you to reduce the risk of XSS attacks by allowing you to define where resources can be loaded from, preventing browsers from loading data from any other locations. This makes it harder for an attacker to inject malicious code into your site.

I banged my head against a brick wall trying to figure out why I was getting CSP errors one after another, and there didn't seem to be any concise, clear instructions on just how does it work. So here's my attempt at explaining some points of CSP briefly, mostly concentrating on the things I found hard to solve.

For brevity I won’t write the full tag in each sample. Instead I'll only show the content property, so a sample that says content="default-src 'self'" means this:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'">

1. How can I allow multiple sources?

You can simply list your sources after a directive as a space-separated list:

content="default-src 'self' https://example.com/js/"

Note that there are no quotes around parameters other than the special ones, like 'self'. Also, there's no colon (:) after the directive. Just the directive, then a space-separated list of parameters.

Everything below the specified parameters is implicitly allowed. That means that in the example above these would be valid sources:

https://example.com/js/file.js
https://example.com/js/subdir/anotherfile.js

These, however, would not be valid:

http://example.com/js/file.js
^^^^ wrong protocol

https://example.com/file.js
                   ^^ above the specified path

2. How can I use different directives? What do they each do?

The most common directives are:

  • default-src the default policy for loading javascript, images, CSS, fonts, AJAX requests, etc
  • script-src defines valid sources for javascript files
  • style-src defines valid sources for css files
  • img-src defines valid sources for images
  • connect-src defines valid targets for to XMLHttpRequest (AJAX), WebSockets or EventSource. If a connection attempt is made to a host that's not allowed here, the browser will emulate a 400 error

There are others, but these are the ones you're most likely to need.

3. How can I use multiple directives?

You define all your directives inside one meta-tag by terminating them with a semicolon (;):

content="default-src 'self' https://example.com/js/; style-src 'self'"

4. How can I handle ports?

Everything but the default ports needs to be allowed explicitly by adding the port number or an asterisk after the allowed domain:

content="default-src 'self' https://ajax.googleapis.com http://example.com:123/free/stuff/"

The above would result in:

https://ajax.googleapis.com:123
                           ^^^^ Not ok, wrong port

https://ajax.googleapis.com - OK

http://example.com/free/stuff/file.js
                 ^^ Not ok, only the port 123 is allowed

http://example.com:123/free/stuff/file.js - OK

As I mentioned, you can also use an asterisk to explicitly allow all ports:

content="default-src example.com:*"

5. How can I handle different protocols?

By default, only standard protocols are allowed. For example to allow WebSockets ws:// you will have to allow it explicitly:

content="default-src 'self'; connect-src ws:; style-src 'self'"
                                         ^^^ web Sockets are now allowed on all domains and ports.

6. How can I allow the file protocol file://?

If you'll try to define it as such it won’t work. Instead, you'll allow it with the filesystem parameter:

content="default-src filesystem"

7. How can I use inline scripts and style definitions?

Unless explicitly allowed, you can't use inline style definitions, code inside <script> tags or in tag properties like onclick. You allow them like so:

content="script-src 'unsafe-inline'; style-src 'unsafe-inline'"

You'll also have to explicitly allow inline, base64 encoded images:

content="img-src data:"

8. How can I allow eval()?

I'm sure many people would say that you don't, since 'eval is evil' and the most likely cause for the impending end of the world. Those people would be wrong. Sure, you can definitely punch major holes into your site's security with eval, but it has perfectly valid use cases. You just have to be smart about using it. You allow it like so:

content="script-src 'unsafe-eval'"

9. What exactly does 'self' mean?

You might take 'self' to mean localhost, local filesystem, or anything on the same host. It doesn't mean any of those. It means sources that have the same scheme (protocol), same host, and same port as the file the content policy is defined in. Serving your site over HTTP? No https for you then, unless you define it explicitly.

I've used 'self' in most examples as it usually makes sense to include it, but it's by no means mandatory. Leave it out if you don't need it.

But hang on a minute! Can't I just use content="default-src *" and be done with it?

No. In addition to the obvious security vulnerabilities, this also won’t work as you'd expect. Even though some docs claim it allows anything, that's not true. It doesn't allow inlining or evals, so to really, really make your site extra vulnerable, you would use this:

content="default-src * 'unsafe-inline' 'unsafe-eval'"

... but I trust you won’t.

Further reading:

http://content-security-policy.com

http://en.wikipedia.org/wiki/Content_Security_Policy

Broken references in Virtualenvs

If you using pipenv, just doing pipenv --rm solves the problem.

how to add jquery in laravel project

you can use online library

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

or else download library and add css in css folder and jquery in js folder.both folder you keep in laravel public folder then you can link like below

<link rel="stylesheet" href="{{asset('css/bootstrap-theme.min.css')}}">
<script src="{{asset('js/jquery.min.js')}}"></script>

or else

{{ HTML::style('css/style.css') }}
{{ HTML::script('js/functions.js') }}

Difference between del, remove, and pop on lists

You can also use remove to remove a value by index as well.

n = [1, 3, 5]

n.remove(n[1])

n would then refer to [1, 5]

Does Java read integers in little endian or big endian?

There are no unsigned integers in Java. All integers are signed and in big endian.

On the C side the each byte has tne LSB at the start is on the left and the MSB at the end.

It sounds like you are using LSB as Least significant bit, are you? LSB usually stands for least significant byte. Endianness is not bit based but byte based.

To convert from unsigned byte to a Java integer:

int i = (int) b & 0xFF;

To convert from unsigned 32-bit little-endian in byte[] to Java long (from the top of my head, not tested):

long l = (long)b[0] & 0xFF;
l += ((long)b[1] & 0xFF) << 8;
l += ((long)b[2] & 0xFF) << 16;
l += ((long)b[3] & 0xFF) << 24;

Check if a string contains a number

alp_num = [x for x in string.split() if x.isalnum() and re.search(r'\d',x) and 
re.search(r'[a-z]',x)]

print(alp_num)

This returns all the string that has both alphabets and numbers in it. isalpha() returns the string with all digits or all characters.

rejected master -> master (non-fast-forward)

! [rejected] master -> master (non-fast-forward)

Don’t panic, this is extremely easy to fix. All you have to do is issue a pull and your branch will be fast-forward:

$ git pull myrepo master

Then retry your push and everything should be fine:

$ git push github master

One liner to check if element is in the list

In JDK7:

if ({"a", "b", "c"}.contains("a")) {

Assuming the Project Coin collections literals project goes through.

Edit: It didn't.

How do I enumerate through a JObject?

For people like me, linq addicts, and based on svick's answer, here a linq approach:

using System.Linq;
//...
//make it linq iterable. 
var obj_linq = Response.Cast<KeyValuePair<string, JToken>>();

Now you can make linq expressions like:

JToken x = obj_linq
          .Where( d => d.Key == "my_key")
          .Select(v => v)
          .FirstOrDefault()
          .Value;
string y = ((JValue)x).Value;

Or just:

var y = obj_linq
       .Where(d => d.Key == "my_key")
       .Select(v => ((JValue)v.Value).Value)
       .FirstOrDefault();

Or this one to iterate over all data:

obj_linq.ToList().ForEach( x => { do stuff } ); 

how to implement a long click listener on a listview

In xml add

<ListView android:longClickable="true">

In java file

lv.setLongClickable(true) 

try this setOnItemLongClickListener()

lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int pos, long l) {
                //final String category = "Position at : "+pos;
                final String category = ((TextView) view.findViewById(R.id.textView)).getText().toString();
                Toast.makeText(getActivity(),""+category,Toast.LENGTH_LONG).show();
                args = new Bundle();
                args.putString("category", category);
                return false;
            }
        });

Execute a large SQL script (with GO commands)

If you don't want to go the SMO route you can search and replace "GO" for ";" and the query as you would. Note that soly the the last result set will be returned.

How does the Java 'for each' loop work?

The for-each loop in Java uses the underlying iterator mechanism. So it's identical to the following:

Iterator<String> iterator = someList.iterator();

while (iterator.hasNext()) {
  String item = iterator.next();
  System.out.println(item);
}

How to solve static declaration follows non-static declaration in GCC C code?

You have declared a function as nonstatic in some file and you have implemented as static in another file or somewhere in the same file can cause this problem also. For example, the following code will produce this error.

void inlet_update_my_ratio(object_t *myobject);
//some where the implementation is like this
static void inlet_update_my_ratio(object_t *myobject) {
//code
}

If you remove the static from the implementation, the error will go away as below.

 void inlet_update_my_ratio(object_t *myobject) {
    //code
    }

VARCHAR to DECIMAL

In case you need to ROUND the result, not truncate, can use this:

select convert(decimal(38,4), round(convert(decimal(38,10), '123456789.1234567'),4))

This will return the following:

'123456789.1235' for '123456789.1234567'
'123456789.1234' for '123456789.1234467'

Sticky and NON-Sticky sessions

I've made an answer with some more details here : https://stackoverflow.com/a/11045462/592477

Or you can read it there ==>

When you use loadbalancing it means you have several instances of tomcat and you need to divide loads.

  • If you're using session replication without sticky session : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send some of these requests to the first tomcat instance, and send some other of these requests to the secondth instance, and other to the third.
  • If you're using sticky session without replication : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send the first user request to one of the three tomcat instances, and all the other requests that are sent by this user during his session will be sent to the same tomcat instance. During these requests, if you shutdown or restart this tomcat instance (tomcat instance which is used) the loadbalancer sends the remaining requests to one other tomcat instance that is still running, BUT as you don't use session replication, the instance tomcat which receives the remaining requests doesn't have a copy of the user session then for this tomcat the user begin a session : the user loose his session and is disconnected from the web app although the web app is still running.
  • If you're using sticky session WITH session replication : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send the first user request to one of the three tomcat instances, and all the other requests that are sent by this user during his session will be sent to the same tomcat instance. During these requests, if you shutdown or restart this tomcat instance (tomcat instance which is used) the loadbalancer sends the remaining requests to one other tomcat instance that is still running, as you use session replication, the instance tomcat which receives the remaining requests has a copy of the user session then the user keeps on his session : the user continue to browse your web app without being disconnected, the shutdown of the tomcat instance doesn't impact the user navigation.

Refused to execute script, strict MIME type checking is enabled?

I hade same problem then i fixed like this

change "text/javascript"

to

type="application/json"

" app-release.apk" how to change this default generated apk name

First rename your module from app to i.e. SurveyApp

Second add this to your project top-level (root project) gradle. It's working with Gradle 3.0

//rename apk for all sub projects
subprojects {
    afterEvaluate { project ->
        if (project.hasProperty("android")) {
            android.applicationVariants.all { variant ->
                variant.outputs.all {
                    outputFileName = "${project.name}-${variant.name}-${variant.versionName}.apk"
                }
            }
        }
    }
}

Which @NotNull Java annotation should I use?

Just pointing out that the Java Validation API (javax.validation.constraints.*) doesn't come with a @Nullable annotation, which is very valuable in a static analysis context. It makes sense for runtime bean validation as this is the default for any non-primitive field in Java (i.e. nothing to validate/enforce). For the purposes stated that should weigh towards the alternatives.

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

Drop the user, flush the privileges; then, create the user. It does work!

How can I scale the content of an iframe?

You don't need to wrap the iframe with an additional tag. Just make sure you increase the width and height of the iframe by the same amount you scale down the iframe.

e.g. to scale the iframe content to 80% :

#frame { /* Example size! */
    height: 400px; /* original height */
    width: 100%; /* original width */
}
#frame {
    height: 500px; /* new height (400 * (1/0.8) ) */
    width: 125%; /* new width (100 * (1/0.8) )*/

    transform: scale(0.8); 
    transform-origin: 0 0;
}

Basically, to get the same size iframe you need to scale the dimensions.

Git Ignores and Maven targets

add following lines in gitignore, from all undesirable files

/target/
*/target/**
**/META-INF/
!.mvn/wrapper/maven-wrapper.jar

### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache

### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr

### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

 $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );

WebSockets vs. Server-Sent events/EventSource

Websockets and SSE (Server Sent Events) are both capable of pushing data to browsers, however they are not competing technologies.

Websockets connections can both send data to the browser and receive data from the browser. A good example of an application that could use websockets is a chat application.

SSE connections can only push data to the browser. Online stock quotes, or twitters updating timeline or feed are good examples of an application that could benefit from SSE.

In practice since everything that can be done with SSE can also be done with Websockets, Websockets is getting a lot more attention and love, and many more browsers support Websockets than SSE.

However, it can be overkill for some types of application, and the backend could be easier to implement with a protocol such as SSE.

Furthermore SSE can be polyfilled into older browsers that do not support it natively using just JavaScript. Some implementations of SSE polyfills can be found on the Modernizr github page.

Gotchas:

  • SSE suffers from a limitation to the maximum number of open connections, which can be specially painful when opening various tabs as the limit is per browser and set to a very low number (6). The issue has been marked as "Won't fix" in Chrome and Firefox. This limit is per browser + domain, so that means that you can open 6 SSE connections across all of the tabs to www.example1.com and another 6 SSE connections to www.example2.com (thanks Phate).
  • Only WS can transmit both binary data and UTF-8, SSE is limited to UTF-8. (Thanks to Chado Nihi).
  • Some enterprise firewalls with packet inspection have trouble dealing with WebSockets (Sophos XG Firewall, WatchGuard, McAfee Web Gateway).

HTML5Rocks has some good information on SSE. From that page:

Server-Sent Events vs. WebSockets

Why would you choose Server-Sent Events over WebSockets? Good question.

One reason SSEs have been kept in the shadow is because later APIs like WebSockets provide a richer protocol to perform bi-directional, full-duplex communication. Having a two-way channel is more attractive for things like games, messaging apps, and for cases where you need near real-time updates in both directions. However, in some scenarios data doesn't need to be sent from the client. You simply need updates from some server action. A few examples would be friends' status updates, stock tickers, news feeds, or other automated data push mechanisms (e.g. updating a client-side Web SQL Database or IndexedDB object store). If you'll need to send data to a server, XMLHttpRequest is always a friend.

SSEs are sent over traditional HTTP. That means they do not require a special protocol or server implementation to get working. WebSockets on the other hand, require full-duplex connections and new Web Socket servers to handle the protocol. In addition, Server-Sent Events have a variety of features that WebSockets lack by design such as automatic reconnection, event IDs, and the ability to send arbitrary events.


TLDR summary:

Advantages of SSE over Websockets:

  • Transported over simple HTTP instead of a custom protocol
  • Can be poly-filled with javascript to "backport" SSE to browsers that do not support it yet.
  • Built in support for re-connection and event-id
  • Simpler protocol
  • No trouble with corporate firewalls doing packet inspection

Advantages of Websockets over SSE:

  • Real time, two directional communication.
  • Native support in more browsers

Ideal use cases of SSE:

  • Stock ticker streaming
  • twitter feed updating
  • Notifications to browser

SSE gotchas:

  • No binary support
  • Maximum open connections limit

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

Laravel's Autoload is a bit different:

1) It will in fact use Composer for some stuff

2) It will call Composer with the optimize flag

3) It will 'recompile' loads of files creating the huge bootstrap/compiled.php

4) And also will find all of your Workbench packages and composer dump-autoload them, one by one.

How do I spool to a CSV formatted file using SQLPLUS?

If you are using 12.2, you can simply say

set markup csv on
spool myfile.csv

How to write asynchronous functions for Node.js

You seem to be confusing asynchronous IO with asynchronous functions. node.js uses asynchronous non-blocking IO because non blocking IO is better. The best way to understand it is to go watch some videos by ryan dahl.

How do I write asynchronous functions for Node?

Just write normal functions, the only difference is that they are not executed immediately but passed around as callbacks.

How should I implement error event handling correctly

Generally API's give you a callback with an err as the first argument. For example

database.query('something', function(err, result) {
  if (err) handle(err);
  doSomething(result);
});

Is a common pattern.

Another common pattern is on('error'). For example

process.on('uncaughtException', function (err) {
  console.log('Caught exception: ' + err);
});

Edit:

var async_function = function(val, callback){
    process.nextTick(function(){
        callback(val);
    });
};

The above function when called as

async_function(42, function(val) {
  console.log(val)
});
console.log(43);

Will print 42 to the console asynchronously. In particular process.nextTick fires after the current eventloop callstack is empty. That call stack is empty after async_function and console.log(43) have run. So we print 43 followed by 42.

You should probably do some reading on the event loop.

How to store an output of shell script to a variable in Unix?

Suppose you want to store the result of an echo command

echo hello   
x=$(echo hello)  
echo "$x",world!  

output:

hello  
hello,world!

How to check if a query string value is present via JavaScript?

This should help:

function getQueryParams(){
    try{
        url = window.location.href;
        query_str = url.substr(url.indexOf('?')+1, url.length-1);
        r_params = query_str.split('&');
        params = {}
        for( i in r_params){
            param = r_params[i].split('=');
            params[ param[0] ] = param[1];
        }
        return params;
    }
    catch(e){
       return {};
    }
}

How to set the title text color of UIButton?

func setTitleColor(_ color: UIColor?, 
               for state: UIControl.State)

Parameters:

color:
The color of the title to use for the specified state.

state:
The state that uses the specified color. The possible values are described in UIControl.State.

Sample:

let MyButton = UIButton()
MyButton.setTitle("Click Me..!", for: .normal)
MyButton.setTitleColor(.green, for: .normal)

How to convert latitude or longitude to meters?

One nautical mile (1852 meters) is defined as one arcminute of longitude at the equator. However, you need to define a map projection (see also UTM) in which you are working for the conversion to really make sense.

Testing if a checkbox is checked with jQuery

Use .is(':checked') to determine whether or not it's checked, and then set your value accordingly.

More information here.

Simple way to unzip a .zip file using zlib

zlib handles the deflate compression/decompression algorithm, but there is more than that in a ZIP file.

You can try libzip. It is free, portable and easy to use.

UPDATE: Here I attach quick'n'dirty example of libzip, with all the error controls ommited:

#include <zip.h>

int main()
{
    //Open the ZIP archive
    int err = 0;
    zip *z = zip_open("foo.zip", 0, &err);

    //Search for the file of given name
    const char *name = "file.txt";
    struct zip_stat st;
    zip_stat_init(&st);
    zip_stat(z, name, 0, &st);

    //Alloc memory for its uncompressed contents
    char *contents = new char[st.size];

    //Read the compressed file
    zip_file *f = zip_fopen(z, name, 0);
    zip_fread(f, contents, st.size);
    zip_fclose(f);

    //And close the archive
    zip_close(z);

    //Do something with the contents
    //delete allocated memory
    delete[] contents;
}

MySQL - Get row number on select

Take a look at this.

Change your query to:

SET @rank=0;
SELECT @rank:=@rank+1 AS rank, itemID, COUNT(*) as ordercount
  FROM orders
  GROUP BY itemID
  ORDER BY ordercount DESC;
SELECT @rank;

The last select is your count.

How to delete the contents of a folder?

As a oneliner:

import os

# Python 2.7
map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) )

# Python 3+
list( map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) ) )

A more robust solution accounting for files and directories as well would be (2.7):

def rm(f):
    if os.path.isdir(f): return os.rmdir(f)
    if os.path.isfile(f): return os.unlink(f)
    raise TypeError, 'must be either file or directory'

map( rm, (os.path.join( mydir,f) for f in os.listdir(mydir)) )

R: rJava package install failing

The rJava package looks for the /usr/lib/jvm/default-java/ folder. But it's not available as default. This folder have a symlink for the default java configured for the system.

To activate the default java install the following packages:

sudo apt-get install default-jre default-jre-headless

Tested on ubuntu 17.04 with CRAN R 3.4.1

python-pandas and databases like mysql

And this is how you connect to PostgreSQL using psycopg2 driver (install with "apt-get install python-psycopg2" if you're on Debian Linux derivative OS).

import pandas.io.sql as psql
import psycopg2

conn = psycopg2.connect("dbname='datawarehouse' user='user1' host='localhost' password='uberdba'")

q = """select month_idx, sum(payment) from bi_some_table"""

df3 = psql.frame_query(q, conn)

Ruby - test for array

Instead of testing for an Array, just convert whatever you get into a one-level Array, so your code only needs to handle the one case.

t = [*something]     # or...
t = Array(something) # or...
def f *x
    ...
end

Ruby has various ways to harmonize an API which can take an object or an Array of objects, so, taking a guess at why you want to know if something is an Array, I have a suggestion.

The splat operator contains lots of magic you can look up, or you can just call Array(something) which will add an Array wrapper if needed. It's similar to [*something] in this one case.

def f x
  p Array(x).inspect
  p [*x].inspect
end
f 1         # => "[1]"
f [1]       # => "[1]"
f [1,2]     # => "[1, 2]"

Or, you could use the splat in the parameter declaration and then .flatten, giving you a different sort of collector. (For that matter, you could call .flatten above, too.)

def f *x
  p x.flatten.inspect
end         # => nil
f 1         # => "[1]"
f 1,2       # => "[1, 2]"
f [1]       # => "[1]"
f [1,2]     # => "[1, 2]"
f [1,2],3,4 # => "[1, 2, 3, 4]"

And, thanks gregschlom, it's sometimes faster to just use Array(x) because when it's already an Array it doesn't need to create a new object.

How to count rows with SELECT COUNT(*) with SQLAlchemy?

I needed to do a count of a very complex query with many joins. I was using the joins as filters, so I only wanted to know the count of the actual objects. count() was insufficient, but I found the answer in the docs here:

http://docs.sqlalchemy.org/en/latest/orm/tutorial.html

The code would look something like this (to count user objects):

from sqlalchemy import func

session.query(func.count(User.id)).scalar() 

How do I terminate a thread in C++11?

Tips of using OS-dependent function to terminate C++ thread:

  1. std::thread::native_handle() only can get the thread’s valid native handle type before calling join() or detach(). After that, native_handle() returns 0 - pthread_cancel() will coredump.

  2. To effectively call native thread termination function(e.g. pthread_cancel()), you need to save the native handle before calling std::thread::join() or std::thread::detach(). So that your native terminator always has a valid native handle to use.

More explanations please refer to: http://bo-yang.github.io/2017/11/19/cpp-kill-detached-thread .

nginx error connect to php5-fpm.sock failed (13: Permission denied)

Please NOTICE (at least in centos 8) the user who you are assigning listen.owner and other stuff to it MUST be in the same POOL with the user for example given I am the foo user

[www] # WRONG | IN MY CASE I WAS UNDER www POOL SO IT WASNT WORKING FOR ME.
[foo] # CORRECT | THE POOL AND THE USER MATCHES.

listen.owner = foo
listen.group = foo
listen.mode = 0660
user = foo
group = foo

I dont know if there's a global pool but after hours of searching I finlly did it.

PHP read and write JSON from file

Or just use $json as an object:

$json->$user = array("first" => $first, "last" => $last);

This is how it is returned without the second parameter (as an instance of stdClass).

What is the use of "object sender" and "EventArgs e" parameters?

Those two parameters (or variants of) are sent, by convention, with all events.

  • sender: The object which has raised the event
  • e an instance of EventArgs including, in many cases, an object which inherits from EventArgs. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.

In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs are Empty as there is no further information about the event.

Looking at the 2 parameters separately, here are some examples where they are useful.

sender

Say you have multiple buttons on a form. These buttons could contain a Tag describing what clicking them should do. You could handle all the Click events with the same handler, and depending on the sender do something different

private void HandleButtonClick(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    if(btn.Tag == "Hello")
      MessageBox.Show("Hello")
    else if(btn.Tag == "Goodbye")
       Application.Exit();
    // etc.
}

Disclaimer : That's a contrived example; don't do that!

e

Some events are cancelable. They send CancelEventArgs instead of EventArgs. This object adds a simple boolean property Cancel on the event args. Code handling this event can cancel the event:

private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
    if(/* some condition*/)
    {
       // Cancel this event
       e.Cancel = true;
    }
}

Day Name from Date in JS

Easiest and simplest way:

var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var dayName = days[new Date().getDay()];

How to get all keys with their values in redis

Tried the given example, but over VPN and with 400k+ keys it was too slow for me. Also it did not give me the key objects.

I wrote a small Python called tool redis-mass-get to combine KEYS and MGET requests against Redis:

# installation:
pip install redis-mass-get

# pipeline example CSV:
redis-mass-get -f csv -och redis://my.redis.url product:* | less

# write to json-file example with progress indicator:
redis-mass-get -d results.json -jd redis://my.redis.url product:*

It supports JSON, CSV and TXT output to file or stdout for usage in pipes. More info can be found at: Reading multiple key/values from Redis.

JSON for List of int

JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:

{
    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [42, 47, 139]
}

AngularJS: How to make angular load script inside ng-include?

Short answer: AngularJS ("jqlite") doesn't support this. Include jQuery on your page (before including Angular), and it should work. See https://groups.google.com/d/topic/angular/H4haaMePJU0/discussion

How to detect the device orientation using CSS media queries?

CSS to detect screen orientation:

 @media screen and (orientation:portrait) { … }
 @media screen and (orientation:landscape) { … }

The CSS definition of a media query is at http://www.w3.org/TR/css3-mediaqueries/#orientation

Detecting an undefined object property

I didn't see (hope I didn't miss it) anyone checking the object before the property. So, this is the shortest and most effective (though not necessarily the most clear):

if (obj && obj.prop) {
  // Do something;
}

If the obj or obj.prop is undefined, null, or "falsy", the if statement will not execute the code block. This is usually the desired behavior in most code block statements (in JavaScript).

How to create empty data frame with column names specified in R?

Just create a data.frame with 0 length variables

eg

nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)

## 'data.frame':    0 obs. of  3 variables:
##  $ x: num 
##  $ y: int 
##  $ z: Factor w/ 0 levels: 

or to create a data.frame with 5 columns named a,b,c,d,e

nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))

How does inline Javascript (in HTML) work?

It looks suspicious because there is no apparent function that is being returned from!

It is an anonymous function that has been attached to the click event of the object.

why are you doing this, Steve?

Why on earth are you doi.....Ah nevermind, as you've mentioned, it really is widely adopted bad practice :)

git-upload-pack: command not found, when cloning remote Git repo

Building on Brian's answer, the upload-pack path can be set permanently by running the following commands after cloning, which eliminates the need for --upload-pack on subsequent pull/fetch requests. Similarly, setting receive-pack eliminates the need for --receive-pack on push requests.

git config remote.origin.uploadpack /path/to/git-upload-pack
git config remote.origin.receivepack /path/to/git-receive-pack

These two commands are equivalent to adding the following lines to a repo's .git/config.

[remote "origin"]
    uploadpack = /path/to/git-upload-pack
    receivepack = /path/to/git-receive-pack

Frequent users of clone -u may be interested in the following aliases. myclone should be self-explanatory. myfetch/mypull/mypush can be used on repos whose config hasn't been modified as described above by replacing git push with git mypush, and so on.

[alias]
    myclone = clone --upload-pack /path/to/git-upload-pack
    myfetch = fetch --upload-pack /path/to/git-upload-pack
    mypull  = pull --upload-pack /path/to/git-upload-pack
    mypush  = push --receive-pack /path/to/git-receive-pack

Using 'sudo apt-get install build-essentials'

Try 'build-essential' instead.

Convert string to date in Swift

  • Convert the ISO8601 string to date

    let isoDate = "2016-04-14T10:44:00+0000"
    
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    let date = dateFormatter.date(from:isoDate)!
    
  • Get the date components for year, month, day and hour from the date

    let calendar = Calendar.current
    let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)
    
  • Finally create a new Date object and strip minutes and seconds

    let finalDate = calendar.date(from:components)
    

Consider also the convenience formatter ISO8601DateFormatter introduced in iOS 10 / macOS 12:

let isoDate = "2016-04-14T10:44:00+0000"

let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!

Difference between static class and singleton pattern?

I'm agree with this definition:

The word "single" means single object across the application life cycle, so the scope is at application level.

The static does not have any Object pointer, so the scope is at App Domain level.

Moreover both should be implemented to be thread-safe.

You can find interesting other differences about: Singleton Pattern Versus Static Class

Find and replace strings in vim on multiple lines

The :&& command repeats the last substitution with the same flags. You can supply the additional range(s) to it (and concatenate as many as you like):

:6,10s/<search_string>/<replace_string>/g | 14,18&&

If you have many ranges though, I'd rather use a loop:

:for range in split('6,10 14,18')| exe range 's/<search_string>/<replace_string>/g' | endfor

How to create a project from existing source in Eclipse and then find it?

Follow this instructions from standard eclipse docs.

  1. From the main menu bar, select command link File > Import.... The Import wizard opens.
  2. Select General > Existing Project into Workspace and click Next.
  3. Choose either Select root directory or Select archive file and click the associated Browse to locate the directory or file containing the projects.
  4. Under Projects select the project or projects which you would like to import.
  5. Click Finish to start the import.

How to import CSV file data into a PostgreSQL table?

IMHO, the most convenient way is to follow "Import CSV data into postgresql, the comfortable way ;-)", using csvsql from csvkit, which is a python package installable via pip.

Reset git proxy to default configuration

For me, I had to add:

git config --global --unset http.proxy

Basically, you can run:

git config --global -l 

to get the list of all proxy defined, and then use "--unset" to disable them

In Git, how do I figure out what my current revision is?

There are many ways git log -1 is the easiest and most common, I think

Converting EditText to int? (Android)

you have to used.

String value= et.getText().toString();
int finalValue=Integer.parseInt(value);

if you have only allow enter number then set EditText property.

android:inputType="number"

if this is helpful then accept otherwise put your comment.

jQuery: If this HREF contains

You could just outright select the elements of interest.

$('a[href*="?"]').each(function() {
    alert('Contains question mark');
});

http://jsfiddle.net/mattball/TzUN3/

Note that you were using the attribute-ends-with selector, the above code uses the attribute-contains selector, which is what it sounds like you're actually aiming for.

How to encode URL to avoid special characters in Java?

URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".

RFC 2396 explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).

In Java, the correct way to build a URL is with the URI class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString() method gives you a properly-escaped and encoded string that you can send to a server. To decode a URL, construct a URI object using the single-string constructor and then use the accessor methods (such as getPath()) to retrieve the decoded components.

Don't use the URLEncoder class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's not correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a URLEncoder. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).

How do I convert a string to a double in Python?

The decimal operator might be more in line with what you are looking for:

>>> from decimal import Decimal
>>> x = "234243.434"
>>> print Decimal(x)
234243.434

No ConcurrentList<T> in .Net 4.0?

System.Collections.Generic.List<t> is already thread safe for multiple readers. Trying to make it thread safe for multiple writers wouldn't make sense. (For reasons Henk and Stephen already mentioned)

Can I get JSON to load into an OrderedDict?

The normally used load command will work if you specify the object_pairs_hook parameter:

import json
from  collections import OrderedDict
with open('foo.json', 'r') as fp:
    metrics_types = json.load(fp, object_pairs_hook=OrderedDict)

fail to change placeholder color with Bootstrap 3

I'm using Bootstrap 4 and Dennis Puzak's solution does not work for me.

The next solution works for me

.form-control::placeholder { color: white;} /* Chrome, Firefox, Opera*/
:-ms-input-placeholder.form-control { color: white; }  /* Internet Explorer*/
.form-control::-ms-input-placeholder { color: white; }  /* Microsoft Edge*/

How does Zalgo text work?

The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).

In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character

So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).

And you can mix “combining above” and “combining below” marks.

The sample text in the question starts with:

DataTable, How to conditionally delete rows

You could query the dataset and then loop the selected rows to set them as delete.

var rows = dt.Select("col1 > 5");
foreach (var row in rows)
    row.Delete();

... and you could also create some extension methods to make it easier ...

myTable.Delete("col1 > 5");

public static DataTable Delete(this DataTable table, string filter)
{
    table.Select(filter).Delete();
    return table;
}
public static void Delete(this IEnumerable<DataRow> rows)
{
    foreach (var row in rows)
        row.Delete();
}

"Line contains NULL byte" in CSV reader (Python)

If you want to replace the nulls with something you can do this:

def fix_nulls(s):
    for line in s:
        yield line.replace('\0', ' ')

r = csv.reader(fix_nulls(open(...)))

How to print time in format: 2009-08-10 18:17:54.811

time.h defines a strftime function which can give you a textual representation of a time_t using something like:

#include <stdio.h>
#include <time.h>
int main (void) {
    char buff[100];
    time_t now = time (0);
    strftime (buff, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now));
    printf ("%s\n", buff);
    return 0;
}

but that won't give you sub-second resolution since that's not available from a time_t. It outputs:

2010-09-09 10:08:34.000

If you're really constrained by the specs and do not want the space between the day and hour, just remove it from the format string.

bootstrap 3 tabs not working properly

This will work

$(".nav-tabs a").click(function(){
     $(this).tab('show');
 });

Event handlers for Twitter Bootstrap dropdowns?

Here is a working example of how you could implement custom functions for your anchors.

http://jsfiddle.net/CH2NZ/43/

You can attach an id to your anchor:

<li><a id="alertMe" href="#">Action</a></li>

And then use jQuery's click event listener to listen for the click action and fire you function:

$('#alertMe').click(function(e) {
    alert('alerted');
    e.preventDefault();// prevent the default anchor functionality
});

Can I write a CSS selector selecting elements NOT having a certain class or attribute?

Using the :not() pseudo class:

For selecting everything but a certain element (or elements). We can use the :not() CSS pseudo class. The :not() pseudo class requires a CSS selector as its argument. The selector will apply the styles to all the elements except for the elements which are specified as an argument.

Examples:

_x000D_
_x000D_
/* This query selects All div elements except for   */_x000D_
div:not(.foo) {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* Selects all hovered nav elements inside section element except_x000D_
   for the nav elements which have the ID foo*/_x000D_
section nav:hover:not(#foo) {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* selects all li elements inside an ul which are not odd */_x000D_
ul li:not(:nth-child(odd)) { _x000D_
  color: red;_x000D_
}
_x000D_
<div>test</div>_x000D_
<div class="foo">test</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<section>_x000D_
  <nav id="foo">test</nav>_x000D_
  <nav>Hover me!!!</nav>_x000D_
</section>_x000D_
<nav></nav>_x000D_
_x000D_
<br>_x000D_
_x000D_
<ul>_x000D_
  <li>1</li>_x000D_
  <li>2</li>_x000D_
  <li>3</li>_x000D_
  <li>4</li>_x000D_
  <li>5</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

We can already see the power of this pseudo class, it allows us to conveniently fine tune our selectors by excluding certain elements. Furthermore, this pseudo class increases the specificity of the selector. For example:

_x000D_
_x000D_
/* This selector has a higher specificity than the #foo below */_x000D_
#foo:not(#bar) {_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
/* This selector is lower in the cascade but is overruled by the style above */_x000D_
#foo {_x000D_
  color: green;_x000D_
}
_x000D_
<div id="foo">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor_x000D_
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</div>
_x000D_
_x000D_
_x000D_

Convert a python 'type' object to a string

>>> class A(object): pass

>>> e = A()
>>> e
<__main__.A object at 0xb6d464ec>
>>> print type(e)
<class '__main__.A'>
>>> print type(e).__name__
A
>>> 

what do you mean by convert into a string? you can define your own repr and str_ methods:

>>> class A(object):
    def __repr__(self):
        return 'hei, i am A or B or whatever'

>>> e = A()
>>> e
hei, i am A or B or whatever
>>> str(e)
hei, i am A or B or whatever

or i dont know..please add explainations ;)

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

I get this every time I want to create an application in VC++.

Right-click the project, select Properties then under 'Configuration properties | C/C++ | Code Generation', select "Multi-threaded Debug (/MTd)" for Debug configuration.

Note that this does not change the setting for your Release configuration - you'll need to go to the same location and select "Multi-threaded (/MT)" for Release.

Eclipse EGit Checkout conflict with files: - EGit doesn't want to continue

This is the way I solved my problem:

  1. Right click the folder that has uncommitted changes on your local
  2. Click Team > Advanced > Assume Unchanged
  3. Pull from master.

UPDATE:

As Hugo Zuleta rightly pointed out, you should be careful while applying this. He says that it might end up saying the branch is up to date, but the changes aren't shown, resulting in desync from the branch.

How to convert from []byte to int in Go Programming

(reposting this answer)

You can use encoding/binary's ByteOrder to do this for 16, 32, 64 bit types

Play

package main

import "fmt"
import "encoding/binary"

func main() {
    var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
    data := binary.BigEndian.Uint64(mySlice)
    fmt.Println(data)
}

How do I iterate and modify Java Sets?

You could create a mutable wrapper of the primitive int and create a Set of those:

class MutableInteger
{
    private int value;
    public int getValue()
    {
        return value;
    }
    public void setValue(int value)
    {
        this.value = value;
    }
}

class Test
{
    public static void main(String[] args)
    {
        Set<MutableInteger> mySet = new HashSet<MutableInteger>();
        // populate the set
        // ....

        for (MutableInteger integer: mySet)
        {
            integer.setValue(integer.getValue() + 1);
        }
    }
}

Of course if you are using a HashSet you should implement the hash, equals method in your MutableInteger but that's outside the scope of this answer.

Deleting rows with Python in a CSV file

You should have if row[2] != "0". Otherwise it's not checking to see if the string value is equal to 0.

How to use both onclick and target="_blank"

you can use

        <p><a href="/link/to/url" target="_blank"><button id="btn_id">Present Name </button></a></p>

Git push rejected after feature branch rebase

Instead of using -f or --force developers should use

--force-with-lease

Why? Because it checks the remote branch for changes which is absolutely a good idea. Let's imagine that James and Lisa are working on the same feature branch and Lisa has pushed a commit. James now rebases his local branch and is rejected when trying to push. Of course James thinks this is due to rebase and uses --force and would rewrite all Lisa's changes. If James had used --force-with-lease he would have received a warning that there are commits done by someone else. I don't see why anyone would use --force instead of --force-with-lease when pushing after a rebase.

How to disable auto-play for local video in iframe

What do you think about video tag ? If you don't have to use iframe tag you can use video tag instead.

<video width="500" height="345" src="hey.mp4"  />

You should not use autoplay attribute in your video tag to disable autoplay.

Bootstrap 3 Navbar with Logo

Why is everyone trying to do it the hard way? Sure, some of these approaches will work, but they're more complicated than is necessary.

OK, first - you need an image that will fit within your navbar. You can adjust your image via css height attribute (allowing width to scale) or you can just use an appropriately sized image. Whatever you decide to do - the way this looks will depend on how well you size your image.

For some reason, everyone wants to stick the image inside of an anchor with navbar-brand, and this isn't necessary. navbar-brand applies text styles that aren't necessary to an image, as well as the navbar-left class (just like pull-left, but for use in a navbar). All you really need is to add navbar-left.

<a href="#" class="navbar-left"><img src="/path/to/image.png"></a>

You can even follow this with a navbar-brand item, which will appear to the right of the image.

JQuery string contains check

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";

sttr1.search(str2);

it will return the position of the match, or -1 if it isn't found.

async at console app in C#?

My solution. The JSONServer is a class I wrote for running an HttpListener server in a console window.

class Program
{
    public static JSONServer srv = null;

    static void Main(string[] args)
    {
        Console.WriteLine("NLPS Core Server");

        srv = new JSONServer(100);
        srv.Start();

        InputLoopProcessor();

        while(srv.IsRunning)
        {
            Thread.Sleep(250);
        }

    }

    private static async Task InputLoopProcessor()
    {
        string line = "";

        Console.WriteLine("Core NLPS Server: Started on port 8080. " + DateTime.Now);

        while(line != "quit")
        {
            Console.Write(": ");
            line = Console.ReadLine().ToLower();
            Console.WriteLine(line);

            if(line == "?" || line == "help")
            {
                Console.WriteLine("Core NLPS Server Help");
                Console.WriteLine("    ? or help: Show this help.");
                Console.WriteLine("    quit: Stop the server.");
            }
        }
        srv.Stop();
        Console.WriteLine("Core Processor done at " + DateTime.Now);

    }
}

Creating threads - Task.Factory.StartNew vs new Thread()

The task gives you all the goodness of the task API:

  • Adding continuations (Task.ContinueWith)
  • Waiting for multiple tasks to complete (either all or any)
  • Capturing errors in the task and interrogating them later
  • Capturing cancellation (and allowing you to specify cancellation to start with)
  • Potentially having a return value
  • Using await in C# 5
  • Better control over scheduling (if it's going to be long-running, say so when you create the task so the task scheduler can take that into account)

Note that in both cases you can make your code slightly simpler with method group conversions:

DataInThread = new Thread(ThreadProcedure);
// Or...
Task t = Task.Factory.StartNew(ThreadProcedure);

Is there a "do ... until" in Python?

There is no do-while loop in Python.

This is a similar construct, taken from the link above.

 while True:
     do_something()
     if condition():
        break

How to turn a vector into a matrix in R?

Just use matrix:

matrix(vec,nrow = 7,ncol = 7)

One advantage of using matrix rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow argument in matrix.

Replace multiple characters in a C# string

Ohhh, the performance horror! The answer is a bit outdated, but still...

public static class StringUtils
{
    #region Private members

    [ThreadStatic]
    private static StringBuilder m_ReplaceSB;

    private static StringBuilder GetReplaceSB(int capacity)
    {
        var result = m_ReplaceSB;

        if (null == result)
        {
            result = new StringBuilder(capacity);
            m_ReplaceSB = result;
        }
        else
        {
            result.Clear();
            result.EnsureCapacity(capacity);
        }

        return result;
    }


    public static string ReplaceAny(this string s, char replaceWith, params char[] chars)
    {
        if (null == chars)
            return s;

        if (null == s)
            return null;

        StringBuilder sb = null;

        for (int i = 0, count = s.Length; i < count; i++)
        {
            var temp = s[i];
            var replace = false;

            for (int j = 0, cc = chars.Length; j < cc; j++)
                if (temp == chars[j])
                {
                    if (null == sb)
                    {
                        sb = GetReplaceSB(count);
                        if (i > 0)
                            sb.Append(s, 0, i);
                    }

                    replace = true;
                    break;
                }

            if (replace)
                sb.Append(replaceWith);
            else
                if (null != sb)
                    sb.Append(temp);
        }

        return null == sb ? s : sb.ToString();
    }
}

Import Maven dependencies in IntelliJ IDEA

A possible pattern for this issue is that you dont have connection to Nexus and basically you want to build the project in offline mode. But when you import the project Idea tries to download Maven dependencies automatically.. and fails. You set Work Offline checkbox in Settings, but its too late: something was already broken during initial download attempt. Neither of the options listed here worked for me to resolve this. Instead I did the following:

  1. first created empty Java (not Maven) project
  2. checked Work Offline option in Maven settings
  3. added my project as a Maven module to this new project

This way it worked.

Store output of subprocess.Popen call in a string

for Python 2.7+ the idiomatic answer is to use subprocess.check_output()

You should also note the handling of arguments when invoking a subprocess, as it can be a little confusing....

If args is just single command with no args of its own (or you have shell=True set), it can be a string. Otherwise it must be a list.

for example... to invoke the ls command, this is fine:

from subprocess import check_call
check_call('ls')

so is this:

from subprocess import check_call
check_call(['ls',])

however, if you want to pass some args to the shell command, you can't do this:

from subprocess import check_call
check_call('ls -al')

instead, you must pass it as a list:

from subprocess import check_call
check_call(['ls', '-al'])

the shlex.split() function can sometimes be useful to split a string into shell-like syntax before creating a subprocesses... like this:

from subprocess import check_call
import shlex
check_call(shlex.split('ls -al'))

Duplicating a MySQL table, indices, and data

Apart from the solution above, you can use AS to make it in one line.

CREATE TABLE tbl_new AS SELECT * FROM tbl_old;

What's the best way to check if a file exists in C?

Use stat like this:

#include <sys/stat.h>   // stat
#include <stdbool.h>    // bool type

bool file_exists (char *filename) {
  struct stat   buffer;   
  return (stat (filename, &buffer) == 0);
}

and call it like this:

#include <stdio.h>      // printf

int main(int ac, char **av) {
    if (ac != 2)
        return 1;

    if (file_exists(av[1]))
        printf("%s exists\n", av[1]);
    else
        printf("%s does not exist\n", av[1]);

    return 0;
}

An example of how to use getopts in bash

I know that this is already answered, but for the record and for anyone with the same requeriments as me I decided to post this related answer. The code is flooded with comments to explain the code.

Updated answer:

Save the file as getopt.sh:

#!/bin/bash

function get_variable_name_for_option {
    local OPT_DESC=${1}
    local OPTION=${2}
    local VAR=$(echo ${OPT_DESC} | sed -e "s/.*\[\?-${OPTION} \([A-Z_]\+\).*/\1/g" -e "s/.*\[\?-\(${OPTION}\).*/\1FLAG/g")

    if [[ "${VAR}" == "${1}" ]]; then
        echo ""
    else
        echo ${VAR}
    fi
}

function parse_options {
    local OPT_DESC=${1}
    local INPUT=$(get_input_for_getopts "${OPT_DESC}")

    shift
    while getopts ${INPUT} OPTION ${@};
    do
        [ ${OPTION} == "?" ] && usage
        VARNAME=$(get_variable_name_for_option "${OPT_DESC}" "${OPTION}")
            [ "${VARNAME}" != "" ] && eval "${VARNAME}=${OPTARG:-true}" # && printf "\t%s\n" "* Declaring ${VARNAME}=${!VARNAME} -- OPTIONS='$OPTION'"
    done

    check_for_required "${OPT_DESC}"

}

function check_for_required {
    local OPT_DESC=${1}
    local REQUIRED=$(get_required "${OPT_DESC}" | sed -e "s/\://g")
    while test -n "${REQUIRED}"; do
        OPTION=${REQUIRED:0:1}
        VARNAME=$(get_variable_name_for_option "${OPT_DESC}" "${OPTION}")
                [ -z "${!VARNAME}" ] && printf "ERROR: %s\n" "Option -${OPTION} must been set." && usage
        REQUIRED=${REQUIRED:1}
    done
}

function get_input_for_getopts {
    local OPT_DESC=${1}
    echo ${OPT_DESC} | sed -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/[][ -]//g"
}

function get_optional {
    local OPT_DESC=${1}
    echo ${OPT_DESC} | sed -e "s/[^[]*\(\[[^]]*\]\)[^[]*/\1/g" -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/[][ -]//g"
}

function get_required {
    local OPT_DESC=${1}
    echo ${OPT_DESC} | sed -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/\[[^[]*\]//g" -e "s/[][ -]//g"
}

function usage {
    printf "Usage:\n\t%s\n" "${0} ${OPT_DESC}"
    exit 10
}

Then you can use it like this:

#!/bin/bash
#
# [ and ] defines optional arguments
#

# location to getopts.sh file
source ./getopt.sh
USAGE="-u USER -d DATABASE -p PASS -s SID [ -a START_DATE_TIME ]"
parse_options "${USAGE}" ${@}

echo ${USER}
echo ${START_DATE_TIME}

Old answer:

I recently needed to use a generic approach. I came across with this solution:

#!/bin/bash
# Option Description:
# -------------------
#
# Option description is based on getopts bash builtin. The description adds a variable name feature to be used
# on future checks for required or optional values.
# The option description adds "=>VARIABLE_NAME" string. Variable name should be UPPERCASE. Valid characters
# are [A-Z_]*.
#
# A option description example:
#   OPT_DESC="a:=>A_VARIABLE|b:=>B_VARIABLE|c=>C_VARIABLE"
#
# -a option will require a value (the colon means that) and should be saved in variable A_VARIABLE.
# "|" is used to separate options description.
# -b option rule applies the same as -a.
# -c option doesn't require a value (the colon absense means that) and its existence should be set in C_VARIABLE
#
#   ~$ echo get_options ${OPT_DESC}
#   a:b:c
#   ~$
#


# Required options 
REQUIRED_DESC="a:=>REQ_A_VAR_VALUE|B:=>REQ_B_VAR_VALUE|c=>REQ_C_VAR_FLAG"

# Optional options (duh)
OPTIONAL_DESC="P:=>OPT_P_VAR_VALUE|r=>OPT_R_VAR_FLAG"

function usage {
    IFS="|"
    printf "%s" ${0}
    for i in ${REQUIRED_DESC};
    do
        VARNAME=$(echo $i | sed -e "s/.*=>//g")
    printf " %s" "-${i:0:1} $VARNAME"
    done

    for i in ${OPTIONAL_DESC};
    do
        VARNAME=$(echo $i | sed -e "s/.*=>//g")
        printf " %s" "[-${i:0:1} $VARNAME]"
    done
    printf "\n"
    unset IFS
    exit
}

# Auxiliary function that returns options characters to be passed
# into 'getopts' from a option description.
# Arguments:
#   $1: The options description (SEE TOP)
#
# Example:
#   OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
#   OPTIONS=$(get_options ${OPT_DESC})
#   echo "${OPTIONS}"
#
# Output:
#   "h:f:PW"
function get_options {
    echo ${1} | sed -e "s/\([a-zA-Z]\:\?\)=>[A-Z_]*|\?/\1/g"
}

# Auxiliary function that returns all variable names separated by '|'
# Arguments:
#       $1: The options description (SEE TOP)
#
# Example:
#       OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
#       VARNAMES=$(get_values ${OPT_DESC})
#       echo "${VARNAMES}"
#
# Output:
#       "H_VAR|F_VAR|P_VAR|W_VAR"
function get_variables {
    echo ${1} | sed -e "s/[a-zA-Z]\:\?=>\([^|]*\)/\1/g"
}

# Auxiliary function that returns the variable name based on the
# option passed by.
# Arguments:
#   $1: The options description (SEE TOP)
#   $2: The option which the variable name wants to be retrieved
#
# Example:
#   OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
#   H_VAR=$(get_variable_name ${OPT_DESC} "h")
#   echo "${H_VAR}"
#
# Output:
#   "H_VAR"
function get_variable_name {
    VAR=$(echo ${1} | sed -e "s/.*${2}\:\?=>\([^|]*\).*/\1/g")
    if [[ ${VAR} == ${1} ]]; then
        echo ""
    else
        echo ${VAR}
    fi
}

# Gets the required options from the required description
REQUIRED=$(get_options ${REQUIRED_DESC})

# Gets the optional options (duh) from the optional description
OPTIONAL=$(get_options ${OPTIONAL_DESC})

# or... $(get_options "${OPTIONAL_DESC}|${REQUIRED_DESC}")

# The colon at starts instructs getopts to remain silent
while getopts ":${REQUIRED}${OPTIONAL}" OPTION
do
    [[ ${OPTION} == ":" ]] && usage
    VAR=$(get_variable_name "${REQUIRED_DESC}|${OPTIONAL_DESC}" ${OPTION})
    [[ -n ${VAR} ]] && eval "$VAR=${OPTARG}"
done

shift $(($OPTIND - 1))

# Checks for required options. Report an error and exits if
# required options are missing.

# Using function version ...
VARS=$(get_variables ${REQUIRED_DESC})
IFS="|"
for VARNAME in $VARS;
do
    [[ -v ${VARNAME} ]] || usage
done
unset IFS

# ... or using IFS Version (no function)
OLDIFS=${IFS}
IFS="|"
for i in ${REQUIRED_DESC};
do
    VARNAME=$(echo $i | sed -e "s/.*=>//g")
    [[ -v ${VARNAME} ]] || usage
    printf "%s %s %s\n" "-${i:0:1}" "${!VARNAME:=present}" "${VARNAME}"
done
IFS=${OLDIFS}

I didn't test this roughly, so I could have some bugs in there.

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Try using SCP on Windows to transfer files, you can download SCP from Putty's website. Then try running:

pscp.exe filename.extension [email protected]:directory/subdirectory

There is a full length guide here.

How do I do an OR filter in a Django query?

Similar to older answers, but a bit simpler, without the lambda:

filter_kwargs = {
    'field_a': 123,
    'field_b__in': (3, 4, 5, ),
}

To filter these two conditions using OR:

Item.objects.filter(Q(field_a=123) | Q(field_b__in=(3, 4, 5, ))

To get the same result programmatically:

list_of_Q = [Q(**{key: val}) for key, val in filter_kwargs.items()]
Item.objects.filter(reduce(operator.or_, list_of_Q))

(broken in two lines here, for clarity)

operator is in standard library: import operator
From docstring:

or_(a, b) -- Same as a | b.

For Python3, reduce is not a builtin any more but is still in the standard library: from functools import reduce


P.S.

Don't forget to make sure list_of_Q is not empty - reduce() will choke on empty list, it needs at least one element.

Collectors.toMap() keyMapper -- more succinct expression?

You can use a lambda:

Collectors.toMap(p -> p.getLast(), Function.identity())

or, more concisely, you can use a method reference using :::

Collectors.toMap(Person::getLast, Function.identity())

and instead of Function.identity, you can simply use the equivalent lambda:

Collectors.toMap(Person::getLast, p -> p)

If you use Netbeans you should get hints whenever an anonymous class can be replaced by a lambda.

Preventing form resubmission

If you refresh a page with POST data, the browser will confirm your resubmission. If you use GET data, the message will not be displayed. You could also have the second page, after saving the submission, redirect to a third page with no data.

How can I divide two integers stored in variables in Python?

Use this line to get the division behavior you want:

from __future__ import division

Alternatively, you could use modulus:

if (a % b) == 0: #do something

Rails 4: how to use $(document).ready() with turbo-links

$(document).on 'ready turbolinks:load', ->
  console.log '(document).turbolinks:load'

Java String.split() Regex

str.split (" ") 
res27: Array[java.lang.String] = Array(a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j)

Can't resolve module (not found) in React.js

Check for the import statements.It should be ended with semicolon. If you miss any, you will get this error.

Also check whether following import statement added in you component.

import { threadId } from 'worker_threads';

If so remove that line. It works for me.

How do I load a PHP file into a variable?

I suppose you want to get the content generated by PHP, if so use:

$Vdata = file_get_contents('http://YOUR_HOST/YOUR/FILE.php');

Otherwise if you want to get the source code of the PHP file, it's the same as a .txt file:

$Vdata = file_get_contents('path/to/YOUR/FILE.php');