Programs & Examples On #Page numbering

How do you make strings "XML safe"?

By either escaping those characters with htmlspecialchars, or, perhaps more appropriately, using a library for building XML documents, such as DOMDocument or XMLWriter.

Another alternative would be to use CDATA sections, but then you'd have to look out for occurrences of ]]>.

Take also into consideration that that you must respect the encoding you define for the XML document (by default UTF-8).

What is the use of BindingResult interface in spring MVC?

It's important to note that the order of parameters is actually important to spring. The BindingResult needs to come right after the Form that is being validated. Likewise, the [optional] Model parameter needs to come after the BindingResult. Example:

Valid:

@RequestMapping(value = "/entry/updateQuantity", method = RequestMethod.POST)
public String updateEntryQuantity(@Valid final UpdateQuantityForm form,
                                  final BindingResult bindingResult,
                                  @RequestParam("pk") final long pk,
                                  final Model model) {
}

Not Valid:

RequestMapping(value = "/entry/updateQuantity", method = RequestMethod.POST)
public String updateEntryQuantity(@Valid final UpdateQuantityForm form,
                                  @RequestParam("pk") final long pk,
                                  final BindingResult bindingResult,
                                  final Model model) {
}

Resize image proportionally with CSS?

Try this:

div.container {
    max-width: 200px;//real picture size
    max-height: 100px;
}

/* resize images */
div.container img {
    width: 100%;
    height: auto;
}

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

When you install php53-mysql using port it returns the following message which is the solution to this problem:

To use mysqlnd with a local MySQL server, edit /opt/local/etc/php53/php.ini
and set mysql.default_socket, mysqli.default_socket and
pdo_mysql.default_socket to the path to your MySQL server's socket file.

For mysql5, use /opt/local/var/run/mysql5/mysqld.sock
For mysql51, use /opt/local/var/run/mysql51/mysqld.sock
For mysql55, use /opt/local/var/run/mysql55/mysqld.sock
For mariadb, use /opt/local/var/run/mariadb/mysqld.sock
For percona, use /opt/local/var/run/percona/mysqld.sock

Parsing a pcap file in python

I would use python-dpkt. Here is the documentation: http://www.commercialventvac.com/dpkt.html

This is all I know how to do though sorry.

#!/usr/local/bin/python2.7

import dpkt

counter=0
ipcounter=0
tcpcounter=0
udpcounter=0

filename='sampledata.pcap'

for ts, pkt in dpkt.pcap.Reader(open(filename,'r')):

    counter+=1
    eth=dpkt.ethernet.Ethernet(pkt) 
    if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
       continue

    ip=eth.data
    ipcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_TCP: 
       tcpcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_UDP:
       udpcounter+=1

print "Total number of packets in the pcap file: ", counter
print "Total number of ip packets: ", ipcounter
print "Total number of tcp packets: ", tcpcounter
print "Total number of udp packets: ", udpcounter

Update:

Project on GitHub, documentation here

How to prevent a browser from storing passwords

This worked for me:

<form action='/login' class='login-form' autocomplete='off'>
  User:
  <input type='user' name='user-entry'>
  <input type='hidden' name='user'>

  Password:
  <input type='password' name='password-entry'>
  <input type='hidden' name='password'>
</form>

How to set String's font size, style in Java using the Font class?

Font myFont = new Font("Serif", Font.BOLD, 12);, then use a setFont method on your components like

JButton b = new JButton("Hello World");
b.setFont(myFont);

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

Another easy way to circumvent google's check is to use another compression algorithm with tar, like bz2:

tar -cvjf my.tar.bz2 dir/

Note that 'j' (for bz2 compression) is used above instead of 'z' (gzip compression).

Linux command: How to 'find' only text files?

Here's a simplified version with extended explanation for beginners like me who are trying to learn how to put more than one command in one line.

If you were to write out the problem in steps, it would look like this:

// For every file in this directory
// Check the filetype
// If it's an ASCII file, then print out the filename

To achieve this, we can use three UNIX commands: find, file, and grep.

find will check every file in the directory.

file will give us the filetype. In our case, we're looking for a return of 'ASCII text'

grep will look for the keyword 'ASCII' in the output from file

So how can we string these together in a single line? There are multiple ways to do it, but I find that doing it in order of our pseudo-code makes the most sense (especially to a beginner like me).

find ./ -exec file {} ";" | grep 'ASCII'

Looks complicated, but not bad when we break it down:

find ./ = look through every file in this directory. The find command prints out the filename of any file that matches the 'expression', or whatever comes after the path, which in our case is the current directory or ./

The most important thing to understand is that everything after that first bit is going to be evaluated as either True or False. If True, the file name will get printed out. If not, then the command moves on.

-exec = this flag is an option within the find command that allows us to use the result of some other command as the search expression. It's like calling a function within a function.

file {} = the command being called inside of find. The file command returns a string that tells you the filetype of a file. Regularly, it would look like this: file mytextfile.txt. In our case, we want it to use whatever file is being looked at by the find command, so we put in the curly braces {} to act as an empty variable, or parameter. In other words, we're just asking for the system to output a string for every file in the directory.

";" = this is required by find and is the punctuation mark at the end of our -exec command. See the manual for 'find' for more explanation if you need it by running man find.

| grep 'ASCII' = | is a pipe. Pipe take the output of whatever is on the left and uses it as input to whatever is on the right. It takes the output of the find command (a string that is the filetype of a single file) and tests it to see if it contains the string 'ASCII'. If it does, it returns true.

NOW, the expression to the right of find ./ will return true when the grep command returns true. Voila.

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

All you need to do is to go to the control panel > Computer Management > Services and manually start the SQL express or SQL server. It worked for me.

Good luck.

Split a large pandas dataframe

I also experienced np.array_split not working with Pandas DataFrame my solution was to only split the index of the DataFrame and then introduce a new column with the "group" label:

indexes = np.array_split(df.index,N, axis=0)
for i,index in enumerate(indexes):
   df.loc[index,'group'] = i

This makes grouby operations very convenient for instance calculation of mean value of each group:

df.groupby(by='group').mean()

C++, What does the colon after a constructor mean?

It's called an initialization list. It initializes members before the body of the constructor executes.

Psql list all tables

If you wish to list all tables, you must use:

\dt *.*

to indicate that you want all tables in all schemas. This will include tables in pg_catalog, the system tables, and those in information_schema. There's no built-in way to say "all tables in all user-defined schemas"; you can, however, set your search_path to a list of all schemas of interest before running \dt.

You may want to do this programmatically, in which case psql backslash-commands won't do the job. This is where the INFORMATION_SCHEMA comes to the rescue. To list tables:

SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';

BTW, if you ever want to see what psql is doing in response to a backslash command, run psql with the -E flag. eg:

$ psql -E regress    
regress=# \list
********* QUERY **********
SELECT d.datname as "Name",
       pg_catalog.pg_get_userbyid(d.datdba) as "Owner",
       pg_catalog.pg_encoding_to_char(d.encoding) as "Encoding",
       d.datcollate as "Collate",
       d.datctype as "Ctype",
       pg_catalog.array_to_string(d.datacl, E'\n') AS "Access privileges"
FROM pg_catalog.pg_database d
ORDER BY 1;
**************************

so you can see that psql is searching pg_catalog.pg_database when it gets a list of databases. Similarly, for tables within a given database:

SELECT n.nspname as "Schema",
  c.relname as "Name",
  CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' END as "Type",
  pg_catalog.pg_get_userbyid(c.relowner) as "Owner"
FROM pg_catalog.pg_class c
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','')
      AND n.nspname <> 'pg_catalog'
      AND n.nspname <> 'information_schema'
      AND n.nspname !~ '^pg_toast'
  AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2;

It's preferable to use the SQL-standard, portable INFORMATION_SCHEMA instead of the Pg system catalogs where possible, but sometimes you need Pg-specific information. In those cases it's fine to query the system catalogs directly, and psql -E can be a helpful guide for how to do so.

Create dynamic URLs in Flask with url_for()

url_for in Flask is used for creating a URL to prevent the overhead of having to change URLs throughout an application (including in templates). Without url_for, if there is a change in the root URL of your app then you have to change it in every page where the link is present.

Syntax: url_for('name of the function of the route','parameters (if required)')

It can be used as:

@app.route('/index')
@app.route('/')
def index():
    return 'you are in the index page'

Now if you have a link the index page:you can use this:

<a href={{ url_for('index') }}>Index</a>

You can do a lot o stuff with it, for example:

@app.route('/questions/<int:question_id>'):    #int has been used as a filter that only integer will be passed in the url otherwise it will give a 404 error
def find_question(question_id):  
    return ('you asked for question{0}'.format(question_id))

For the above we can use:

<a href = {{ url_for('find_question' ,question_id=1) }}>Question 1</a>

Like this you can simply pass the parameters!

How do I launch a Git Bash window with particular working directory using a script?

In addition, Win10 gives you an option to open git bash from your working directory by right-clicking on your folder and selecting GitBash here.

enter image description here

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

Since this result is the first that Google returns for this error, I'll just add that if anyone looks for way do change java security settings without changing the global file java.security (for example you need to run some tests), you can just provide an overriding security file by JVM parameter -Djava.security.properties=your/file/path in which you can enable the necessary algorithms by overriding the disablements.

What is *.o file?

A file ending in .o is an object file. The compiler creates an object file for each source file, before linking them together, into the final executable.

Check box size change with CSS

Try this

<input type="checkbox" style="zoom:1.5;" />
/* The value 1.5 i.e., the size of checkbox will be increased by 0.5% */

Node / Express: EADDRINUSE, Address already in use - Kill server

Rewriting @Gerard 's comment in my answer:

Try pkill nodejs or pkill node if on UNIX-like OS.

This will kill the process running the node server running on any port. Worked for me.

How to concatenate columns in a Postgres SELECT?

it is better to use CONCAT function in PostgreSQL for concatenation

eg : select CONCAT(first_name,last_name) from person where pid = 136

if you are using column_a || ' ' || column_b for concatenation for 2 column , if any of the value in column_a or column_b is null query will return null value. which may not be preferred in all cases.. so instead of this

||

use

CONCAT

it will return relevant value if either of them have value

Viewing unpushed Git commits

git log origin/master..HEAD

You can also view the diff using the same syntax

git diff origin/master..HEAD

What's the difference between IFrame and Frame?

IFrame is just an "internal frame". The reason why it can be considered less secure (than not using any kind of frame at all) is because you can include content that does not originate from your domain.

All this means is that you should trust whatever you include in an iFrame or a regular frame.

Frames and IFrames are equally secure (and insecure if you include content from an untrusted source).

Why does an image captured using camera intent gets rotated on some devices on Android?

I solved it using a different method. All you have to do is check if the width is greater than height

            Matrix rotationMatrix = new Matrix();
        if(finalBitmap.getWidth() >= finalBitmap.getHeight())
        {
            rotationMatrix.setRotate(-90);
        }
        else
        {
            rotationMatrix.setRotate(0);
        }

        Bitmap rotatedBitmap = Bitmap.createBitmap(finalBitmap,0,0,finalBitmap.getWidth(),finalBitmap.getHeight(),rotationMatrix,true);

How to compare dates in datetime fields in Postgresql?

When you compare update_date >= '2013-05-03' postgres casts values to the same type to compare values. So your '2013-05-03' was casted to '2013-05-03 00:00:00'.

So for update_date = '2013-05-03 14:45:00' your expression will be that:

'2013-05-03 14:45:00' >= '2013-05-03 00:00:00' AND '2013-05-03 14:45:00' <= '2013-05-03 00:00:00'

This is always false

To solve this problem cast update_date to date:

select * from table where update_date::date >= '2013-05-03' AND update_date::date <= '2013-05-03' -> Will return result

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • Download history stock prices automatically from yahoo finance in python

    When you're going to work with such time series in Python, pandas is indispensable. And here's the good news: it comes with a historical data downloader for Yahoo: pandas.io.data.DataReader.

    from pandas.io.data import DataReader
    from datetime import datetime
    
    ibm = DataReader('IBM',  'yahoo', datetime(2000, 1, 1), datetime(2012, 1, 1))
    print(ibm['Adj Close'])
    

    Here's an example from the pandas documentation.

    Update for pandas >= 0.19:

    The pandas.io.data module has been removed from pandas>=0.19 onwards. Instead, you should use the separate pandas-datareader package. Install with:

    pip install pandas-datareader
    

    And then you can do this in Python:

    import pandas_datareader as pdr
    from datetime import datetime
    
    ibm = pdr.get_data_yahoo(symbols='IBM', start=datetime(2000, 1, 1), end=datetime(2012, 1, 1))
    print(ibm['Adj Close'])
    

    Downloading from Google Finance is also supported.

    There's more in the documentation of pandas-datareader.

    Make a dictionary with duplicate keys in Python

    You can't have a dict with duplicate keys for definition! Instead you can use a single key and, as value, a list of elements that had that key.

    So you can follow these steps:

    1. See if the current element's (of your initial set) key is in the final dict. If it is, go to step 3
    2. Update dict with key
    3. Append the new value to the dict[key] list
    4. Repeat [1-3]

    Is it possible to style a select box?

    Update: As of 2013 the two I've seen that are worth checking are:

    • Chosen - loads of cool stuff, 7k+ watchers on github. (mentioned by 'a paid nerd' in the comments)
    • Select2 - inspired by Chosen, part of Angular-UI with a couple useful tweaks on Chosen.

    Yeah!


    As of 2012 one of the most lightweight, flexible solutions I've found is ddSlick. Relevant (edited) info from the site:

    • Adds images and text to select options
    • Can use JSON to populate options
    • Supports callback functions on selection

    And here's a preview of the various modes:

    enter image description here

    How to free memory from char array in C

    Local variables are automatically freed when the function ends, you don't need to free them by yourself. You only free dynamically allocated memory (e.g using malloc) as it's allocated on the heap:

    char *arr = malloc(3 * sizeof(char));
    strcpy(arr, "bo");
    // ...
    free(arr);
    

    More about dynamic memory allocation: http://en.wikipedia.org/wiki/C_dynamic_memory_allocation

    Basic HTTP authentication with Node and Express 4

    Simple Basic Auth with vanilla JavaScript (ES6)

    app.use((req, res, next) => {
    
      // -----------------------------------------------------------------------
      // authentication middleware
    
      const auth = {login: 'yourlogin', password: 'yourpassword'} // change this
    
      // parse login and password from headers
      const b64auth = (req.headers.authorization || '').split(' ')[1] || ''
      const [login, password] = Buffer.from(b64auth, 'base64').toString().split(':')
    
      // Verify login and password are set and correct
      if (login && password && login === auth.login && password === auth.password) {
        // Access granted...
        return next()
      }
    
      // Access denied...
      res.set('WWW-Authenticate', 'Basic realm="401"') // change this
      res.status(401).send('Authentication required.') // custom message
    
      // -----------------------------------------------------------------------
    
    })
    

    note: This "middleware" can be used in any handler. Just remove next() and reverse the logic. See the 1-statement example below, or the edit history of this answer.

    Why?

    • req.headers.authorization contains the value "Basic <base64 string>", but it can also be empty and we don't want it to fail, hence the weird combo of || ''
    • Node doesn't know atob() and btoa(), hence the Buffer

    ES6 -> ES5

    const is just var .. sort of
    (x, y) => {...} is just function(x, y) {...}
    const [login, password] = ...split() is just two var assignments in one

    source of inspiration (uses packages)


    The above is a super simple example that was intended to be super short and quickly deployable to your playground server. But as was pointed out in the comments, passwords can also contain colon characters :. To correctly extract it from the b64auth, you can use this.

      // parse login and password from headers
      const b64auth = (req.headers.authorization || '').split(' ')[1] || ''
      const strauth = Buffer.from(b64auth, 'base64').toString()
      const splitIndex = strauth.indexOf(':')
      const login = strauth.substring(0, splitIndex)
      const password = strauth.substring(splitIndex + 1)
    
      // using shorter regex by @adabru
      // const [_, login, password] = strauth.match(/(.*?):(.*)/) || []
    

    Basic auth in one statement

    ...on the other hand, if you only ever use one or very few logins, this is the bare minimum you need: (you don't even need to parse the credentials at all)

    function (req, res) {
    //btoa('yourlogin:yourpassword') -> "eW91cmxvZ2luOnlvdXJwYXNzd29yZA=="
    //btoa('otherlogin:otherpassword') -> "b3RoZXJsb2dpbjpvdGhlcnBhc3N3b3Jk"
    
      // Verify credentials
      if (  req.headers.authorization !== 'Basic eW91cmxvZ2luOnlvdXJwYXNzd29yZA=='
         && req.headers.authorization !== 'Basic b3RoZXJsb2dpbjpvdGhlcnBhc3N3b3Jk')        
        return res.status(401).send('Authentication required.') // Access denied.   
    
      // Access granted...
      res.send('hello world')
      // or call next() if you use it as middleware (as snippet #1)
    }
    

    PS: do you need to have both "secure" and "public" paths? Consider using express.router instead.

    var securedRoutes = require('express').Router()
    
    securedRoutes.use(/* auth-middleware from above */)
    securedRoutes.get('path1', /* ... */) 
    
    app.use('/secure', securedRoutes)
    app.get('public', /* ... */)
    
    // example.com/public       // no-auth
    // example.com/secure/path1 // requires auth
    

    Change mysql user password using command line

    Your login root should be /usr/local/directadmin/conf/mysql.conf. Then try following

    UPDATE mysql.user SET password=PASSWORD('$w0rdf1sh') WHERE user='tate256' AND Host='10.10.2.30';
    FLUSH PRIVILEGES;
    

    Host is your mysql host.

    How do I display Ruby on Rails form validation error messages one at a time?

    After experimenting for a few hours I figured it out.

    <% if @user.errors.full_messages.any? %>
      <% @user.errors.full_messages.each do |error_message| %>
        <%= error_message if @user.errors.full_messages.first == error_message %> <br />
      <% end %>
    <% end %>
    

    Even better:

    <%= @user.errors.full_messages.first if @user.errors.any? %>
    

    Daemon Threads Explanation

    Let's say you're making some kind of dashboard widget. As part of this, you want it to display the unread message count in your email box. So you make a little thread that will:

    1. Connect to the mail server and ask how many unread messages you have.
    2. Signal the GUI with the updated count.
    3. Sleep for a little while.

    When your widget starts up, it would create this thread, designate it a daemon, and start it. Because it's a daemon, you don't have to think about it; when your widget exits, the thread will stop automatically.

    how to send an array in url request

    Separate with commas:

    http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505
    

    or:

    http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505
    

    or:

    http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505
    

    Either way, your method signature needs to be:

    @RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
    public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
       //code to get results from db for those params.
     }
    

    How to add Google Maps Autocomplete search box?

    <!DOCTYPE html>
    <html>
      <head>
        <title>Place Autocomplete Address Form</title>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <style>
          html, body, #map-canvas {
            height: 100%;
            margin: 0px;
            padding: 0px
          }
        </style>
        <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
        <script>
    // This example displays an address form, using the autocomplete feature
    // of the Google Places API to help users fill in the information.
    
    var placeSearch, autocomplete;
    var componentForm = {
      street_number: 'short_name',
      route: 'long_name',
      locality: 'long_name',
      administrative_area_level_1: 'short_name',
      country: 'long_name',
      postal_code: 'short_name'
    };
    
    function initialize() {
      // Create the autocomplete object, restricting the search
      // to geographical location types.
      autocomplete = new google.maps.places.Autocomplete(
          /** @type {HTMLInputElement} */(document.getElementById('autocomplete')),
          { types: ['geocode'] });
      // When the user selects an address from the dropdown,
      // populate the address fields in the form.
      google.maps.event.addListener(autocomplete, 'place_changed', function() {
        fillInAddress();
      });
    }
    
    // [START region_fillform]
    function fillInAddress() {
      // Get the place details from the autocomplete object.
      var place = autocomplete.getPlace();
    
      for (var component in componentForm) {
        document.getElementById(component).value = '';
        document.getElementById(component).disabled = false;
      }
    
      // Get each component of the address from the place details
      // and fill the corresponding field on the form.
      for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];
        if (componentForm[addressType]) {
          var val = place.address_components[i][componentForm[addressType]];
          document.getElementById(addressType).value = val;
        }
      }
    }
    // [END region_fillform]
    
    // [START region_geolocation]
    // Bias the autocomplete object to the user's geographical location,
    // as supplied by the browser's 'navigator.geolocation' object.
    function geolocate() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var geolocation = new google.maps.LatLng(
              position.coords.latitude, position.coords.longitude);
          var circle = new google.maps.Circle({
            center: geolocation,
            radius: position.coords.accuracy
          });
          autocomplete.setBounds(circle.getBounds());
        });
      }
    }
    // [END region_geolocation]
    
        </script>
    
        <style>
          #locationField, #controls {
            position: relative;
            width: 480px;
          }
          #autocomplete {
            position: absolute;
            top: 0px;
            left: 0px;
            width: 99%;
          }
          .label {
            text-align: right;
            font-weight: bold;
            width: 100px;
            color: #303030;
          }
          #address {
            border: 1px solid #000090;
            background-color: #f0f0ff;
            width: 480px;
            padding-right: 2px;
          }
          #address td {
            font-size: 10pt;
          }
          .field {
            width: 99%;
          }
          .slimField {
            width: 80px;
          }
          .wideField {
            width: 200px;
          }
          #locationField {
            height: 20px;
            margin-bottom: 2px;
          }
        </style>
      </head>
    
      <body onload="initialize()">
        <div id="locationField">
          <input id="autocomplete" placeholder="Enter your address"
                 onFocus="geolocate()" type="text"></input>
        </div>
    
    
      </body>
    </html>
    

    Fully custom validation error message with Rails

    Here is another way:

    If you use this template:

    <% if @thing.errors.any? %>
      <ul>
        <% @thing.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    <% end %>
    

    You can write you own custom message like this:

    class Thing < ActiveRecord::Base
    
      validate :custom_validation_method_with_message
    
      def custom_validation_method_with_message
        if some_model_attribute.blank?
          errors.add(:_, "My custom message")
        end
      end
    

    This way, because of the underscore, the full message becomes " My custom message", but the extra space in the beginning is unnoticeable. If you really don't want that extra space at the beginning just add the .lstrip method.

    <% if @thing.errors.any? %>
      <ul>
        <% @thing.errors.full_messages.each do |message| %>
          <li><%= message.lstrip %></li>
        <% end %>
      </ul>
    <% end %>
    

    The String.lstrip method will get rid of the extra space created by ':_' and will leave any other error messages unchanged.

    Or even better, use the first word of your custom message as the key:

      def custom_validation_method_with_message
        if some_model_attribute.blank?
          errors.add(:my, "custom message")
        end
      end
    

    Now the full message will be "My custom message" with no extra space.

    If you want the full message to start with a word capitalized like "URL can't be blank" it cannot be done. Instead try adding some other word as the key:

      def custom_validation_method_with_message
        if some_model_attribute.blank?
          errors.add(:the, "URL can't be blank")
        end
      end
    

    Now the full message will be "The URL can't be blank"

    ValidateAntiForgeryToken purpose, explanation and example

    MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.

    It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form, or by simply programmatically triggering a form when the page loads.

    The feature doesn't prevent any other type of data forgery or tampering based attacks.

    To use it, decorate the action method or controller with the ValidateAntiForgeryToken attribute and place a call to @Html.AntiForgeryToken() in the forms posting to the method.

    C# ASP.NET Single Sign-On Implementation

    There are multiple options to implement SSO for a .NET application.

    Check out the following tutorials online:

    Basics of Single Sign on, July 2012

    http://www.codeproject.com/Articles/429166/Basics-of-Single-Sign-on-SSO

    GaryMcAllisterOnline: ASP.NET MVC 4, ADFS 2.0 and 3rd party STS integration (IdentityServer2), Jan 2013

    http://garymcallisteronline.blogspot.com/2013/01/aspnet-mvc-4-adfs-20-and-3rd-party-sts.html

    The first one uses ASP.NET Web Forms, while the second one uses ASP.NET MVC4.

    If your requirements allow you to use a third-party solution, also consider OpenID. There's an open source library called DotNetOpenAuth.

    For further information, read MSDN blog post Integrate OpenAuth/OpenID with your existing ASP.NET application using Universal Providers.

    Hope this helps!

    How to properly assert that an exception gets raised in pytest?

    Have you tried to remove "pytrace=True" ?

    pytest.fail(exc, pytrace=True) # before
    pytest.fail(exc) # after
    

    Have you tried to run with '--fulltrace' ?

    How to get xdebug var_dump to show full object/array

    I'd like to recommend var_export($array) - it doesn't show types, but it generates syntax you can use in your code :)

    What are good examples of genetic algorithms/genetic programming solutions?

    Evolutionary Computation Graduate Class: Developed a solution for TopCoder Marathon Match 49: MegaParty. My small group was testing different domain representations and how the different representation would affect the ga's ability to find the correct answer. We rolled our own code for this problem.

    Neuroevolution and Generative and Developmental Systems, Graduate Class: Developed an Othello game board evaluator that was used in the min-max tree of a computer player. The player was set to evaluate one-deep into the game, and trained to play against a greedy computer player that considered corners of vital importance. The training player saw either 3 or 4 deep (I'll need to look at my config files to answer, and they're on a different computer). The goal of the experiment was to compare Novelty Search to traditional, fitness-based search in the Game Board Evaluation domain. Results were relatively inconclusive, unfortunately. While both the novelty search and fitness-based search methods came to a solution (showing that Novelty Search can be used in the Othello domain), it was possible to have a solution to this domain with no hidden nodes. Apparently I didn't create a sufficiently competent trainer if a linear solution was available (and it was possible to have a solution right out of the gates). I believe my implementation of Fitness-based search produced solutions more quickly than my implementation of Novelty search, this time. (this isn't always the case). Either way, I used ANJI, "Another NEAT Java Implementation" for the neural network code, with various modifications. The Othello game I wrote myself.

    System.drawing namespace not found under console application

    Add reference .dll file to project. Right, Click on Project reference folder --> click on Add Reference -->.Net tab you will find System.Drawing --> click on ok this will add a reference to System.Drawing

    How to evaluate http response codes from bash/shell script?

    curl --write-out "%{http_code}\n" --silent --output /dev/null "$URL"
    

    works. If not, you have to hit return to view the code itself.

    How to reset (clear) form through JavaScript?

    You can simply do:

    $("#client.frm").trigger('reset')

    Initialize class fields in constructor or at declaration?

    Consider the situation where you have more than one constructor. Will the initialization be different for the different constructors? If they will be the same, then why repeat for each constructor? This is in line with kokos statement, but may not be related to parameters. Let's say, for example, you want to keep a flag which shows how the object was created. Then that flag would be initialized differently for different constructors regardless of the constructor parameters. On the other hand, if you repeat the same initialization for each constructor you leave the possibility that you (unintentionally) change the initialization parameter in some of the constructors but not in others. So, the basic concept here is that common code should have a common location and not be potentially repeated in different locations. So I would say always put it in the declaration until you have a specific situation where that no longer works for you.

    How do I base64 encode a string efficiently using Excel VBA?

    This code works very fast. It comes from here

    Option Explicit
    
    Private Const clOneMask = 16515072          '000000 111111 111111 111111
    Private Const clTwoMask = 258048            '111111 000000 111111 111111
    Private Const clThreeMask = 4032            '111111 111111 000000 111111
    Private Const clFourMask = 63               '111111 111111 111111 000000
    
    Private Const clHighMask = 16711680         '11111111 00000000 00000000
    Private Const clMidMask = 65280             '00000000 11111111 00000000
    Private Const clLowMask = 255               '00000000 00000000 11111111
    
    Private Const cl2Exp18 = 262144             '2 to the 18th power
    Private Const cl2Exp12 = 4096               '2 to the 12th
    Private Const cl2Exp6 = 64                  '2 to the 6th
    Private Const cl2Exp8 = 256                 '2 to the 8th
    Private Const cl2Exp16 = 65536              '2 to the 16th
    
    Public Function Encode64(sString As String) As String
    
        Dim bTrans(63) As Byte, lPowers8(255) As Long, lPowers16(255) As Long, bOut() As Byte, bIn() As Byte
        Dim lChar As Long, lTrip As Long, iPad As Integer, lLen As Long, lTemp As Long, lPos As Long, lOutSize As Long
    
        For lTemp = 0 To 63                                 'Fill the translation table.
            Select Case lTemp
                Case 0 To 25
                    bTrans(lTemp) = 65 + lTemp              'A - Z
                Case 26 To 51
                    bTrans(lTemp) = 71 + lTemp              'a - z
                Case 52 To 61
                    bTrans(lTemp) = lTemp - 4               '1 - 0
                Case 62
                    bTrans(lTemp) = 43                      'Chr(43) = "+"
                Case 63
                    bTrans(lTemp) = 47                      'Chr(47) = "/"
            End Select
        Next lTemp
    
        For lTemp = 0 To 255                                'Fill the 2^8 and 2^16 lookup tables.
            lPowers8(lTemp) = lTemp * cl2Exp8
            lPowers16(lTemp) = lTemp * cl2Exp16
        Next lTemp
    
        iPad = Len(sString) Mod 3                           'See if the length is divisible by 3
        If iPad Then                                        'If not, figure out the end pad and resize the input.
            iPad = 3 - iPad
            sString = sString & String(iPad, Chr(0))
        End If
    
        bIn = StrConv(sString, vbFromUnicode)               'Load the input string.
        lLen = ((UBound(bIn) + 1) \ 3) * 4                  'Length of resulting string.
        lTemp = lLen \ 72                                   'Added space for vbCrLfs.
        lOutSize = ((lTemp * 2) + lLen) - 1                 'Calculate the size of the output buffer.
        ReDim bOut(lOutSize)                                'Make the output buffer.
    
        lLen = 0                                            'Reusing this one, so reset it.
    
        For lChar = LBound(bIn) To UBound(bIn) Step 3
            lTrip = lPowers16(bIn(lChar)) + lPowers8(bIn(lChar + 1)) + bIn(lChar + 2)    'Combine the 3 bytes
            lTemp = lTrip And clOneMask                     'Mask for the first 6 bits
            bOut(lPos) = bTrans(lTemp \ cl2Exp18)           'Shift it down to the low 6 bits and get the value
            lTemp = lTrip And clTwoMask                     'Mask for the second set.
            bOut(lPos + 1) = bTrans(lTemp \ cl2Exp12)       'Shift it down and translate.
            lTemp = lTrip And clThreeMask                   'Mask for the third set.
            bOut(lPos + 2) = bTrans(lTemp \ cl2Exp6)        'Shift it down and translate.
            bOut(lPos + 3) = bTrans(lTrip And clFourMask)   'Mask for the low set.
            If lLen = 68 Then                               'Ready for a newline
                bOut(lPos + 4) = 13                         'Chr(13) = vbCr
                bOut(lPos + 5) = 10                         'Chr(10) = vbLf
                lLen = 0                                    'Reset the counter
                lPos = lPos + 6
            Else
                lLen = lLen + 4
                lPos = lPos + 4
            End If
        Next lChar
    
        If bOut(lOutSize) = 10 Then lOutSize = lOutSize - 2 'Shift the padding chars down if it ends with CrLf.
    
        If iPad = 1 Then                                    'Add the padding chars if any.
            bOut(lOutSize) = 61                             'Chr(61) = "="
        ElseIf iPad = 2 Then
            bOut(lOutSize) = 61
            bOut(lOutSize - 1) = 61
        End If
    
        Encode64 = StrConv(bOut, vbUnicode)                 'Convert back to a string and return it.
    
    End Function
    
    Public Function Decode64(sString As String) As String
    
        Dim bOut() As Byte, bIn() As Byte, bTrans(255) As Byte, lPowers6(63) As Long, lPowers12(63) As Long
        Dim lPowers18(63) As Long, lQuad As Long, iPad As Integer, lChar As Long, lPos As Long, sOut As String
        Dim lTemp As Long
    
        sString = Replace(sString, vbCr, vbNullString)      'Get rid of the vbCrLfs.  These could be in...
        sString = Replace(sString, vbLf, vbNullString)      'either order.
    
        lTemp = Len(sString) Mod 4                          'Test for valid input.
        If lTemp Then
            Call Err.Raise(vbObjectError, "MyDecode", "Input string is not valid Base64.")
        End If
    
        If InStrRev(sString, "==") Then                     'InStrRev is faster when you know it's at the end.
            iPad = 2                                        'Note:  These translate to 0, so you can leave them...
        ElseIf InStrRev(sString, "=") Then                  'in the string and just resize the output.
            iPad = 1
        End If
    
        For lTemp = 0 To 255                                'Fill the translation table.
            Select Case lTemp
                Case 65 To 90
                    bTrans(lTemp) = lTemp - 65              'A - Z
                Case 97 To 122
                    bTrans(lTemp) = lTemp - 71              'a - z
                Case 48 To 57
                    bTrans(lTemp) = lTemp + 4               '1 - 0
                Case 43
                    bTrans(lTemp) = 62                      'Chr(43) = "+"
                Case 47
                    bTrans(lTemp) = 63                      'Chr(47) = "/"
            End Select
        Next lTemp
    
        For lTemp = 0 To 63                                 'Fill the 2^6, 2^12, and 2^18 lookup tables.
            lPowers6(lTemp) = lTemp * cl2Exp6
            lPowers12(lTemp) = lTemp * cl2Exp12
            lPowers18(lTemp) = lTemp * cl2Exp18
        Next lTemp
    
        bIn = StrConv(sString, vbFromUnicode)               'Load the input byte array.
        ReDim bOut((((UBound(bIn) + 1) \ 4) * 3) - 1)       'Prepare the output buffer.
    
        For lChar = 0 To UBound(bIn) Step 4
            lQuad = lPowers18(bTrans(bIn(lChar))) + lPowers12(bTrans(bIn(lChar + 1))) + _
                    lPowers6(bTrans(bIn(lChar + 2))) + bTrans(bIn(lChar + 3))           'Rebuild the bits.
            lTemp = lQuad And clHighMask                    'Mask for the first byte
            bOut(lPos) = lTemp \ cl2Exp16                   'Shift it down
            lTemp = lQuad And clMidMask                     'Mask for the second byte
            bOut(lPos + 1) = lTemp \ cl2Exp8                'Shift it down
            bOut(lPos + 2) = lQuad And clLowMask            'Mask for the third byte
            lPos = lPos + 3
        Next lChar
    
        sOut = StrConv(bOut, vbUnicode)                     'Convert back to a string.
        If iPad Then sOut = Left$(sOut, Len(sOut) - iPad)   'Chop off any extra bytes.
        Decode64 = sOut
    
    End Function
    

    Visual Studio Code compile on save

    I implemented compile on save with gulp task using gulp-typescript and incremental build. This allows to control compilation whatever you want. Notice my variable tsServerProject, in my real project I also have tsClientProject because I want to compile my client code with no module specified. As I know you can't do it with vs code.

    var gulp = require('gulp'),
        ts = require('gulp-typescript'),
        sourcemaps = require('gulp-sourcemaps');
    
    var tsServerProject = ts.createProject({
       declarationFiles: false,
       noExternalResolve: false,
       module: 'commonjs',
       target: 'ES5'
    });
    
    var srcServer = 'src/server/**/*.ts'
    
    gulp.task('watch-server', ['compile-server'], watchServer);
    gulp.task('compile-server', compileServer);
    
    function watchServer(params) {
       gulp.watch(srcServer, ['compile-server']);
    }
    
    function compileServer(params) {
       var tsResult = gulp.src(srcServer)
          .pipe(sourcemaps.init())
          .pipe(ts(tsServerProject));
    
       return tsResult.js
          .pipe(sourcemaps.write('./source-maps'))
          .pipe(gulp.dest('src/server/'));
    
    }
    

    Parsing JSON Object in Java

    I'm assuming you want to store the interestKeys in a list.

    Using the org.json library:

    JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
    
    List<String> list = new ArrayList<String>();
    JSONArray array = obj.getJSONArray("interests");
    for(int i = 0 ; i < array.length() ; i++){
        list.add(array.getJSONObject(i).getString("interestKey"));
    }
    

    How to change the DataTable Column Name?

    Rename the Column by doing the following:

    dataTable.Columns["ColumnName"].ColumnName = "newColumnName";
    

    How do I extract data from a DataTable?

    You can set the datatable as a datasource to many elements.

    For eg

    gridView

    repeater

    datalist

    etc etc

    If you need to extract data from each row then you can use

    table.rows[rowindex][columnindex]
    

    or

    if you know the column name

    table.rows[rowindex][columnname]
    

    If you need to iterate the table then you can either use a for loop or a foreach loop like

    for ( int i = 0; i < table.rows.length; i ++ )
    {
        string name = table.rows[i]["columnname"].ToString();
    }
    
    foreach ( DataRow dr in table.Rows )
    {
        string name = dr["columnname"].ToString();
    }
    

    Set value for particular cell in pandas DataFrame with iloc

    Extending Jianxun's answer, using set_value mehtod in pandas. It sets value for a column at given index.

    From pandas documentations:

    DataFrame.set_value(index, col, value)

    To set value at particular index for a column, do:

    df.set_value(index, 'COL_NAME', x)
    

    Hope it helps.

    PHP Check for NULL

    Use is_null or === operator.

    is_null($result['column'])
    
    $result['column'] === NULL
    

    Ignoring NaNs with str.contains

    import folium
    import pandas
    
    data= pandas.read_csv("maps.txt")
    
    lat = list(data["latitude"])
    lon = list(data["longitude"])
    
    map= folium.Map(location=[31.5204, 74.3587], zoom_start=6, tiles="Mapbox Bright")
    
    fg = folium.FeatureGroup(name="My Map")
    
    for lt, ln in zip(lat, lon):
    c1 = fg.add_child(folium.Marker(location=[lt, ln], popup="Hi i am a Country",icon=folium.Icon(color='green')))
    
    child = fg.add_child(folium.Marker(location=[31.5204, 74.5387], popup="Welcome to Lahore", icon= folium.Icon(color='green')))
    
    map.add_child(fg)
    
    map.save("Lahore.html")
    
    
    Traceback (most recent call last):
      File "C:\Users\Ryan\AppData\Local\Programs\Python\Python36-32\check2.py", line 14, in <module>
        c1 = fg.add_child(folium.Marker(location=[lt, ln], popup="Hi i am a Country",icon=folium.Icon(color='green')))
      File "C:\Users\Ryan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\folium\map.py", line 647, in __init__
        self.location = _validate_coordinates(location)
      File "C:\Users\Ryan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\folium\utilities.py", line 48, in _validate_coordinates
        'got:\n{!r}'.format(coordinates))
    ValueError: Location values cannot contain NaNs, got:
    [nan, nan]
    

    How do I work with a git repository within another repository?

    If I understand your problem well you want the following things:

    1. Have your media files stored in one single git repository, which is used by many projects
    2. If you modify a media file in any of the projects in your local machine, it should immediately appear in every other project (so you don't want to commit+push+pull all the time)

    Unfortunately there is no ultimate solution for what you want, but there are some things by which you can make your life easier.

    First you should decide one important thing: do you want to store for every version in your project repository a reference to the version of the media files? So for example if you have a project called example.com, do you need know which style.css it used 2 weeks ago, or the latest is always (or mostly) the best?

    If you don't need to know that, the solution is easy:

    1. create a repository for the media files and one for each project
    2. create a symbolic link in your projects which point to the locally cloned media repository. You can either create a relative symbolic link (e.g. ../media) and assume that everybody will checkout the project so that the media directory is in the same place, or write the name of the symbolic link into .gitignore, and everybody can decide where he/she puts the media files.

    In most of the cases, however, you want to know this versioning information. In this case you have two choices:

    1. Store every project in one big repository. The advantage of this solution is that you will have only 1 copy of the media repository. The big disadvantage is that it is much harder to switch between project versions (if you checkout to a different version you will always modify ALL projects)

    2. Use submodules (as explained in answer 1). This way you will store the media files in one repository, and the projects will contain only a reference to a specific media repo version. But this way you will normally have many local copies of the media repository, and you cannot easily modify a media file in all projects.

    If I were you I would probably choose the first or third solution (symbolic links or submodules). If you choose to use submodules you can still do a lot of things to make your life easier:

    1. Before committing you can rename the submodule directory and put a symlink to a common media directory. When you're ready to commit, you can remove the symlink and remove the submodule back, and then commit.

    2. You can add one of your copy of the media repository as a remote repository to all of your projects.

    You can add local directories as a remote this way:

    cd /my/project2/media
    git remote add project1 /my/project1/media
    

    If you modify a file in /my/project1/media, you can commit it and pull it from /my/project2/media without pushing it to a remote server:

    cd /my/project1/media
    git commit -a -m "message"
    cd /my/project2/media
    git pull project1 master
    

    You are free to remove these commits later (with git reset) because you haven't shared them with other users.

    Bash: If/Else statement in one line

    Use grep -vc to ignore grep in the ps output and count the lines simultaneously.

    if [[ $(ps aux | grep process | grep -vc grep)  > 0 ]] ; then echo 1; else echo 0 ; fi
    

    How to make a char string from a C macro's value?

    @Jonathan Leffler: Thank you. Your solution works.

    A complete working example:

    /** compile-time dispatch 
    
       $ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub
    */
    #include <stdio.h>
    
    #define QUOTE(name) #name
    #define STR(macro) QUOTE(macro)
    
    #ifndef TEST_FUN
    #  define TEST_FUN some_func
    #endif
    
    #define TEST_FUN_NAME STR(TEST_FUN)
    
    void some_func(void)
    {
      printf("some_func() called\n");
    }
    
    void another_func(void)
    {
      printf("do something else\n");
    }
    
    int main(void)
    {
      TEST_FUN();
      printf("TEST_FUN_NAME=%s\n", TEST_FUN_NAME);
      return 0;
    }
    

    Example:

    $ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub
    do something else
    TEST_FUN_NAME=another_func
    

    Connect to Oracle DB using sqlplus

    Easy way (using XE):

    1). Configure your tnsnames.ora

    XE =
      (DESCRIPTION =
        (ADDRESS = (PROTOCOL = TCP)(HOST = HOST.DOMAIN.COM)(PORT = 1521))
        (CONNECT_DATA =
          (SERVER = DEDICATED)
          (SERVICE_NAME = XE)
        )
      )
    

    You can replace HOST.DOMAIN.COM with IP address, the TCP port by default is 1521 (ckeck it) and look that name of this configuration is XE

    2). Using your app named sqlplus:

    sqlplus SYSTEM@XE
    

    SYSTEM should be replaced with an authorized USER, and put your password when prompt appear

    3). See at firewall for any possibilities of some blocked TCP ports and fix it if appear

    Change event on select with knockout binding, how can I know if it is a real change?

    I use this custom binding (based on this fiddle by RP Niemeyer, see his answer to this question), which makes sure the numeric value is properly converted from string to number (as suggested by the solution of Michael Best):

    Javascript:

    ko.bindingHandlers.valueAsNumber = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var observable = valueAccessor(),
                interceptor = ko.computed({
                    read: function () {
                        var val = ko.utils.unwrapObservable(observable);
                        return (observable() ? observable().toString() : observable());
                    },
                    write: function (newValue) {
                        observable(newValue ? parseInt(newValue, 10) : newValue);
                    },
                    owner: this
                });
            ko.applyBindingsToNode(element, { value: interceptor });
        }
    };
    

    Example HTML:

    <select data-bind="valueAsNumber: level, event:{ change: $parent.permissionChanged }">
        <option value="0"></option>
        <option value="1">R</option>
        <option value="2">RW</option>
    </select>
    

    Call to getLayoutInflater() in places not in activity

    or

    View.inflate(context, layout, parent)

    How do I install the yaml package for Python?

    Debian-based systems:

    $ sudo aptitude install python-yaml

    or newer for python3

    $ sudo aptitude install python3-yaml

    How to get back to the latest commit after checking out a previous commit?

    git reflog //find the hash of the commit that you want to checkout
    git checkout <commit number>>
    

    Shift column in pandas dataframe up by one?

    shift column gdp up:

    df.gdp = df.gdp.shift(-1)
    

    and then remove the last row

    Objective-C - Remove last character from string

    The documentation is your friend, NSString supports a call substringWithRange that can shorten the string that you have an return the shortened String. You cannot modify an instance of NSString it is immutable. If you have an NSMutableString is has a method called deleteCharactersInRange that can modify the string in place

    ...
    NSRange r;
    r.location = 0;
    r.size = [mutable length]-1;
    NSString* shorted = [stringValue substringWithRange:r];
    ...
    

    How to split one string into multiple variables in bash shell?

    If your solution doesn't have to be general, i.e. only needs to work for strings like your example, you could do:

    var1=$(echo $STR | cut -f1 -d-)
    var2=$(echo $STR | cut -f2 -d-)
    

    I chose cut here because you could simply extend the code for a few more variables...

    kill -3 to get java thread dump

    With Java 8 in picture, jcmd is the preferred approach.

    jcmd <PID> Thread.print
    

    Following is the snippet from Oracle documentation :

    The release of JDK 8 introduced Java Mission Control, Java Flight Recorder, and jcmd utility for diagnosing problems with JVM and Java applications. It is suggested to use the latest utility, jcmd instead of the previous jstack utility for enhanced diagnostics and reduced performance overhead.

    However, shipping this with the application may be licensing implications which I am not sure.

    How to save a plot into a PDF file without a large margin around

    Axes sizing in MATLAB can be a bit tricky sometimes. You are correct to suspect the paper sizing properties as one part of the problem. Another is the automatic margins MATLAB calculates. Fortunately, there are settable axes properties that allow you to circumvent these margins. You can reset the margins to be just big enough for axis labels using a combination of the Position and TightInset properties which are explained here. Try this:

    >> h = figure;
    >> axes;
    >> set(h, 'InvertHardcopy', 'off');
    >> saveas(h, 'WithMargins.pdf');
    

    and you'll get a PDF that looks like: MATLAB plot with auto-margins but now do this:

    >> tightInset = get(gca, 'TightInset');
    >> position(1) = tightInset(1);
    >> position(2) = tightInset(2);
    >> position(3) = 1 - tightInset(1) - tightInset(3);
    >> position(4) = 1 - tightInset(2) - tightInset(4);
    >> set(gca, 'Position', position);
    >> saveas(h, 'WithoutMargins.pdf');
    

    and you'll get: MATLAB plot with auto-margins removed

    How can you print a variable name in python?

    For the revised question of how to read in configuration parameters, I'd strongly recommend saving yourself some time and effort and use ConfigParser or (my preferred tool) ConfigObj.

    They can do everything you need, they're easy to use, and someone else has already worried about how to get them to work properly!

    What is the keyguard in Android?

    In a nutshell, it is your lockscreen.

    PIN, pattern, face, password locks or the default lock (slide to unlock), but it is your lock screen.

    Play audio as microphone input

    Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

    I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

    If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

    What is the difference between UNION and UNION ALL?

    The basic difference between UNION and UNION ALL is union operation eliminates the duplicated rows from the result set but union all returns all rows after joining.

    from http://zengin.wordpress.com/2007/07/31/union-vs-union-all/

    How to index into a dictionary?

    If you need an ordered dictionary, you can use odict.

    How to initialize a nested struct?

    You have this option also:

    type Configuration struct {
            Val string
            Proxy
    }
    
    type Proxy struct {
            Address string
            Port    string
    }
    
    func main() {
            c := &Configuration{"test", Proxy{"addr", "port"}}
            fmt.Println(c)
    }
    

    HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

    NullPointerException with JSP can also happen if:

    A getter returns a non-public inner class.

    This code will fail if you remove Getters's access modifier or make it private or protected.

    JAVA:

    package com.myPackage;
    public class MyClass{ 
        //: Must be public or you will get:
        //: org.apache.jasper.JasperException: 
        //: java.lang.NullPointerException
        public class Getters{
            public String 
            myProperty(){ return(my_property); }
        };;
    
        //: JSP EL can only access functions:
        private Getters _get;
        public  Getters  get(){ return _get; }
    
        private String 
        my_property;
    
        public MyClass(String my_property){
            super();
            this.my_property    = my_property;
            _get = new Getters();
        };;
    };;
    

    JSP

    <%@ taglib uri   ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ page import="com.myPackage.MyClass" %>
    <%
        MyClass inst = new MyClass("[PROP_VALUE]");
        pageContext.setAttribute("my_inst", inst ); 
    %><html lang="en"><body>
        ${ my_inst.get().myProperty() }
    </body></html>
    

    QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

    In April 2017 a patch was merged into Safari, so it aligned with the other browsers. This was released with Safari 11.

    https://bugs.webkit.org/show_bug.cgi?id=157010

    Python list subtraction operation

    Looking up values in sets are faster than looking them up in lists:

    [item for item in x if item not in set(y)]
    

    I believe this will scale slightly better than:

    [item for item in x if item not in y]
    

    Both preserve the order of the lists.

    How do I move files in node.js?

    I would separate all involved functions (i.e. rename, copy, unlink) from each other to gain flexibility and promisify everything, of course:

    const renameFile = (path, newPath) => 
      new Promise((res, rej) => {
        fs.rename(path, newPath, (err, data) =>
          err
            ? rej(err)
            : res(data));
      });
    
    const copyFile = (path, newPath, flags) =>
      new Promise((res, rej) => {
        const readStream = fs.createReadStream(path),
          writeStream = fs.createWriteStream(newPath, {flags});
    
        readStream.on("error", rej);
        writeStream.on("error", rej);
        writeStream.on("finish", res);
        readStream.pipe(writeStream);
      });
    
    const unlinkFile = path => 
      new Promise((res, rej) => {
        fs.unlink(path, (err, data) =>
          err
            ? rej(err)
            : res(data));
      });
    
    const moveFile = (path, newPath, flags) =>
      renameFile(path, newPath)
        .catch(e => {
          if (e.code !== "EXDEV")
            throw new e;
    
          else
            return copyFile(path, newPath, flags)
              .then(() => unlinkFile(path));
        });
    

    moveFile is just a convenience function and we can apply the functions separately, when, for example, we need finer grained exception handling.

    Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

    There is only three way to solve. paste in following code in this path application/config/autoload.php.

    most of them I use this

    require_once BASEPATH . '/helpers/url_helper.php';
    

    this is good but some time, it fail

    $autoload['helper'] = array('url');
    

    I never use it but I know it work

    $this->load->helper('url');
    

    Calling async method on button click

    use below code

     Task.WaitAll(Task.Run(async () => await GetResponse<MyObject>("my url")));
    

    How do I split a string so I can access item x?

    Here's my solution that may help someone. Modification of Jonesinator's answer above.

    If I have a string of delimited INT values and want a table of INTs returned (Which I can then join on). e.g. '1,20,3,343,44,6,8765'

    Create a UDF:

    IF OBJECT_ID(N'dbo.ufn_GetIntTableFromDelimitedList', N'TF') IS NOT NULL
        DROP FUNCTION dbo.[ufn_GetIntTableFromDelimitedList];
    GO
    
    CREATE FUNCTION dbo.[ufn_GetIntTableFromDelimitedList](@String NVARCHAR(MAX),                 @Delimiter CHAR(1))
    
    RETURNS @table TABLE 
    (
        Value INT NOT NULL
    )
    AS 
    BEGIN
    DECLARE @Pattern NVARCHAR(3)
    SET @Pattern = '%' + @Delimiter + '%'
    DECLARE @Value NVARCHAR(MAX)
    
    WHILE LEN(@String) > 0
        BEGIN
            IF PATINDEX(@Pattern, @String) > 0
            BEGIN
                SET @Value = SUBSTRING(@String, 0, PATINDEX(@Pattern, @String))
                INSERT INTO @table (Value) VALUES (@Value)
    
                SET @String = SUBSTRING(@String, LEN(@Value + @Delimiter) + 1, LEN(@String))
            END
            ELSE
            BEGIN
                -- Just the one value.
                INSERT INTO @table (Value) VALUES (@String)
                RETURN
            END
        END
    
    RETURN
    END
    GO
    

    Then get the table results:

    SELECT * FROM dbo.[ufn_GetIntTableFromDelimitedList]('1,20,3,343,44,6,8765', ',')
    
    1
    20
    3
    343
    44
    6
    8765
    

    And in a join statement:

    SELECT [ID], [FirstName]
    FROM [User] u
    JOIN dbo.[ufn_GetIntTableFromDelimitedList]('1,20,3,343,44,6,8765', ',') t ON u.[ID] = t.[Value]
    
    1    Elvis
    20   Karen
    3    David
    343  Simon
    44   Raj
    6    Mike
    8765 Richard
    

    If you want to return a list of NVARCHARs instead of INTs then just change the table definition:

    RETURNS @table TABLE 
    (
        Value NVARCHAR(MAX) NOT NULL
    )
    

    Compare two columns using pandas

    One way is to use a Boolean series to index the column df['one']. This gives you a new column where the True entries have the same value as the same row as df['one'] and the False values are NaN.

    The Boolean series is just given by your if statement (although it is necessary to use & instead of and):

    >>> df['que'] = df['one'][(df['one'] >= df['two']) & (df['one'] <= df['three'])]
    >>> df
        one two three   que
    0   10  1.2 4.2      10
    1   15  70  0.03    NaN
    2   8   5   0       NaN
    

    If you want the NaN values to be replaced by other values, you can use the fillna method on the new column que. I've used 0 instead of the empty string here:

    >>> df['que'] = df['que'].fillna(0)
    >>> df
        one two three   que
    0   10  1.2   4.2    10
    1   15   70  0.03     0
    2    8    5     0     0
    

    how to update the multiple rows at a time using linq to sql?

    Do not use the ToList() method as in the accepted answer !

    Running SQL profiler, I verified and found that ToList() function gets all the records from the database. It is really bad performance !!

    I would have run this query by pure sql command as follows:

    string query = "Update YourTable Set ... Where ...";    
    context.Database.ExecuteSqlCommandAsync(query, new SqlParameter("@ColumnY", value1), new SqlParameter("@ColumnZ", value2));
    

    This would operate the update in one-shot without selecting even one row.

    What’s the best way to reload / refresh an iframe?

    If you tried all of the other suggestions, and couldn't get any of them to work (like I couldn't), here's something you can try that may be useful.

    HTML

    <a class="refresh-this-frame" rel="#iframe-id-0">Refresh</a>
    <iframe src="" id="iframe-id-0"></iframe>
    

    JS

    $('.refresh-this-frame').click(function() {
        var thisIframe = $(this).attr('rel');
        var currentState = $(thisIframe).attr('src');
        function removeSrc() {
            $(thisIframe).attr('src', '');
        }
        setTimeout (removeSrc, 100);
        function replaceSrc() {
            $(thisIframe).attr('src', currentState);
        }
        setTimeout (replaceSrc, 200);
    });
    

    I initially set out to try and save some time with RWD and cross-browser testing. I wanted to create a quick page that housed a bunch of iframes, organized into groups that I would show/hide at will. Logically you'd want to be able to easily and quickly refresh any given frame.

    I should note that the project I am working on currently, the one in use in this test-bed, is a one-page site with indexed locations (e.g. index.html#home). That may have had something to do with why I couldn't get any of the other solutions to refresh my particular frame.

    Having said that, I know it's not the cleanest thing in the world, but it works for my purposes. Hope this helps someone. Now if only I could figure out how to keep the iframe from scrolling the parent page each time there's animation inside iframe...

    EDIT: I realized that this doesn't "refresh" the iframe like I'd hoped it would. It will reload the iframe's initial source though. Still can't figure out why I couldn't get any of the other options to work..

    UPDATE: The reason I couldn't get any of the other methods to work is because I was testing them in Chrome, and Chrome won't allow you to access an iframe's content (Explanation: Is it likely that future releases of Chrome support contentWindow/contentDocument when iFrame loads a local html file from local html file?) if it doesn't originate from the same location (so far as I understand it). Upon further testing, I can't access contentWindow in FF either.

    AMENDED JS

    $('.refresh-this-frame').click(function() {
        var targetID = $(this).attr('rel');
        var targetSrc = $(targetID).attr('src');
        var cleanID = targetID.replace("#","");     
        var chromeTest = ( navigator.userAgent.match(/Chrome/g) ? true : false );
        var FFTest = ( navigator.userAgent.match(/Firefox/g) ? true : false );      
        if (chromeTest == true) {
            function removeSrc() {
                $(targetID).attr('src', '');
            }
            setTimeout (removeSrc, 100);
            function replaceSrc() {
                $(targetID).attr('src', targetSrc);
            }
            setTimeout (replaceSrc, 200);
        }
        if (FFTest == true) {
            function removeSrc() {
                $(targetID).attr('src', '');
            }
            setTimeout (removeSrc, 100);
            function replaceSrc() {
                $(targetID).attr('src', targetSrc);
            }
            setTimeout (replaceSrc, 200);
        }       
        if (chromeTest == false && FFTest == false) {
            var targetLoc = (document.getElementById(cleanID).contentWindow.location).toString();
            function removeSrc() {
                $(targetID).attr('src', '');
            }
            setTimeout (removeSrc, 100);
            function replaceSrc2() {
                $(targetID).attr('src', targetLoc);
            }
            setTimeout (replaceSrc2, 200);
        }
    });
    

    How can I read an input string of unknown length?

    With the computers of today, you can get away with allocating very large strings (hundreds of thousands of characters) while hardly making a dent in the computer's RAM usage. So I wouldn't worry too much.

    However, in the old days, when memory was at a premium, the common practice was to read strings in chunks. fgets reads up to a maximum number of chars from the input, but leaves the rest of the input buffer intact, so you can read the rest from it however you like.

    in this example, I read in chunks of 200 chars, but you can use whatever chunk size you want of course.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    char* readinput()
    {
    #define CHUNK 200
       char* input = NULL;
       char tempbuf[CHUNK];
       size_t inputlen = 0, templen = 0;
       do {
           fgets(tempbuf, CHUNK, stdin);
           templen = strlen(tempbuf);
           input = realloc(input, inputlen+templen+1);
           strcpy(input+inputlen, tempbuf);
           inputlen += templen;
        } while (templen==CHUNK-1 && tempbuf[CHUNK-2]!='\n');
        return input;
    }
    
    int main()
    {
        char* result = readinput();
        printf("And the result is [%s]\n", result);
        free(result);
        return 0;
    }
    

    Note that this is a simplified example with no error checking; in real life you will have to make sure the input is OK by verifying the return value of fgets.

    Also note that at the end if the readinput routine, no bytes are wasted; the string has the exact memory size it needs to have.

    How to create and download a csv file from php script?

    Use the following,

    echo "<script type='text/javascript'> window.location.href = '$file_name'; </script>";
    

    Target a css class inside another css class

    I use div instead of tables and am able to target classes within the main class, as below:

    CSS

    .main {
        .width: 800px;
        .margin: 0 auto;
        .text-align: center;
    }
    .main .table {
        width: 80%;
    }
    .main .row {
       / ***something ***/
    }
    .main .column {
        font-size: 14px;
        display: inline-block;
    }
    .main .left {
        width: 140px;
        margin-right: 5px;
        font-size: 12px;
    }
    .main .right {
        width: auto;
        margin-right: 20px;
        color: #fff;
        font-size: 13px;
        font-weight: normal;
    }
    

    HTML

    <div class="main">
        <div class="table">
            <div class="row">
                <div class="column left">Swing Over Bed</div>
                <div class="column right">650mm</div>
                <div class="column left">Swing In Gap</div>
                <div class="column right">800mm</div>
            </div>
        </div>
    </div>
    

    If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:

    .main #red { color: red; }

    <div class="main">
        <div class="table">
            <div class="row">
                <div id="red" class="column left">Swing Over Bed</div>
                <div class="column right">650mm</div>
                <div class="column left">Swing In Gap</div>
                <div class="column right">800mm</div>
            </div>
        </div>
    </div>
    

    Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

    There's a great blog post on this here:

    http://www.kylejlarson.com/blog/2011/fixed-elements-and-scrolling-divs-in-ios-5/

    Along with a demo here:

    http://www.kylejlarson.com/files/iosdemo/

    In summary, you can use the following on a div containing your main content:

    .scrollable {
        position: absolute;
        top: 50px;
        left: 0;
        right: 0;
        bottom: 0;
        overflow: scroll;
        -webkit-overflow-scrolling: touch;
    }
    

    The problem I think you're describing is when you try to scroll up within a div that is already at the top - it then scrolls up the page instead of up the div and causes a bounce effect at the top of the page. I think your question is asking how to get rid of this?

    In order to fix this, the author suggests that you use ScrollFix to auto increase the height of scrollable divs.

    It's also worth noting that you can use the following to prevent the user from scrolling up e.g. in a navigation element:

    document.addEventListener('touchmove', function(event) {
       if(event.target.parentNode.className.indexOf('noBounce') != -1 
    || event.target.className.indexOf('noBounce') != -1 ) {
        event.preventDefault(); }
    }, false);
    

    Unfortunately there are still some issues with ScrollFix (e.g. when using form fields), but the issues list on ScrollFix is a good place to look for alternatives. Some alternative approaches are discussed in this issue.

    Other alternatives, also mentioned in the blog post, are Scrollability and iScroll

    How do I insert datetime value into a SQLite database?

    The way to store dates in SQLite is:

     yyyy-mm-dd hh:mm:ss.xxxxxx
    

    SQLite also has some date and time functions you can use. See SQL As Understood By SQLite, Date And Time Functions.

    python object() takes no parameters error

    I struggled for a while about this. Stupid rule for __init__. It is two "_" together to be "__"

    Java 11 package javax.xml.bind does not exist

    According to the release-notes, Java 11 removed the Java EE modules:

    java.xml.bind (JAXB) - REMOVED
    
    • Java 8 - OK
    • Java 9 - DEPRECATED
    • Java 10 - DEPRECATED
    • Java 11 - REMOVED

    See JEP 320 for more info.

    You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

    <dependency>
      <groupId>javax.xml.bind</groupId>
      <artifactId>jaxb-api</artifactId>
      <version>2.3.0</version>
    </dependency>
    <dependency>
      <groupId>com.sun.xml.bind</groupId>
      <artifactId>jaxb-core</artifactId>
      <version>2.3.0</version>
    </dependency>
    <dependency>
      <groupId>com.sun.xml.bind</groupId>
      <artifactId>jaxb-impl</artifactId>
      <version>2.3.0</version>
    </dependency>
    

    Jakarta EE 8 update (Mar 2020)

    Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

    <dependency>
      <groupId>jakarta.xml.bind</groupId>
      <artifactId>jakarta.xml.bind-api</artifactId>
      <version>2.3.3</version>
    </dependency>
    <dependency>
      <groupId>com.sun.xml.bind</groupId>
      <artifactId>jaxb-impl</artifactId>
      <version>2.3.3</version>
      <scope>runtime</scope>
    </dependency>
    

    Jakarta EE 9 update (Nov 2020)

    Use latest release of Eclipse Implementation of JAXB 3.0.0:

    <dependency>
      <groupId>jakarta.xml.bind</groupId>
      <artifactId>jakarta.xml.bind-api</artifactId>
      <version>3.0.0</version>
    </dependency>
    <dependency>
      <groupId>com.sun.xml.bind</groupId>
      <artifactId>jaxb-impl</artifactId>
      <version>3.0.0</version>
      <scope>runtime</scope>
    </dependency>
    

    Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

    javax.xml.bind -> jakarta.xml.bind
    

    Getting Python error "from: can't read /var/mail/Bio"

    Same here. I had this error when running an import command from terminal without activating python3 shell through manage.py in a django project (yes, I am a newbie yet). As one must expect, activating shell allowed the command to be interpreted correctly.

    ./manage.py shell
    

    and only then

    >>> from django.contrib.sites.models import Site
    

    Android EditText Hint

    I don't know whether a direct way of doing this is available or not, but you surely there is a workaround via code: listen for onFocus event of EditText, and as soon it gains focus, set the hint to be nothing with something like editText.setHint(""):

    This may not be exactly what you have to do, but it may be something like this-

    myEditText.setOnFocusListener(new OnFocusListener(){
      public void onFocus(){
        myEditText.setHint("");
      }
    });
    

    Jquery: how to sleep or delay?

    If you can't use the delay method as Robert Harvey suggested, you can use setTimeout.

    Eg.

    setTimeout(function() {$("#test").animate({"top":"-=80px"})} , 1500); // delays 1.5 sec
    setTimeout(function() {$("#test").animate({"opacity":"0"})} , 1500 + 1000); // delays 1 sec after the previous one
    

    Excel - Combine multiple columns into one column

    Try this. Click anywhere in your range of data and then use this macro:

    Sub CombineColumns()
    Dim rng As Range
    Dim iCol As Integer
    Dim lastCell As Integer
    
    Set rng = ActiveCell.CurrentRegion
    lastCell = rng.Columns(1).Rows.Count + 1
    
    For iCol = 2 To rng.Columns.Count
        Range(Cells(1, iCol), Cells(rng.Columns(iCol).Rows.Count, iCol)).Cut
        ActiveSheet.Paste Destination:=Cells(lastCell, 1)
        lastCell = lastCell + rng.Columns(iCol).Rows.Count
    Next iCol
    End Sub
    

    How to wait for the 'end' of 'resize' event and only then perform an action?

    There is an elegant solution using the Underscore.js So, if you are using it in your project you can do the following -

    $( window ).resize( _.debounce( resizedw, 500 ) );
    

    This should be enough :) But, If you are interested to read more on that, you can check my blog post - http://rifatnabi.com/post/detect-end-of-jquery-resize-event-using-underscore-debounce(deadlink)

    How can I scroll to a specific location on the page using jquery?

    <div id="idVal">
        <!--div content goes here-->
    </div>
    ...
    <script type="text/javascript">
         $(document).ready(function(){
             var divLoc = $('#idVal').offset();
             $('html, body').animate({scrollTop: divLoc.top}, "slow");
         });
    </script>
    

    This example shows to locate to a particular div id i.e, 'idVal' in this case. If you have subsequent divs/tables that will open up in this page via ajax, then you can assign unique divs and call the script to scroll to the particular location for each contents of divs.

    Hope this will be useful.

    How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

    No need to promise with $http, i use it just with two returns :

     myApp.service('dataService', function($http) {
       this.getData = function() {
          return $http({
              method: 'GET',
              url: 'https://www.example.com/api/v1/page',
              params: 'limit=10, sort_by=created:desc',
              headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
          }).success(function(data){
            return data;
          }).error(function(){
             alert("error");
             return null ;
          });
       }
     });
    

    In controller

     myApp.controller('AngularJSCtrl', function($scope, dataService) {
         $scope.data = null;
         dataService.getData().then(function(response) {
             $scope.data = response;
         });
     }); 
    

    Spring Data JPA findOne() change to Optional how to use this?

    The method has been renamed to findById(…) returning an Optional so that you have to handle absence yourself:

    Optional<Foo> result = repository.findById(…);
    
    result.ifPresent(it -> …); // do something with the value if present
    result.map(it -> …); // map the value if present
    Foo foo = result.orElse(null); // if you want to continue just like before
    

    Internal vs. Private Access Modifiers

    private - encapsulations in class/scope/struct ect'.

    internal - encapsulation in assemblies.

    How do I check to see if my array includes an object?

    #include? should work, it works for general objects, not only strings. Your problem in example code is this test:

    unless @suggested_horses.exists?(horse.id)
      @suggested_horses<< horse
    end
    

    (even assuming using #include?). You try to search for specific object, not for id. So it should be like this:

    unless @suggested_horses.include?(horse)
      @suggested_horses << horse
    end
    

    ActiveRecord has redefined comparision operator for objects to take a look only for its state (new/created) and id

    Compare two objects' properties to find differences?

    Sure you can with reflection. Here is the code to grab the properties off of a given type.

    var info = typeof(SomeType).GetProperties();
    

    If you can give more info on what you're comparing about the properties we can get together a basic diffing algorithmn. This code for intstance will diff on names

    public bool AreDifferent(Type t1, Type t2) {
      var list1 = t1.GetProperties().OrderBy(x => x.Name).Select(x => x.Name);
      var list2 = t2.GetProperties().OrderBy(x => x.Name).Select(x => x.Name);
      return list1.SequenceEqual(list2);
    }
    

    Sort an Array by keys based on another Array?

    function sortArrayByArray(array $toSort, array $sortByValuesAsKeys)
    {
        $commonKeysInOrder = array_intersect_key(array_flip($sortByValuesAsKeys), $toSort);
        $commonKeysWithValue = array_intersect_key($toSort, $commonKeysInOrder);
        $sorted = array_merge($commonKeysInOrder, $commonKeysWithValue);
        return $sorted;
    }
    

    Check difference in seconds between two times

    DateTime has a Subtract method and an overloaded - operator for just such an occasion:

    DateTime now = DateTime.UtcNow;
    TimeSpan difference = now.Subtract(otherTime); // could also write `now - otherTime`
    if (difference.TotalSeconds > 5) { ... }
    

    How to search for rows containing a substring?

    Well, you can always try WHERE textcolumn LIKE "%SUBSTRING%" - but this is guaranteed to be pretty slow, as your query can't do an index match because you are looking for characters on the left side.

    It depends on the field type - a textarea usually won't be saved as VARCHAR, but rather as (a kind of) TEXT field, so you can use the MATCH AGAINST operator.

    To get the columns that don't match, simply put a NOT in front of the like: WHERE textcolumn NOT LIKE "%SUBSTRING%".

    Whether the search is case-sensitive or not depends on how you stock the data, especially what COLLATION you use. By default, the search will be case-insensitive.

    Updated answer to reflect question update:

    I say that doing a WHERE field LIKE "%value%" is slower than WHERE field LIKE "value%" if the column field has an index, but this is still considerably faster than getting all values and having your application filter. Both scenario's:

    1/ If you do SELECT field FROM table WHERE field LIKE "%value%", MySQL will scan the entire table, and only send the fields containing "value".

    2/ If you do SELECT field FROM table and then have your application (in your case PHP) filter only the rows with "value" in it, MySQL will also scan the entire table, but send all the fields to PHP, which then has to do additional work. This is much slower than case #1.

    Solution: Please do use the WHERE clause, and use EXPLAIN to see the performance.

    How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

    You can just create a folder ProgramFiles at local D or local C to install those apps that can be install to a folder name which has a SPACES / Characters on it.

    Overwriting txt file in java

    SOLVED

    My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.

    File fold = new File("../playlist/" + existingPlaylist.getText() + ".txt");
    fold.delete();
    
    File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
    
    String source = textArea.getText();
    System.out.println(source);
    
    try {
        FileWriter f2 = new FileWriter(fnew, false);
        f2.write(source);
        f2.close();
    
    } catch (IOException e) {
        e.printStackTrace();
    }   
    

    REST API - Use the "Accept: application/json" HTTP Header

    You guessed right, HTTP Headers are not part of the URL.

    And when you type a URL in the browser the request will be issued with standard headers. Anyway REST Apis are not meant to be consumed by typing the endpoint in the address bar of a browser.

    The most common scenario is that your server consumes a third party REST Api.

    To do so your server-side code forges a proper GET (/PUT/POST/DELETE) request pointing to a given endpoint (URL) setting (when needed, like your case) some headers and finally (maybe) sending some data (as typically occurrs in a POST request for example).

    The code to forge the request, send it and finally get the response back depends on your server side language.

    If you want to test a REST Api you may use curl tool from the command line.

    curl makes a request and outputs the response to stdout (unless otherwise instructed).

    In your case the test request would be issued like this:

    $curl -H "Accept: application/json" 'http://localhost:8080/otp/routers/default/plan?fromPlace=52.5895,13.2836&toPlace=52.5461,13.3588&date=2017/04/04&time=12:00:00'
    

    The H or --header directive sets a header and its value.

    Facebook database design?

    It's most likely a many to many relationship:

    FriendList (table)

    user_id -> users.user_id
    friend_id -> users.user_id
    friendVisibilityLevel
    

    EDIT

    The user table probably doesn't have user_email as a PK, possibly as a unique key though.

    users (table)

    user_id PK
    user_email
    password
    

    How to input automatically when running a shell over SSH?

    Also you can pipe the answers to the script:

    printf "y\npassword\n" | sh test.sh
    

    where \n is escape-sequence

    How to calculate the number of occurrence of a given character in each row of a column of strings?

    s <- "aababacababaaathhhhhslsls jsjsjjsaa ghhaalll"
    p <- "a"
    s2 <- gsub(p,"",s)
    numOcc <- nchar(s) - nchar(s2)
    

    May not be the efficient one but solve my purpose.

    Angular 4 - Select default value in dropdown [Reactive Forms]

    You have to create a new property (ex:selectedCountry) and should use it in [(ngModel)] and further in component file assign default value to it.

    In your_component_file.ts

    this.selectedCountry = default;
    

    In your_component_template.html

    <select id="country" formControlName="country" [(ngModel)]="selectedCountry">
     <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
    </select> 
    

    Plunker link

    How to convert an Array to a Set in Java

    Set<T> b = new HashSet<>(Arrays.asList(requiredArray));
    

    Initialize a string variable in Python: "" or None?

    Either is fine, though None is more common as a convention - None indicates that no value was passed for the optional parameter.

    There will be times when "" is the correct default value to use - in my experience, those times occur less often.

    How can I create 2 separate log files with one log4j config file?

    Try the following configuration:

    log4j.rootLogger=TRACE, stdout
    
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
    
    log4j.appender.debugLog=org.apache.log4j.FileAppender
    log4j.appender.debugLog.File=logs/debug.log
    log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
    log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
    
    log4j.appender.reportsLog=org.apache.log4j.FileAppender
    log4j.appender.reportsLog.File=logs/reports.log
    log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
    log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
    
    log4j.category.debugLogger=TRACE, debugLog
    log4j.additivity.debugLogger=false
    
    log4j.category.reportsLogger=DEBUG, reportsLog
    log4j.additivity.reportsLogger=false
    

    Then configure the loggers in the Java code accordingly:

    static final Logger debugLog = Logger.getLogger("debugLogger");
    static final Logger resultLog = Logger.getLogger("reportsLogger");
    

    Do you want output to go to stdout? If not, change the first line of log4j.properties to:

    log4j.rootLogger=OFF
    

    and get rid of the stdout lines.

    Right way to write JSON deserializer in Spring or extend it

    With Spring MVC 4.2.1.RELEASE, you need to use the new Jackson2 dependencies as below for the Deserializer to work.

    Dont use this

    <dependency>  
                <groupId>org.codehaus.jackson</groupId>  
                <artifactId>jackson-mapper-asl</artifactId>  
                <version>1.9.12</version>  
            </dependency>  
    

    Use this instead.

    <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>2.2.2</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>2.2.2</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.2.2</version>
            </dependency>  
    

    Also use com.fasterxml.jackson.databind.JsonDeserializer and com.fasterxml.jackson.databind.annotation.JsonDeserialize for the deserialization and not the classes from org.codehaus.jackson

    How can I change the app display name build with Flutter?

    You can change it in iOS without opening Xcode by editing file *project/ios/Runner/info.plist. Set <key>CFBundleDisplayName</key> to the string that you want as your name.

    For Android, change the app name from the Android folder, in the AndroidManifest.xml file, android/app/src/main. Let the android label refer to the name you prefer, for example,

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        <application
            android:label="test"
            // The rest of the code
        </application>
    </manifest>
    

    How to input matrix (2D list) in Python?

    You can make any dimension of list

    list=[]
    n= int(input())
    for i in range(0,n) :
        #num = input()
        list.append(input().split())
    print(list)
    

    output:

    code in shown with output

    How to align matching values in two columns in Excel, and bring along associated values in other columns

    assuming the item numbers are unique, a VLOOKUP should get you the information you need.

    first value would be =VLOOKUP(E1,A:B,2,FALSE), and the same type of formula to retrieve the second value would be =VLOOKUP(E1,C:D,2,FALSE). Wrap them in an IFERROR if you want to return anything other than #N/A if there is no corresponding value in the item column(s)

    How to display the function, procedure, triggers source code in postgresql?

    Here are few examples from PostgreSQL-9.5

    Display list:

    1. Functions: \df+
    2. Triggers : \dy+

    Display Definition:

    postgres=# \sf
    function name is required
    
    postgres=# \sf pg_reload_conf()
    CREATE OR REPLACE FUNCTION pg_catalog.pg_reload_conf()
     RETURNS boolean
     LANGUAGE internal
     STRICT
    AS $function$pg_reload_conf$function$
    
    postgres=# \sf pg_encoding_to_char
    CREATE OR REPLACE FUNCTION pg_catalog.pg_encoding_to_char(integer)
     RETURNS name
     LANGUAGE internal
     STABLE STRICT
    AS $function$PG_encoding_to_char$function$
    

    Create ArrayList from array

    There is one more way that you can use to convert the array into an ArrayList. You can iterate over the array and insert each index into the ArrayList and return it back as in ArrayList.

    This is shown below.

    public static void main(String[] args) {
            String[] array = {new String("David"), new String("John"), new String("Mike")};
    
            ArrayList<String> theArrayList = convertToArrayList(array);
        }
    
        private static ArrayList<String> convertToArrayList(String[] array) {
            ArrayList<String> convertedArray = new ArrayList<String>();
    
            for (String element : array) {
                convertedArray.add(element);
            }
    
            return convertedArray;
        }
    

    file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

    There was a problem once in ruby where files in windows needed an "fsync" to actually be able to turn around and re-read the file after writing it and closing it. Maybe this is a similar manifestation (and if so, I think a windows bug, really).

    How do I auto-resize an image to fit a 'div' container?

    Currently there is no way to do this correctly in a deterministic way, with fixed-size images such as JPEGs or PNG files.

    To resize an image proportionally, you have to set either the height or width to "100%", but not both. If you set both to "100%", your image will be stretched.

    Choosing whether to do height or width depends on your image and container dimensions:

    1. If your image and container are both "portrait shaped" or both "landscape shaped" (taller than they are wide, or wider than they are tall, respectively), then it doesn't matter which of height or width are "%100".
    2. If your image is portrait, and your container is landscape, you must set height="100%" on the image.
    3. If your image is landscape, and your container is portrait, you must set width="100%" on the image.

    If your image is an SVG, which is a variable-sized vector image format, you can have the expansion to fit the container happen automatically.

    You just have to ensure that the SVG file has none of these properties set in the <svg> tag:

    height
    width
    viewbox
    

    Most vector drawing programs out there will set these properties when exporting an SVG file, so you will have to manually edit your file every time you export, or write a script to do it.

    Easiest way to develop simple GUI in Python

    Take your pick here.

    Tkinter is in the Python stdlib.

    SASS :not selector

    I tried re-creating this, and .someclass.notip was being generated for me but .someclass:not(.notip) was not, for as long as I did not have the @mixin tip() defined. Once I had that, it all worked.

    http://sassmeister.com/gist/9775949

    $dropdown-width: 100px;
    $comp-tip: true;
    
    @mixin tip($pos:right) {
    
    }
    
    @mixin dropdown-pos($pos:right) {
      &:not(.notip) {
        @if $comp-tip == true{
          @if $pos == right {
            top:$dropdown-width * -0.6;
            background-color: #f00;
            @include tip($pos:$pos);
          }
        }
      }
      &.notip {
        @if $pos == right {
          top: 0;
          left:$dropdown-width * 0.8;
          background-color: #00f;
        }
      }
    }
    
    .someclass { @include dropdown-pos(); }
    

    EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'. it what I get when I remove @mixin tip($pos:right) { }

    How do I test a private function or a class that has private methods, fields or inner classes?

    Having tried Cem Catikkas' solution using reflection for Java, I'd have to say his was a more elegant solution than I have described here. However, if you're looking for an alternative to using reflection, and have access to the source you're testing, this will still be an option.

    There is possible merit in testing private methods of a class, particularly with test-driven development, where you would like to design small tests before you write any code.

    Creating a test with access to private members and methods can test areas of code which are difficult to target specifically with access only to public methods. If a public method has several steps involved, it can consist of several private methods, which can then be tested individually.

    Advantages:

    • Can test to a finer granularity

    Disadvantages:

    • Test code must reside in the same file as source code, which can be more difficult to maintain
    • Similarly with .class output files, they must remain within the same package as declared in source code

    However, if continuous testing requires this method, it may be a signal that the private methods should be extracted, which could be tested in the traditional, public way.

    Here is a convoluted example of how this would work:

    // Import statements and package declarations
    
    public class ClassToTest
    {
        private int decrement(int toDecrement) {
            toDecrement--;
            return toDecrement;
        }
    
        // Constructor and the rest of the class
    
        public static class StaticInnerTest extends TestCase
        {
            public StaticInnerTest(){
                super();
            }
    
            public void testDecrement(){
                int number = 10;
                ClassToTest toTest= new ClassToTest();
                int decremented = toTest.decrement(number);
                assertEquals(9, decremented);
            }
    
            public static void main(String[] args) {
                junit.textui.TestRunner.run(StaticInnerTest.class);
            }
        }
    }
    

    The inner class would be compiled to ClassToTest$StaticInnerTest.

    See also: Java Tip 106: Static inner classes for fun and profit

    Why does the 'int' object is not callable error occur when using the sum() function?

    In the interpreter its easy to restart it and fix such problems. If you don't want to restart the interpreter, there is another way to fix it:

    Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
    [GCC 4.4.5] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> l = [1,2,3]
    >>> sum(l)
    6
    >>> sum = 0 # oops! shadowed a builtin!
    >>> sum(l)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'int' object is not callable
    >>> import sys
    >>> sum = sys.modules['__builtin__'].sum # -- fixing sum
    >>> sum(l)
    6
    

    This also comes in handy if you happened to assign a value to any other builtin, like dict or list

    C program to check little vs. big endian

    The following will do.

    unsigned int x = 1;
    printf ("%d", (int) (((char *)&x)[0]));
    

    And setting &x to char * will enable you to access the individual bytes of the integer, and the ordering of bytes will depend on the endianness of the system.

    In SQL how to compare date values?

    Uh, WHERE mydate<='2008-11-25' is the way to do it. That should work.

    Do you get an error message? Are you using an ancient version of MySQL?

    Edit: The following works fine for me on MySQL 5.x

    create temporary table foo(d datetime);
    insert into foo(d) VALUES ('2000-01-01');
    insert into foo(d) VALUES ('2001-01-01');
    select * from foo where d <= '2000-06-01';
    

    Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

    The window.navigator.platform property is not spoofed when the userAgent string is changed. I tested on my Mac if I change the userAgent to iPhone or Chrome Windows, navigator.platform remains MacIntel.

    navigator.platform is not spoofed when the userAgent string is changed

    The property is also read-only

    navigator.platform is read-only


    I could came up with the following table

    Mac Computers

    Mac68K Macintosh 68K system.
    MacPPC Macintosh PowerPC system.
    MacIntel Macintosh Intel system.

    iOS Devices

    iPhone iPhone.
    iPod iPod Touch.
    iPad iPad.


    Modern macs returns navigator.platform == "MacIntel" but to give some "future proof" don't use exact matching, hopefully they will change to something like MacARM or MacQuantum in future.

    var isMac = navigator.platform.toUpperCase().indexOf('MAC')>=0;
    

    To include iOS that also use the "left side"

    var isMacLike = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
    var isIOS = /(iPhone|iPod|iPad)/i.test(navigator.platform);
    

    _x000D_
    _x000D_
    var is_OSX = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
    var is_iOS = /(iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
    _x000D_
    var is_Mac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;_x000D_
    var is_iPhone = navigator.platform == "iPhone";_x000D_
    var is_iPod = navigator.platform == "iPod";_x000D_
    var is_iPad = navigator.platform == "iPad";_x000D_
    _x000D_
    /* Output */_x000D_
    var out = document.getElementById('out');_x000D_
    if (!is_OSX) out.innerHTML += "This NOT a Mac or an iOS Device!";_x000D_
    if (is_Mac) out.innerHTML += "This is a Mac Computer!\n";_x000D_
    if (is_iOS) out.innerHTML += "You're using an iOS Device!\n";_x000D_
    if (is_iPhone) out.innerHTML += "This is an iPhone!";_x000D_
    if (is_iPod) out.innerHTML += "This is an iPod Touch!";_x000D_
    if (is_iPad) out.innerHTML += "This is an iPad!";_x000D_
    out.innerHTML += "\nPlatform: " + navigator.platform;
    _x000D_
    <pre id="out"></pre>
    _x000D_
    _x000D_
    _x000D_


    Since most O.S. use the close button on the right, you can just move the close button to the left when the user is on a MacLike O.S., otherwise isn't a problem if you put it on the most common side, the right.

    _x000D_
    _x000D_
    setTimeout(test, 1000); //delay for demonstration_x000D_
    _x000D_
    function test() {_x000D_
    _x000D_
      var mac = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
    _x000D_
      if (mac) {_x000D_
        document.getElementById('close').classList.add("left");_x000D_
      }_x000D_
    }
    _x000D_
    #window {_x000D_
      position: absolute;_x000D_
      margin: 1em;_x000D_
      width: 300px;_x000D_
      padding: 10px;_x000D_
      border: 1px solid gray;_x000D_
      background-color: #DDD;_x000D_
      text-align: center;_x000D_
      box-shadow: 0px 1px 3px #000;_x000D_
    }_x000D_
    #close {_x000D_
      position: absolute;_x000D_
      top: 0px;_x000D_
      right: 0px;_x000D_
      width: 22px;_x000D_
      height: 22px;_x000D_
      margin: -12px;_x000D_
      box-shadow: 0px 1px 3px #000;_x000D_
      background-color: #000;_x000D_
      border: 2px solid #FFF;_x000D_
      border-radius: 22px;_x000D_
      color: #FFF;_x000D_
      text-align: center;_x000D_
      font: 14px"Comic Sans MS", Monaco;_x000D_
    }_x000D_
    #close.left{_x000D_
      left: 0px;_x000D_
    }
    _x000D_
    <div id="window">_x000D_
      <div id="close">x</div>_x000D_
      <p>Hello!</p>_x000D_
      <p>If the "close button" change to the left side</p>_x000D_
      <p>you're on a Mac like system!</p>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    http://www.nczonline.net/blog/2007/12/17/don-t-forget-navigator-platform/

    CSS Selector "(A or B) and C"?

    is there a better syntax?

    No. CSS' or operator (,) does not permit groupings. It's essentially the lowest-precedence logical operator in selectors, so you must use .a.c,.b.c.

    Window.Open with PDF stream instead of PDF location

    Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.

    if (data == "" || data == undefined) {
        alert("Falied to open PDF.");
    } else { //For IE using atob convert base64 encoded data to byte array
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            var byteCharacters = atob(data);
            var byteNumbers = new Array(byteCharacters.length);
            for (var i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            var byteArray = new Uint8Array(byteNumbers);
            var blob = new Blob([byteArray], {
                type: 'application/pdf'
            });
            window.navigator.msSaveOrOpenBlob(blob, fileName);
        } else { // Directly use base 64 encoded data for rest browsers (not IE)
            var base64EncodedPDF = data;
            var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
            window.open(dataURI, '_blank');
        }
    
    }
    

    What is the Swift equivalent of respondsToSelector?

    Functions are first-class types in Swift, so you can check whether an optional function defined in a protocol has been implemented by comparing it to nil:

    if (someObject.someMethod != nil) {
        someObject.someMethod!(someArgument)
    } else {
        // do something else
    }
    

    jQuery: How to get the HTTP status code from within the $.ajax.error method?

    You should create a map of actions using the statusCode setting:

    $.ajax({
      statusCode: {
        400: function() {
          alert('400 status code! user error');
        },
        500: function() {
          alert('500 status code! server error');
        }
      }
    });
    

    Reference (Scroll to: 'statusCode')

    EDIT (In response to comments)

    If you need to take action based on the data returned in the response body (which seems odd to me), you will need to use error: instead of statusCode:

    error:function (xhr, ajaxOptions, thrownError){
        switch (xhr.status) {
            case 404:
                 // Take action, referencing xhr.responseText as needed.
        }
    } 
    

    How to specify the default error page in web.xml?

    You can also do something like that:

    <error-page>
        <error-code>403</error-code>
        <location>/403.html</location>
    </error-page>
    
    <error-page>
        <location>/error.html</location>
    </error-page>
    

    For error code 403 it will return the page 403.html, and for any other error code it will return the page error.html.

    How to Write text file Java

    It does work with me. Make sure that you append ".txt" next to timeLog. I used it in a simple program opened with Netbeans and it writes the program in the main folder (where builder and src folders are).

    How to delete projects in Intellij IDEA 14?

    You will have to manually delete from the project explorer (your local machine hard drive), then delete the project in IntelliJ when it asks to re-open recent projects.

    flutter remove back button on appbar

      appBar: new AppBar(title: new Text("SmartDocs SPAY"),backgroundColor: Colors.blueAccent, automaticallyImplyLeading:false,
            leading: new Container(),
          ),
    

    It is working Fine

    How can I clear event subscriptions in C#?

    The best practice to clear all subscribers is to set the someEvent to null by adding another public method if you want to expose this functionality to outside. This has no unseen consequences. The precondition is to remember to declare SomeEvent with the keyword 'event'.

    Please see the book - C# 4.0 in the nutshell, page 125.

    Some one here proposed to use Delegate.RemoveAll method. If you use it, the sample code could follow the below form. But it is really stupid. Why not just SomeEvent=null inside the ClearSubscribers() function?

    public void ClearSubscribers ()
    {
       SomeEvent = (EventHandler) Delegate.RemoveAll(SomeEvent, SomeEvent);
       // Then you will find SomeEvent is set to null.
    }
    

    How to list running screen sessions?

     For windows system
    
     Open putty 
     then login in server
    

    If you want to see screen in Console then you have to write command

     Screen -ls
    

    if you have to access the screen then you have to use below command

     screen -x screen id
    

    Write PWD in command line to check at which folder you are currently

    Best method for reading newline delimited files and discarding the newlines?

    Just use generator expressions:

    blahblah = (l.rstrip() for l in open(filename))
    for x in blahblah:
        print x
    

    Also I want to advise you against reading whole file in memory -- looping over generators is much more efficient on big datasets.

    Sort a list by multiple attributes?

    It appears you could use a list instead of a tuple. This becomes more important I think when you are grabbing attributes instead of 'magic indexes' of a list/tuple.

    In my case I wanted to sort by multiple attributes of a class, where the incoming keys were strings. I needed different sorting in different places, and I wanted a common default sort for the parent class that clients were interacting with; only having to override the 'sorting keys' when I really 'needed to', but also in a way that I could store them as lists that the class could share

    So first I defined a helper method

    def attr_sort(self, attrs=['someAttributeString']:
      '''helper to sort by the attributes named by strings of attrs in order'''
      return lambda k: [ getattr(k, attr) for attr in attrs ]
    

    then to use it

    # would defined elsewhere but showing here for consiseness
    self.SortListA = ['attrA', 'attrB']
    self.SortListB = ['attrC', 'attrA']
    records = .... #list of my objects to sort
    records.sort(key=self.attr_sort(attrs=self.SortListA))
    # perhaps later nearby or in another function
    more_records = .... #another list
    more_records.sort(key=self.attr_sort(attrs=self.SortListB))
    

    This will use the generated lambda function sort the list by object.attrA and then object.attrB assuming object has a getter corresponding to the string names provided. And the second case would sort by object.attrC then object.attrA.

    This also allows you to potentially expose outward sorting choices to be shared alike by a consumer, a unit test, or for them to perhaps tell you how they want sorting done for some operation in your api by only have to give you a list and not coupling them to your back end implementation.

    How can I get the order ID in WooCommerce?

    This is quite an old question now, but someone may come here looking for an answer:

    echo $order->id;
    

    This should return the order id without "#".

    EDIT (feb/2018)

    The current way of accomplishing this is by using:

    $order->get_id();
    

    Oracle DB : java.sql.SQLException: Closed Connection

    You have to validate the connection.

    If you use Oracle it is likely that you use Oracle´s Universal Connection Pool. The following assumes that you do so.

    The easiest way to validate the connection is to tell Oracle that the connection must be validated while borrowing it. This can be done with

    pool.setValidateConnectionOnBorrow(true);
    

    But it works only if you hold the connection for a short period. If you borrow the connection for a longer time, it is likely that the connection gets broken while you hold it. In that case you have to validate the connection explicitly with

    if (connection == null || !((ValidConnection) connection).isValid())
    

    See the Oracle documentation for further details.

    Close iOS Keyboard by touching anywhere using Swift

    I got you fam

    override func viewDidLoad() {
        super.viewDidLoad() /*This ensures that our view loaded*/
        self.textField.delegate = self /*we select our text field that we want*/   
        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("dismissKeyboard")))
    }
    
    func dismissKeyboard(){ /*this is a void function*/
        textField.resignFirstResponder() /*This will dismiss our keyboard on tap*/
    }
    

    What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

    The big thing to get your head around is that the File class tries to represent a view of what Sun like to call "hierarchical pathnames" (basically a path like c:/foo.txt or /usr/muggins). This is why you create files in terms of paths. The operations you are describing are all operations upon this "pathname".

    • getPath() fetches the path that the File was created with (../foo.txt)
    • getAbsolutePath() fetches the path that the File was created with, but includes information about the current directory if the path is relative (/usr/bobstuff/../foo.txt)
    • getCanonicalPath() attempts to fetch a unique representation of the absolute path to the file. This eliminates indirection from ".." and "." references (/usr/foo.txt).

    Note I say attempts - in forming a Canonical Path, the VM can throw an IOException. This usually occurs because it is performing some filesystem operations, any one of which could fail.

    What's the pythonic way to use getters and setters?

    Properties are pretty useful since you can use them with assignment but then can include validation as well. You can see this code where you use the decorator @property and also @<property_name>.setter to create the methods:

    # Python program displaying the use of @property 
    class AgeSet:
        def __init__(self):
            self._age = 0
    
        # using property decorator a getter function
        @property
        def age(self):
            print("getter method called")
            return self._age
    
        # a setter function
        @age.setter
        def age(self, a):
            if(a < 18):
                raise ValueError("Sorry your age is below eligibility criteria")
            print("setter method called")
            self._age = a
    
    pkj = AgeSet()
    
    pkj.age = int(input("set the age using setter: "))
    
    print(pkj.age)
    

    There are more details in this post I wrote about this as well: https://pythonhowtoprogram.com/how-to-create-getter-setter-class-properties-in-python-3/

    Page redirect with successful Ajax request

    In your mail3.php file you should trap errors in a try {} catch {}

    try {
        /*code here for email*/
    } catch (Exception $e) {
        header('HTTP/1.1 500 Internal Server Error');
    }
    

    Then in your success call you wont have to worry about your errors, because it will never return as a success.

    and you can use: window.location.href = "thankyou.php"; inside your success function like Nick stated.

    How can I resolve the error: "The command [...] exited with code 1"?

    This builds on the answer from JaredPar... and is for VS2017. The same "Build and Run" options are present in Visual Studio 2017.

    I was getting, The command "chmod +x """ exited with code 1

    In the build output window, I searched for "Error" and found a few errors in the same general area. I was able to click on a link in the build output, and found that the error involved this entry in the .targets file:

      <Target Name="ChmodChromeDriver" BeforeTargets="BeforeBuild" Condition="'$(WebDriverPlatform)' != 'win32'">
        <Exec Command="chmod +x &quot;$(ChromeDriverSrcPath)&quot;" />
      </Target>
    

    In the build output, I also found a more detailed error message that essentially stated that it couldn't find Selenium.WebDriver.ChromeDriver v2.36 in the packages folder it was looking in. I checked the project's NuGet packages, and version 2.36 was indeed in the list of installed packages. I did find the package files for 2.36, and changed the attributes on the folder, subfolders and files from "Read Only" to "Read/Write". Built, but same failure. Sometimes "updating" to a different version of the package and then updating back to the original can fix this type of error. So I "updated" the reference in Manage NuGet packages to 2.37, built, failed, then "updated" back to 2.36, built, and the build succeeded without the "chmod +x" error message.

    The project I was building was based on a Visual Studio Project template for Appium test tooling, template name "Develop_Automated_Test".

    Is there an SQLite equivalent to MySQL's DESCRIBE [table]?

    The SQLite command line utility has a .schema TABLENAME command that shows you the create statements.

    Current time in microseconds in java

    tl;dr

    Java 9 and later: Up to nanoseconds resolution when capturing the current moment. That’s 9 digits of decimal fraction.

    Instant.now()   
    

    2017-12-23T12:34:56.123456789Z

    To limit to microseconds, truncate.

    Instant                // Represent a moment in UTC. 
    .now()                 // Capture the current moment. Returns a `Instant` object. 
    .truncatedTo(          // Lop off the finer part of this moment. 
        ChronoUnit.MICROS  // Granularity to which we are truncating. 
    )                      // Returns another `Instant` object rather than changing the original, per the immutable objects pattern. 
    

    2017-12-23T12:34:56.123456Z

    In practice, you will see only microseconds captured with .now as contemporary conventional computer hardware clocks are not accurate in nanoseconds.

    Details

    The other Answers are somewhat outdated as of Java 8.

    java.time

    Java 8 and later comes with the java.time framework. These new classes supplant the flawed troublesome date-time classes shipped with the earliest versions of Java such as java.util.Date/.Calendar and java.text.SimpleDateFormat. The framework is defined by JSR 310, inspired by Joda-Time, extended by the ThreeTen-Extra project.

    The classes in java.time resolve to nanoseconds, much finer than the milliseconds used by both the old date-time classes and by Joda-Time. And finer than the microseconds asked in the Question.

    enter image description here

    Clock Implementation

    While the java.time classes support data representing values in nanoseconds, the classes do not yet generate values in nanoseconds. The now() methods use the same old clock implementation as the old date-time classes, System.currentTimeMillis(). We have the new Clock interface in java.time but the implementation for that interface is the same old milliseconds clock.

    So you could format the textual representation of the result of ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ) to see nine digits of a fractional second but only the first three digits will have numbers like this:

    2017-12-23T12:34:56.789000000Z

    New Clock In Java 9

    The OpenJDK and Oracle implementations of Java 9 have a new default Clock implementation with finer granularity, up to the full nanosecond capability of the java.time classes.

    See the OpenJDK issue, Increase the precision of the implementation of java.time.Clock.systemUTC(). That issue has been successfully implemented.

    2017-12-23T12:34:56.123456789Z

    On a MacBook Pro (Retina, 15-inch, Late 2013) with macOS Sierra, I get the current moment in microseconds (up to six digits of decimal fraction).

    2017-12-23T12:34:56.123456Z

    Hardware Clock

    Remember that even with a new finer Clock implementation, your results may vary by computer. Java depends on the underlying computer hardware’s clock to know the current moment.

    • The resolution of the hardware clocks vary widely. For example, if a particular computer’s hardware clock supports only microseconds granularity, any generated date-time values will have only six digits of fractional second with the last three digits being zeros.
    • The accuracy of the hardware clocks vary widely. Just because a clock generates a value with several digits of decimal fraction of a second, those digits may be inaccurate, just approximations, adrift from actual time as might be read from an atomic clock. In other words, just because you see a bunch of digits to the right of the decimal mark does not mean you can trust the elapsed time between such readings to be true to that minute degree.

    Handle Button click inside a row in RecyclerView

    I wanted a solution that did not create any extra objects (ie listeners) that would have to be garbage collected later, and did not require nesting a view holder inside an adapter class.

    In the ViewHolder class

    private static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    
            private final TextView ....// declare the fields in your view
            private ClickHandler ClickHandler;
    
            public MyHolder(final View itemView) {
                super(itemView);
                nameField = (TextView) itemView.findViewById(R.id.name);
                //find other fields here...
                Button myButton = (Button) itemView.findViewById(R.id.my_button);
                myButton.setOnClickListener(this);
            }
            ...
            @Override
            public void onClick(final View view) {
                if (clickHandler != null) {
                    clickHandler.onMyButtonClicked(getAdapterPosition());
                }
            }
    

    Points to note: the ClickHandler interface is defined, but not initialized here, so there is no assumption in the onClick method that it was ever initialized.

    The ClickHandler interface looks like this:

    private interface ClickHandler {
        void onMyButtonClicked(final int position);
    } 
    

    In the adapter, set an instance of 'ClickHandler' in the constructor, and override onBindViewHolder, to initialize `clickHandler' on the view holder:

    private class MyAdapter extends ...{
    
        private final ClickHandler clickHandler;
    
        public MyAdapter(final ClickHandler clickHandler) {
            super(...);
            this.clickHandler = clickHandler;
        }
    
        @Override
        public void onBindViewHolder(final MyViewHolder viewHolder, final int position) {
            super.onBindViewHolder(viewHolder, position);
            viewHolder.clickHandler = this.clickHandler;
        }
    

    Note: I know that viewHolder.clickHandler is potentially getting set multiple times with the exact same value, but this is cheaper than checking for null and branching, and there is no memory cost, just an extra instruction.

    Finally, when you create the adapter, you are forced to pass a ClickHandlerinstance to the constructor, as so:

    adapter = new MyAdapter(new ClickHandler() {
        @Override
        public void onMyButtonClicked(final int position) {
            final MyModel model = adapter.getItem(position);
            //do something with the model where the button was clicked
        }
    });
    

    Note that adapter is a member variable here, not a local variable

    Python Script execute commands in Terminal

    Jupyter

    In a jupyter notebook you can use the magic function !

    !echo "execute a command"
    files = !ls -a /data/dir/ #get the output into a variable
    

    ipython

    To execute this as a .py script you would need to use ipython

    files = get_ipython().getoutput('ls -a /data/dir/')
    

    execute script

    $ ipython my_script.py
    

    load csv into 2D matrix with numpy for plotting

    You can read a CSV file with headers into a NumPy structured array with np.genfromtxt. For example:

    import numpy as np
    
    csv_fname = 'file.csv'
    with open(csv_fname, 'w') as fp:
        fp.write("""\
    "A","B","C","D","E","F","timestamp"
    611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
    611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
    611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12
    """)
    
    # Read the CSV file into a Numpy record array
    r = np.genfromtxt(csv_fname, delimiter=',', names=True, case_sensitive=True)
    print(repr(r))
    

    which looks like this:

    array([(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111196e+12),
           (611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111311e+12),
           (611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29112065e+12)],
          dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ('D', '<f8'), ('E', '<f8'), ('F', '<f8'), ('timestamp', '<f8')])
    

    You can access a named column like this r['E']:

    array([1715.37476, 1715.37476, 1715.37476])
    

    Note: this answer previously used np.recfromcsv to read the data into a NumPy record array. While there was nothing wrong with that method, structured arrays are generally better than record arrays for speed and compatibility.

    How to create a file name with the current date & time in Python?

    This one is much more human readable.

    from datetime import datetime
    
    datetime.now().strftime("%Y_%m_%d-%I_%M_%S_%p")
    
    '2020_08_12-03_29_22_AM'
    

    auto run a bat script in windows 7 at login

    Just enable parsing of the autoexec.bat in the registry, using these instructions.

    :: works only on windows vista and earlier 
    Run REGEDT32.EXE.
    Modify the following value within HKEY_CURRENT_USER: 
    
    Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ParseAutoexec 
    
    1 = autoexec.bat is parsed
    0 = autoexec.bat is not parsed
    

    How to assign a value to a TensorFlow variable?

    So i had a adifferent case where i needed to assign values before running a session, So this was the easiest way to do that:

    other_variable = tf.get_variable("other_variable", dtype=tf.int32,
      initializer=tf.constant([23, 42]))
    

    here i'm creating a variable as well as assigning it values at the same time

    Remove Null Value from String array in java

    Using Google's guava library

    String[] firstArray = {"test1","","test2","test4","",null};
    
    Iterable<String> st=Iterables.filter(Arrays.asList(firstArray),new Predicate<String>() {
        @Override
        public boolean apply(String arg0) {
            if(arg0==null) //avoid null strings 
                return false;
            if(arg0.length()==0) //avoid empty strings 
                return false;
            return true; // else true
        }
    });
    

    How do I add an element to a list in Groovy?

    From the documentation:

    We can add to a list in many ways:

    assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
    assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
        //equivalent method for +
    def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
    assert [1, *[222, 333], 456] == [1, 222, 333, 456]
    assert [ *[1,2,3] ] == [1,2,3]
    assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    def list= [1,2]
    list.add(3) //alternative method name
    list.addAll([5,4]) //alternative method name
    assert list == [1,2,3,5,4]
    
    list= [1,2]
    list.add(1,3) //add 3 just before index 1
    assert list == [1,3,2]
    list.addAll(2,[5,4]) //add [5,4] just before index 2
    assert list == [1,3,5,4,2]
    
    list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
    list[8] = 'x'
    assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']
    

    You can also do:

    def myNewList = myList << "fifth"
    

    How to insert text in a td with id, using JavaScript

    Use jQuery

    Look how easy it would be if you did.

    Example:

    $('#td1').html('hello world');
    

    Adding system header search path to Xcode

    Follow up to Eonil's answer related to project level settings. With the target selected and the Build Settings tab selected, there may be no listing under Search Paths for Header Search Paths. In this case, you can change to "All" from "Basic" in the search bar and Header Search Paths will show up in the Search Paths section.

    Putty: Getting Server refused our key Error

    In my case it was caused by (/etc/ssh/sshd_config):

    PermitRootLogin no
    

    Changed to yes, restarted the service and got in normally.

    'adb' is not recognized as an internal or external command, operable program or batch file

    On Window, sometimes I feel hard to click through many steps to find platform-tools and open Environment Variables Prompt, so the below steps maybe help

    Step 1. Open cmd as Administrator

    Step 2. File platform-tools path

    cd C:\
    dir /s adb.exe
    

    Step 3: Edit Path in Edit Enviroment Variables Prompt

    rundll32 sysdm.cpl,EditEnvironmentVariables
    

    more, the command to open environment variables can not remember, so I often make an alias for it (eg: editenv), if you need to work with environment variables multiple time, you can use a permanent doskey to make alias

    Step 4: Restart cmd

    Changing Shell Text Color (Windows)

    Been looking into this for a while and not got any satisfactory answers, however...

    1) ANSI escape sequences do work in a terminal on Linux

    2) if you can tolerate a limited set of colo(u)rs try this:

    print("hello", end=''); print("error", end='', file=sys.stderr); print("goodbye")

    In idle "hello" and "goodbye" are in blue and "error" is in red.

    Not fantastic, but good enough for now, and easy!

    How to display a content in two-column layout in LaTeX?

    You can import a csv file to this website(https://www.tablesgenerator.com/latex_tables) and click copy to clipboard.

    How to split a string with angularJS

    You may want to wrap that functionality up into a filter, this way you don't have to put the mySplit function in all of your controllers. For example

    angular.module('myModule', [])
        .filter('split', function() {
            return function(input, splitChar, splitIndex) {
                // do some bounds checking here to ensure it has that index
                return input.split(splitChar)[splitIndex];
            }
        });
    

    From here, you can use a filter as you originally intended

    {{test | split:',':0}}
    {{test | split:',':0}}
    

    More info at http://docs.angularjs.org/guide/filter (thanks ross)

    Plunkr @ http://plnkr.co/edit/NA4UeL

    Combine or merge JSON on node.js without jQuery

    It can easy be done using Object.assign() method -

     var object1 = {name: "John"};
     var object2 = {location: "San Jose"};
     var object3 = Object.assign(object1,object2);
     console.log(object3);
    

    now object3 is { name: 'John', location: 'San Jose' }

    List of tuples to dictionary

    Just call dict() on the list of tuples directly

    >>> my_list = [('a', 1), ('b', 2)]
    >>> dict(my_list)
    {'a': 1, 'b': 2}
    

    Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

    Should work for any collection except Map, but it's easy to support, too. Modify code to pass these 3 chars as arguments if needed.

    static <T> String seqToString(Iterable<T> items) {
        StringBuilder sb = new StringBuilder();
        sb.append('[');
        boolean needSeparator = false;
        for (T x : items) {
            if (needSeparator)
                sb.append(' ');
            sb.append(x.toString());
            needSeparator = true;
        }
        sb.append(']');
        return sb.toString();
    }
    

    No Network Security Config specified, using platform default - Android Log

    I just had the same problem. It is not a network permission but rather thread issue. Below code helped me to solve it. Put is in main activity

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (android.os.Build.VERSION.SDK_INT > 9)
        {
            StrictMode.ThreadPolicy policy = new 
            StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
    

    How can I export data to an Excel file

    I used interop to open Excel and to modify the column widths once the data was done. If you use interop to spit the data into a new Excel workbook (if this is what you want), it will be terribly slow. Instead, I generated a .CSV, then opened the .CSV in Excel. This has its own problems, but I've found this the quickest method.

    First, convert the .CSV:

    // Convert array data into CSV format.
    // Modified from http://csharphelper.com/blog/2018/04/write-a-csv-file-from-an-array-in-c/.
    private string GetCSV(List<string> Headers, List<List<double>> Data)
    {
        // Get the bounds.
        var rows = Data[0].Count;
        var cols = Data.Count;
        var row = 0;
    
        // Convert the array into a CSV string.
        StringBuilder sb = new StringBuilder();
    
        // Add the first field in this row.
        sb.Append(Headers[0]);
    
        // Add the other fields in this row separated by commas.
        for (int col = 1; col < cols; col++)
            sb.Append("," + Headers[col]);
    
        // Move to the next line.
        sb.AppendLine();
    
        for (row = 0; row < rows; row++)
        {
            // Add the first field in this row.
            sb.Append(Data[0][row]);
    
            // Add the other fields in this row separated by commas.
            for (int col = 1; col < cols; col++)
                sb.Append("," + Data[col][row]);
    
            // Move to the next line.
            sb.AppendLine();
        }
    
        // Return the CSV format string.
        return sb.ToString();
    }
    

    Then, export it to Excel:

    public void ExportToExcel()
    {
        // Initialize app and pop Excel on the screen.
        var excelApp = new Excel.Application { Visible = true };
    
        // I use unix time to give the files a unique name that's almost somewhat useful.
        DateTime dateTime = DateTime.UtcNow;
        long unixTime = ((DateTimeOffset)dateTime).ToUnixTimeSeconds();
        var path = @"C:\Users\my\path\here + unixTime + ".csv";
    
        var csv = GetCSV();
        File.WriteAllText(path, csv);
    
        // Create a new workbook and get its active sheet.
        excelApp.Workbooks.Open(path);
    
        var workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
    
        // iterate over each value and throw it in the chart
        for (var column = 0; column < Data.Count; column++)
        {
            ((Excel.Range)workSheet.Columns[column + 1]).AutoFit();
        }
    
        currentSheet = workSheet;
    }
    

    You'll have to install some stuff, too...

    1. Right click on the solution from solution explorer and select "Manage NuGet Packages." - add Microsoft.Office.Interop.Excel

    2. It might actually work right now if you created the project the way interop wants you to. If it still doesn't work, I had to create a new project in a different category. Under New > Project, select Visual C# > Windows Desktop > Console App. Otherwise, the interop tools won't work.

    In case I forgot anything, here's my 'using' statements:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using Excel = Microsoft.Office.Interop.Excel;
    

    Getting the class of the element that fired an event using JQuery

    Careful as target might not work with all browsers, it works well with Chrome, but I reckon Firefox (or IE/Edge, can't remember) is a bit different and uses srcElement. I usually do something like

    var t = ev.srcElement || ev.target;
    

    thus leading to

    $(document).ready(function() {
        $("a").click(function(ev) {
            // get target depending on what API's in use
            var t = ev.srcElement || ev.target;
    
            alert(t.id+" and "+$(t).attr('class'));
        });
    });
    

    Thx for the nice answers!

    How do I check if a property exists on a dynamic anonymous type in c#?

    In case someone need to handle a dynamic object come from Json, I has modified Seth Reno answer to handle dynamic object deserialized from NewtonSoft.Json.JObjcet.

    public static bool PropertyExists(dynamic obj, string name)
        {
            if (obj == null) return false;
            if (obj is ExpandoObject)
                return ((IDictionary<string, object>)obj).ContainsKey(name);
            if (obj is IDictionary<string, object> dict1)
                return dict1.ContainsKey(name);
            if (obj is IDictionary<string, JToken> dict2)
                return dict2.ContainsKey(name);
            return obj.GetType().GetProperty(name) != null;
        }
    

    How to use export with Python on Linux

    You actually want to do

    import os
    os.environ["MY_DATA"] = "my_export"
    

    Visual Studio Code includePath

    A more current take on the situation. During 2018, the C++ extension added another option to the configuration compilerPath of the c_cpp_properties.json file;

    compilerPath (optional) The absolute path to the compiler you use to build your project. The extension will query the compiler to determine the system include paths and default defines to use for IntelliSense.

    If used, the includePath would not be needed since the IntelliSense will use the compiler to figure out the system include paths.


    Originally,

    How and where can I add include paths in the configurations below?

    The list is a string array, hence adding an include path would look something like;

    "configurations": [
        {
            "name": "Mac",
            "includePath": ["/usr/local/include",
                "/path/to/additional/includes",
                "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include"
            ]
        }
    ]
    

    Source; cpptools blog 31 March 2016.

    The linked source has a gif showing the format for the Win32 configuration, but the same applies to the others.

    The above sample includes the SDK (OSX 10.11) path if Xcode is installed.

    Note I find it can take a while to update once the include path has been changed.

    The cpptools extension can be found here.

    Further documentation (from Microsoft) on the C++ language support in VSCode can be found here.


    For the sake of preservation (from the discussion), the following are basic snippets for the contents of the tasks.json file to compile and execute either a C++ file, or a C file. They allow for spaces in the file name (requires escaping the additional quotes in the json using \"). The shell is used as the runner, thus allowing the compilation (clang...) and the execution (&& ./a.out) of the program. It also assumes that the tasks.json "lives" in the local workspace (under the directory .vscode). Further task.json details, such as supported variables etc. can be found here.

    For C++;

    { 
        "version": "0.1.0", 
        "isShellCommand": true, 
        "taskName": "GenericBuild", 
        "showOutput": "always", 
        "command": "sh", 
        "suppressTaskName": false, 
        "args": ["-c", "clang++ -std=c++14 -Wall -Wextra -pedantic -pthread \"${file}\" && ./a.out"]
    }
    

    For C;

    { 
        "version": "0.1.0", 
        "isShellCommand": true, 
        "taskName": "GenericBuild", 
        "showOutput": "always", 
        "command": "sh", 
        "suppressTaskName": false, 
        "args": ["-c", "clang -std=c11 -Wall -Wextra -pedantic -pthread \"${file}\" && ./a.out"] // command arguments... 
    }
    

    Add string in a certain position in Python

    Python 3.6+ using f-string:

    mys = '1362511338314'
    f"{mys[:10]}_{mys[10:]}"
    

    gives

    '1362511338_314'
    

    "ssl module in Python is not available" when installing package with pip3

    Downgrading openssl worked for me,

    brew switch openssl 1.0.2s
    

    Upgrade python without breaking yum

    I have written a quick guide on how to install the latest versions of Python 2 and Python 3 on CentOS 6 and CentOS 7. It currently covers Python 2.7.13 and Python 3.6.0:

    # Start by making sure your system is up-to-date:
    yum update
    # Compilers and related tools:
    yum groupinstall -y "development tools"
    # Libraries needed during compilation to enable all features of Python:
    yum install -y zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel expat-devel
    # If you are on a clean "minimal" install of CentOS you also need the wget tool:
    yum install -y wget
    

    The next steps depend on the version of Python you're installing.

    For Python 2.7.14:

    wget http://python.org/ftp/python/2.7.14/Python-2.7.14.tar.xz
    tar xf Python-2.7.14.tar.xz
    cd Python-2.7.14
    ./configure --prefix=/usr/local --enable-unicode=ucs4 --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
    make && make altinstall
    
    # Strip the Python 2.7 binary:
    strip /usr/local/lib/libpython2.7.so.1.0
    

    For Python 3.6.3:

    wget http://python.org/ftp/python/3.6.3/Python-3.6.3.tar.xz
    tar xf Python-3.6.3.tar.xz
    cd Python-3.6.3
    ./configure --prefix=/usr/local --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
    make && make altinstall
    
    # Strip the Python 3.6 binary:
    strip /usr/local/lib/libpython3.6m.so.1.0
    

    To install Pip:

    # First get the script:
    wget https://bootstrap.pypa.io/get-pip.py
    
    # Then execute it using Python 2.7 and/or Python 3.6:
    python2.7 get-pip.py
    python3.6 get-pip.py
    
    # With pip installed you can now do things like this:
    pip2.7 install [packagename]
    pip2.7 install --upgrade [packagename]
    pip2.7 uninstall [packagename]
    

    You are not supposed to change the system version of Python because it will break the system (as you found out). Installing other versions works fine as long as you leave the original system version alone. This can be accomplished by using a custom prefix (for example /usr/local) when running configure, and using make altinstall (instead of the normal make install) when installing your build of Python.

    Having multiple versions of Python available is usually not a big problem as long as you remember to type the full name including the version number (for example "python2.7" or "pip2.7"). If you do all your Python work from a virtualenv the versioning is handled for you, so make sure you install and use virtualenv!

    JS: Uncaught TypeError: object is not a function (onclick)

    I was able to figure it out by following the answer in this thread: https://stackoverflow.com/a/8968495/1543447

    Basically, I renamed all values, function names, and element names to different values so they wouldn't conflict - and it worked!

    How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

    My approach via group dialout to get every tty with user 'dialout' ls -l /dev/tty* | grep 'dialout' to only get its folder ls -l /dev/tty* | grep 'dialout' | rev | cut -d " " -f1 | rev

    easy listen to the tty output e.g. when arduino serial out: head --lines 1 < /dev/ttyUSB0

    listen to every tty out for one line only: for i in $(ls -l /dev/tty* | grep 'dialout' | rev | cut -d " " -f1 | rev); do head --lines 1 < $i; done

    I really like the approach via looking for drivers: ll /sys/class/tty/*/device/driver

    You can pick the tty-Name now: ls /sys/class/tty/*/device/driver | grep 'driver' | cut -d "/" -f 5

    SQL exclude a column using SELECT * [except columnA] FROM tableA?

    DECLARE @SQL VARCHAR(max), @TableName sysname = 'YourTableName'
    
    SELECT @SQL = COALESCE(@SQL + ', ', '') + Name 
    FROM sys.columns
    WHERE OBJECT_ID = OBJECT_ID(@TableName)
    AND name NOT IN ('Not This', 'Or that');
    
    SELECT @SQL = 'SELECT ' + @SQL + ' FROM ' + @TableName
    
    EXEC (@SQL)
    

    UPDATE:

    You can also create a stored procedure to take care of this task if you use it more often. In this example I have used the built in STRING_SPLIT() which is available on SQL Server 2016+, but if you need there are pleanty of examples of how to create it manually on SO.

    CREATE PROCEDURE [usp_select_without]
    @schema_name sysname = N'dbo',
    @table_name sysname,
    @list_of_columns_excluded nvarchar(max),
    @separator nchar(1) = N','
    AS
    BEGIN
     DECLARE 
     @SQL nvarchar(max),
     @full_table_name nvarchar(max) = CONCAT(@schema_name, N'.', @table_name);
    
     SELECT @SQL = COALESCE(@SQL + ', ', '') + QUOTENAME([Name])
     FROM sys.columns sc
     LEFT JOIN STRING_SPLIT(@list_of_columns_excluded, @separator) ss ON sc.[name] = ss.[value]
     WHERE sc.OBJECT_ID = OBJECT_ID(@full_table_name, N'u')
     AND ss.[value] IS NULL;
    
     SELECT @SQL = N'SELECT ' + @SQL + N' FROM ' + @full_table_name;
     EXEC(@SQL)
    END
    

    And then just:

    EXEC [usp_select_without] 
    @table_name = N'Test_Table',
    @list_of_columns_excluded = N'ID, Date, Name';
    

    Formatting DataBinder.Eval data

    <asp:Label ID="ServiceBeginDate" runat="server" Text='<%# (DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:yyyy}") == "0001") ? "" : DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:MM/dd/yyyy}") %>'>
    </asp:Label>
    

    How to obtain the start time and end time of a day?

    public static Date beginOfDay(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
    
        return cal.getTime();
    }
    
    public static Date endOfDay(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 999);
    
        return cal.getTime();
    }
    

    How do you get the current time of day?

    Get the current date and time, then just use the time portion of it. Look at the possibilities for formatting a date time string in the MSDN docs.

    Table 'performance_schema.session_variables' doesn't exist

    I was able to log on to the mysql server after running the command @robregonm suggested:

    mysql_upgrade -u root -p --force
    

    A MySQL server restart is required.

    Is there any way to show a countdown on the lockscreen of iphone?

    There is no way to display interactive elements on the lockscreen or wallpaper with a non jailbroken iPhone.

    I would recommend Countdown Widget it's free an you can display countdowns in the notification center which you can also access from your lockscreen.

    Ruby on Rails generates model field:type - what are the options for field:type?

    Remember to not capitalize your text when writing this command. For example:

    Do write:

    rails g model product title:string description:text image_url:string price:decimal
    

    Do not write:

    rails g Model product title:string description:text image_url:string price:decimal
    

    At least it was a problem to me.

    Changing .gitconfig location on Windows

    I have solved this problem using a slightly different approach that I have seen work for other configuration files. Git Config supports includes that allows you to point to a configuration file in another location. That alternate location is then imported and expanded in place as if it was part of .gitconfig file. So now I just have a single entry in .gitconfig:

    [include]
       path = c:\\path\\to\\my.config
    

    Any updates written by Git to the .gitconfig file will not overwrite my include path. It does mean that occasionally I may need to move values from .gitconfig to my.config.

    C# : "A first chance exception of type 'System.InvalidOperationException'"

    If you check Thrown for Common Language Runtime Exception in the break when an exception window (Ctrl+Alt+E in Visual Studio), then the execution should break while you are debugging when the exception is thrown.

    This will probably give you some insight into what is going on.

    Example of the exceptions window

    Simple prime number generator in Python

    def is_prime(num):
        """Returns True if the number is prime
        else False."""
        if num == 0 or num == 1:
            return False
        for x in range(2, num):
            if num % x == 0:
                return False
        else:
            return True
    
    >> filter(is_prime, range(1, 20))
      [2, 3, 5, 7, 11, 13, 17, 19]
    

    We will get all the prime numbers upto 20 in a list. I could have used Sieve of Eratosthenes but you said you want something very simple. ;)

    Mockito. Verify method arguments

    Verify(a).aFunc(eq(b))
    

    In pseudocode:

    When in the instance a - a function named aFunc is called.

    Verify this call got an argument which is equal to b.

    Declaring and initializing a string array in VB.NET

    I believe you need to specify "Option Infer On" for this to work.

    Option Infer allows the compiler to make a guess at what is being represented by your code, thus it will guess that {"stuff"} is an array of strings. With "Option Infer Off", {"stuff"} won't have any type assigned to it, ever, and so it will always fail, without a type specifier.

    Option Infer is, I think On by default in new projects, but Off by default when you migrate from earlier frameworks up to 3.5.

    Opinion incoming:

    Also, you mention that you've got "Option Explicit Off". Please don't do this.

    Setting "Option Explicit Off" means that you don't ever have to declare variables. This means that the following code will silently and invisibly create the variable "Y":

    Dim X as Integer
    Y = 3
    

    This is horrible, mad, and wrong. It creates variables when you make typos. I keep hoping that they'll remove it from the language.

    How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project

    You can also use Url.Action for the path instead like so:

    $.ajax({
            url: "@Url.Action("Holiday", "Calendar", new { area = "", year= (val * 1) + 1 })",                
            type: "GET",           
            success: function (partialViewResult) {            
                $("#refTable").html(partialViewResult);
            }
        });
    

    How to count instances of character in SQL Column

    In SQL Server:

    SELECT LEN(REPLACE(myColumn, 'N', '')) 
    FROM ...
    

    Using the Underscore module with Node.js

    The name _ used by the node.js REPL to hold the previous input. Choose another name.

    How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

    When I want to examine or change an import / export specification I query the tables in MS Access where the specification is defined.

    SELECT 
        MSysIMEXSpecs.SpecName,
        MSysIMexColumns.*
    FROM 
        MSysIMEXSpecs
        LEFT JOIN MSysIMEXColumns 
        ON MSysIMEXSpecs.SpecID = MSysIMEXColumns.SpecID
    WHERE
        SpecName = 'MySpecName'
    ORDER BY
        MSysIMEXSpecs.SpecID, MSysIMEXColumns.Start;
    

    You can also use an UPDATE or INSERT statement to alter existing columns or insert and append new columns to an existing specification. You can create entirely new specifications using this methodology.

    Failed to resolve: com.google.firebase:firebase-core:16.0.1

    If you receive an error stating the library cannot be found, check the Google maven repo for your library and version. I had a version suddenly disappear and make my builds fail.

    https://maven.google.com/web/index.html

    How to check if a symlink exists

    How about using readlink?

    # if symlink, readlink returns not empty string (the symlink target)
    # if string is not empty, test exits w/ 0 (normal)
    #
    # if non symlink, readlink returns empty string
    # if string is empty, test exits w/ 1 (error)
    simlink? () {
      test "$(readlink "${1}")";
    }
    
    FILE=/usr/mda
    
    if simlink? "${FILE}"; then
      echo $FILE is a symlink
    else
      echo $FILE is not a symlink
    fi