Programs & Examples On #Ui spy

The UI Spy tool enables developers and testers to view and interact with the user interface (UI) elements of an application. (http://msdn.microsoft.com/en-us/library/ms727247.aspx)

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

How to run Rake tasks from within Rake tasks?

task :invoke_another_task do
  # some code
  Rake::Task["another:task"].invoke
end

Why does AngularJS include an empty option in select?

Among the multitudes of answers here, I figured I'd repost the solution that worked for me and met all of the following conditions:

  • provided a placeholder/prompt when the ng-model is falsy (e.g. "--select region--" w. value="")
  • when ng-model value is falsy and user opens the options dropdown, the placeholder is selected (other solutions mentioned here make the first option appear selected which can be misleading)
  • allow the user to deselect a valid value, essentially selecting the falsy/default value again

enter image description here

code

<select name="market_vertical" ng-model="vc.viewData.market_vertical"
    ng-options="opt as (opt | capitalizeFirst) for opt in vc.adminData.regions">

    <option ng-selected="true" value="">select a market vertical</option>
</select>

src

original q&a - https://stackoverflow.com/a/32880941/1121919

How can I scale an entire web page with CSS?

If your CSS is constructed completely around ex or em units, then this might be possible and feasible. You'd just need to declare font-size: 150% in your style for body or html. This should cause every other lengths to scale proportionally. You can't scale images this way, though, unless they get a style too.

But that's a very big if on most sites, anyway.

Convert double to BigDecimal and set BigDecimal Precision

You want to try String.format("%f", d), which will print your double in decimal notation. Don't use BigDecimal at all.

Regarding the precision issue: You are first storing 47.48 in the double c, then making a new BigDecimal from that double. The loss of precision is in assigning to c. You could do

BigDecimal b = new BigDecimal("47.48")

to avoid losing any precision.

How can I show current location on a Google Map on Android Marshmallow?

Firstly make sure your API Key is valid and add this into your manifest <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Here's my maps activity.. there might be some redundant information in it since it's from a larger project I created.

import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {


    //These variable are initalized here as they need to be used in more than one methid
    private double currentLatitude; //lat of user
    private double currentLongitude; //long of user

    private double latitudeVillageApartmets= 53.385952001750184;
    private double longitudeVillageApartments= -6.599087119102478;


    public static final String TAG = MapsActivity.class.getSimpleName();

    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        setUpMapIfNeeded();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        // Create the LocationRequest object
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds
 }
    /*These methods all have to do with the map and wht happens if the activity is paused etc*/
    //contains lat and lon of another marker
    private void setUpMap() {

            MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
            mMap.addMarker(marker); // adding marker
    }

    //contains your lat and lon
    private void handleNewLocation(Location location) {
        Log.d(TAG, location.toString());

        currentLatitude = location.getLatitude();
        currentLongitude = location.getLongitude();

        LatLng latLng = new LatLng(currentLatitude, currentLongitude);

        MarkerOptions options = new MarkerOptions()
                .position(latLng)
                .title("You are here");
        mMap.addMarker(options);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom((latLng), 11.0F));
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }

        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
        else {
            handleNewLocation(location);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                /*
                 * Thrown if Google Play services canceled the original
                 * PendingIntent
                 */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        handleNewLocation(location);
    }

}

There's a lot of methods here that are hard to understand but basically all update the map when it's paused etc. There are also connection timeouts etc. Sorry for just posting this, I tried to fix your code but I couldn't figure out what was wrong.

Current date and time - Default in MVC razor

Isn't this what default constructors are for?

class MyModel
{

    public MyModel()
    {
        this.ReturnDate = DateTime.Now;
    }

    public date ReturnDate {get; set;};

}

replace special characters in a string python

One way is to use re.sub, that's my preferred way.

import re
my_str = "hey th~!ere"
my_new_string = re.sub('[^a-zA-Z0-9 \n\.]', '', my_str)
print my_new_string

Output:

hey there

Another way is to use re.escape:

import string
import re

my_str = "hey th~!ere"

chars = re.escape(string.punctuation)
print re.sub(r'['+chars+']', '',my_str)

Output:

hey there

Just a small tip about parameters style in python by PEP-8 parameters should be remove_special_chars and not removeSpecialChars

Also if you want to keep the spaces just change [^a-zA-Z0-9 \n\.] to [^a-zA-Z0-9\n\.]

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

I ran into a very similar problem with my Xamarin Windows Phone 8.1 app. The reason JObject.Parse(json) would not work for me was because my Json had a beginning "[" and an ending "]". In order to make it work, I had to remove those two characters. From your example, it looks like you might have the same issue.

jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });

I was then able to use the JObject.Parse(jsonResult) and everything worked.

Conda command is not recognized on Windows 10

If you want to use Anaconda in regular cmd on windows you need to add several paths to your Path env variable.

Those paths are (instead of Anaconda3 the folder may be Anaconda2 depending on the Anaconda version on your PC):

\Users\YOUR_USER\Anaconda3
\Users\YOUR_USER\Anaconda3\Library\mingw-w64\bin
\Users\YOUR_USER\Anaconda3\Library\usr\bin
\Users\YOUR_USER\Anaconda3\Library\bin
\Users\YOUR_USER\Anaconda3\Scripts
\Users\YOUR_USER\Anaconda3\bin

Appending a line break to an output file in a shell script

You can do that without an I/O redirection:

sed -i 's/$/\n/' filename

You can also use this command to append a newline to a list of files:

find dir -name filepattern | xargs sed -i 's/$/\n/' filename

For echo, some shells implement it as a shell builtin command. It might not accept the -e option. If you still want to use echo, try to find where the echo binary file is, using which echo. In most cases, it is located in /bin/echo, so you can use /bin/echo -e "\n" to echo a new line.

Iterating over and deleting from Hashtable in Java

You can use Enumeration:

Hashtable<Integer, String> table = ...

Enumeration<Integer> enumKey = table.keys();
while(enumKey.hasMoreElements()) {
    Integer key = enumKey.nextElement();
    String val = table.get(key);
    if(key==0 && val.equals("0"))
        table.remove(key);
}

Sequel Pro Alternative for Windows

You can try DBVisualizer some features are not free, but you can get an evaluate license...

How do I create a circle or square with just CSS - with a hollow center?

You can use special characters to make lots of shapes. Examples: http://jsfiddle.net/martlark/jWh2N/2/

_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>hollow square</td>_x000D_
    <td>&#9633;</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>solid circle</td>_x000D_
    <td>&bull;</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>open circle</td>_x000D_
    <td>&#3664;</td>_x000D_
  </tr>_x000D_
_x000D_
</table>
_x000D_
_x000D_
_x000D_

enter image description here

Many more can be found here: HTML Special Characters

Using Javascript in CSS

Not in any conventional sense of the phrase "inside CSS."

SQL Server table creation date query

For SQL Server 2000:

SELECT   su.name,so.name,so.crdate,* 
FROM     sysobjects so JOIN sysusers su
ON       so.uid = su.uid
WHERE    xtype='U'
ORDER BY so.name

How to access the local Django webserver from outside world

I'm going to add this here:

  1. sudo python manage.py runserver 80

  2. Go to your phone or computer and enter your computers internal IP (e.g 192.168.0.12) into the browser.

At this point you should be connected to the Django server.

This should also work without sudo:

python manage.py runserver 0.0.0.0:8000

is there a require for json in node.js

No. Either use readFile or readFileSync (The latter only at startup time).

Or use an existing library like

Alternatively write your config in a js file rather then a json file like

module.exports = {
  // json
}

Oracle date function for the previous month

Getting last nth months data retrieve

SELECT * FROM TABLE_NAME 
WHERE DATE_COLUMN BETWEEN '&STARTDATE' AND '&ENDDATE'; 

How to create an Array with AngularJS's ng-model

This should work.

app = angular.module('plunker', [])

app.controller 'MainCtrl', ($scope) ->
  $scope.users = ['bob', 'sean', 'rocky', 'john']
  $scope.test = ->
    console.log $scope.users

HTML:

<input ng-repeat="user in users" ng-model="user" type="text"/>
<input type="button" value="test" ng-click="test()" />

Example plunk here

How to set selected item of Spinner by value, not by position?

very simple just use getSelectedItem();

eg :

ArrayAdapter<CharSequence> type=ArrayAdapter.createFromResource(this,R.array.admin_typee,android.R.layout.simple_spinner_dropdown_item);
        type.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mainType.setAdapter(type);

String group=mainType.getSelectedItem().toString();

the above method returns an string value

in the above the R.array.admin_type is an string resource file in values

just create an .xml file in values>>strings

Filezilla FTP Server Fails to Retrieve Directory Listing

File > Site Manager > Select your site > Transfer Settings > Active

Works for me.

Replace duplicate spaces with a single space in T-SQL

I typically use this approach:

declare @s varchar(50)
set @s = 'TEST         TEST'
select REPLACE(REPLACE(REPLACE(@s,' ','[o][c]'),'[c][o]',''),'[o][c]',' ')

How can I move a tag on a git branch to a different commit?

One other way:

Move tag in remote repo.(Replace HEAD with any other if needed.)

$ git push --force origin HEAD:refs/tags/v0.0.1.2

Fetch changes back.

$ git fetch --tags

super() raises "TypeError: must be type, not classobj" for new-style class

The problem is that super needs an object as an ancestor:

>>> class oldstyle:
...     def __init__(self): self.os = True

>>> class myclass(oldstyle):
...     def __init__(self): super(myclass, self).__init__()

>>> myclass()
TypeError: must be type, not classobj

On closer examination one finds:

>>> type(myclass)
classobj

But:

>>> class newstyle(object): pass

>>> type(newstyle)
type    

So the solution to your problem would be to inherit from object as well as from HTMLParser. But make sure object comes last in the classes MRO:

>>> class myclass(oldstyle, object):
...     def __init__(self): super(myclass, self).__init__()

>>> myclass().os
True

Select all from table with Laravel and Eloquent

If your table is very big, you can also process rows by "small packages" (not all at oce) (laravel doc: Eloquent> Chunking Results )

Post::chunk(200, function($posts)
{
    foreach ($posts as $post)
    {
        // process post here.
    }
});

The APR based Apache Tomcat Native library was not found on the java.library.path

not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib

The native lib is expected in one of the following locations

/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib

and not in

tomcat/lib

The files in tomcat/lib are all jar file and are added by tomcat to the classpath so that they are available to your application.

The native lib is needed by tomcat to perform better on the platform it is installed on and thus cannot be a jar, for linux it could be a .so file, for windows it could be a .dll file.

Just download the native library for your platform and place it in the one of the locations tomcat is expecting it to be.

Note that you are not required to have this lib for development/test purposes. Tomcat runs just fine without it.

org.apache.catalina.startup.Catalina start INFO: Server startup in 2882 ms

EDIT

The output you are getting is very normal, it's just some logging outputs from tomcat, the line right above indicates that the server correctly started and is ready for operating.

If you are troubling with running your servlet then after the run on sever command eclipse opens a browser window (embeded (default) or external, depends on your config). If nothing shows on the browser, then check the url bar of the browser to see whether your servlet was requested or not.

It should be something like that

http://localhost:8080/<your-context-name>/<your-servlet-name>

EDIT 2

Try to call your servlet using the following url

http://localhost:8080/com.filecounter/FileCounter

Also each web project has a web.xml, you can find it in your project under WebContent\WEB-INF.

It is better to configure your servlets there using servlet-name servlet-class and url-mapping. It could look like that:

  <servlet>
    <description></description>
    <display-name>File counter - My first servlet</display-name>
    <servlet-name>file_counter</servlet-name>
    <servlet-class>com.filecounter.FileCounter</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>file_counter</servlet-name>
    <url-pattern>/FileFounter</url-pattern>
  </servlet-mapping>

In eclipse dynamic web project the default context name is the same as your project name.

http://localhost:8080/<your-context-name>/FileCounter

will work too.

How to set the text color of TextView in code?

From API 23 onward, getResources().getColor() is deprecated.

Use this instead:

textView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.color_black));

What does <a href="#" class="view"> mean?

I felt like replying as well, explaining the same thing as the others a bit differently. I am sure you know most of this, but it might help someone else.

<a href="#" class="view">

The

href="#"

part is a commonly used way to make sure the link doesn't lead anywhere on it's own. the #-attribute is used to create a link to some other section in the same document. For example clicking a link of this kind:

<a href="#news">Go to news</a>

will take you to wherever you have the

<a name="news"></a>

code. So if you specify # without any name like in your case, the link leads nowhere.

The

class="view"

part gives it an identifier that CSS or javascript can use. Inside the CSS-files (if you have any) you will find specific styling procedures on all the elements tagged with the "view"-class.

To find out where the URL is specified I would look in the javascript code. It is either written directly in the same document or included from another file.

Search your source code for something like:

<script type="text/javascript"> bla bla bla </script>

or

<script> bla bla bla </script>

and then search for any reference to your "view"-class. An included javascript file can look something like this:

<script type="text/javascript" src="include/javascript.js"></script>

In that case, open javascript.js under the "include" folder and search in that file. Most commonly the includes are placed between <head> and </head> or close to the </body>-tag.

A faster way to find the link is to search for the actual link it goes to. For example, if you are directed to http://www.google.com/search?q=html when you click it, search for "google.com" or something in all the files you have in your web project, just remember the included files.

In many text editors you can open all the files at once, and then search in them all for something.

Common xlabel/ylabel for matplotlib subplots

Without sharex=True, sharey=True you get:

enter image description here

With it you should get it nicer:

fig, axes2d = plt.subplots(nrows=3, ncols=3,
                           sharex=True, sharey=True,
                           figsize=(6,6))

for i, row in enumerate(axes2d):
    for j, cell in enumerate(row):
        cell.imshow(np.random.rand(32,32))

plt.tight_layout()

enter image description here

But if you want to add additional labels, you should add them only to the edge plots:

fig, axes2d = plt.subplots(nrows=3, ncols=3,
                           sharex=True, sharey=True,
                           figsize=(6,6))

for i, row in enumerate(axes2d):
    for j, cell in enumerate(row):
        cell.imshow(np.random.rand(32,32))
        if i == len(axes2d) - 1:
            cell.set_xlabel("noise column: {0:d}".format(j + 1))
        if j == 0:
            cell.set_ylabel("noise row: {0:d}".format(i + 1))

plt.tight_layout()

enter image description here

Adding label for each plot would spoil it (maybe there is a way to automatically detect repeated labels, but I am not aware of one).

CronJob not running

Sometimes the command that cron needs to run is in a directory where cron has no access, typically on systems where users' home directories' permissions are 700 and the command is in that directory.

Enable 'xp_cmdshell' SQL Server

As listed in other answers, the trick (in SQL 2005 or later) is to change the global configuration settings for show advanced options and xp_cmdshell to 1, in that order.

Adding to this, if you want to preserve the previous values, you can read them from sys.configurations first, then apply them in reverse order at the end. We can also avoid unnecessary reconfigure calls:

declare @prevAdvancedOptions int
declare @prevXpCmdshell int

select @prevAdvancedOptions = cast(value_in_use as int) from sys.configurations where name = 'show advanced options'
select @prevXpCmdshell = cast(value_in_use as int) from sys.configurations where name = 'xp_cmdshell'

if (@prevAdvancedOptions = 0)
begin
    exec sp_configure 'show advanced options', 1
    reconfigure
end

if (@prevXpCmdshell = 0)
begin
    exec sp_configure 'xp_cmdshell', 1
    reconfigure
end

/* do work */

if (@prevXpCmdshell = 0)
begin
    exec sp_configure 'xp_cmdshell', 0
    reconfigure
end

if (@prevAdvancedOptions = 0)
begin
    exec sp_configure 'show advanced options', 0
    reconfigure
end

Note that this relies on SQL Server version 2005 or later (original question was for 2008).

How do I select a random value from an enumeration?

Call Enum.GetValues; this returns an array that represents all possible values for your enum. Pick a random item from this array. Cast that item back to the original enum type.

how to remove pagination in datatable

You should include "bPaginate": false, into the configuration object you pass to your constructor parameters. As seen here: http://datatables.net/release-datatables/examples/basic_init/filter_only.html

Regex to validate JSON

Yes, a complete regex validation is possible.

Most modern regex implementations allow for recursive regexpressions, which can verify a complete JSON serialized structure. The json.org specification makes it quite straightforward.

$pcre_regex = '
  /
  (?(DEFINE)
     (?<number>   -? (?= [1-9]|0(?!\d) ) \d+ (\.\d+)? ([eE] [+-]? \d+)? )    
     (?<boolean>   true | false | null )
     (?<string>    " ([^"\\\\]* | \\\\ ["\\\\bfnrt\/] | \\\\ u [0-9a-f]{4} )* " )
     (?<array>     \[  (?:  (?&json)  (?: , (?&json)  )*  )?  \s* \] )
     (?<pair>      \s* (?&string) \s* : (?&json)  )
     (?<object>    \{  (?:  (?&pair)  (?: , (?&pair)  )*  )?  \s* \} )
     (?<json>   \s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) \s* )
  )
  \A (?&json) \Z
  /six   
';

It works quite well in PHP with the PCRE functions . Should work unmodified in Perl; and can certainly be adapted for other languages. Also it succeeds with the JSON test cases.

Simpler RFC4627 verification

A simpler approach is the minimal consistency check as specified in RFC4627, section 6. It's however just intended as security test and basic non-validity precaution:

  var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
         text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
     eval('(' + text + ')');

Clearing localStorage in javascript?

If you want to clear all item you stored in localStorage then

localStorage.clear();

Use this for clear all stored key.

If you want to clear/remove only specific key/value then you can use removeItem(key).

localStorage.removeItem('yourKey');

Get folder name from full file path

Based on previous answers (but fixed)

using static System.IO.Path;

var dir = GetFileName(path?.TrimEnd(DirectorySeparatorChar, AltDirectorySeparatorChar));

Explanation of GetFileName from .NET source:

Returns the name and extension parts of the given path. The resulting string contains the characters of path that follow the last backslash ("\"), slash ("/"), or colon (":") character in path. The resulting string is the entire path if path contains no backslash after removing trailing slashes, slash, or colon characters. The resulting string is null if path is null.

env: node: No such file or directory in mac

I was getting this env: node: No such file or directory error when running the job through Jenkins.

What I did to fix it - added export PATH="$PATH:"/usr/local/bin/ at the beginning of the script that Jenkins job executes.

JSON formatter in C#?

Example

    public static string JsonFormatter(string json)
    {
        StringBuilder builder = new StringBuilder();

        bool quotes = false;

        bool ignore = false;

        int offset = 0;

        int position = 0;

        if (string.IsNullOrEmpty(json))
        {
            return string.Empty;
        }

        json = json.Replace(Environment.NewLine, "").Replace("\t", "");

        foreach (char character in json)
        {
            switch (character)
            {
                case '"':
                    if (!ignore)
                    {
                        quotes = !quotes;
                    }
                    break;
                case '\'':
                    if (quotes)
                    {
                        ignore = !ignore;
                    }
                    break;
            }

            if (quotes)
            {
                builder.Append(character);
            }
            else
            {
                switch (character)
                {
                    case '{':
                    case '[':
                        builder.Append(character);
                        builder.Append(Environment.NewLine);
                        builder.Append(new string(' ', ++offset * 4));
                        break;
                    case '}':
                    case ']':
                        builder.Append(Environment.NewLine);
                        builder.Append(new string(' ', --offset * 4));
                        builder.Append(character);
                        break;
                    case ',':
                        builder.Append(character);
                        builder.Append(Environment.NewLine);
                        builder.Append(new string(' ', offset * 4));
                        break;
                    case ':':
                        builder.Append(character);
                        builder.Append(' ');
                        break;
                    default:
                        if (character != ' ')
                        {
                            builder.Append(character);
                        }
                        break;
                }

                position++;
            }
        }

        return builder.ToString().Trim();
    }

How to copy files between two nodes using ansible

I was able to solve this using local_action to scp to file from machineA to machineC and then copying the file to machineB.

The value violated the integrity constraints for the column

It usually happens when Allow Nulls option is unchecked.

Solution:

  1. Look at the name of the column for this error/warning.
  2. Go to SSMS and find the table
  3. Allow Null for that Column
  4. Save the table
  5. Rerun the SSIS

Try these steps. It worked for me.

See this link

Execute cmd command from VBScript

Set oShell = WScript.CreateObject("WSCript.shell")
oShell.run "cmd cd /d C:dir_test\file_test & sanity_check_env.bat arg1"

How to resolve "local edit, incoming delete upon update" message

Short version:

$ svn st
!  +  C foo
      >   local edit, incoming delete upon update
!  +  C bar
      >   local edit, incoming delete upon update
$ touch foo bar
$ svn revert foo bar
$ rm foo bar

If the conflict is about directories instead of files then replace touch with mkdir and rm with rm -r.


Note: the same procedure also work for the following situation:

$ svn st
!     C foo
      >   local delete, incoming delete upon update
!     C bar
      >   local delete, incoming delete upon update

Long version:

This happens when you edit a file while someone else deleted the file and commited first. As a good svn citizen you do an update before a commit. Now you have a conflict. Realising that deleting the file is the right thing to do you delete the file from your working copy. Instead of being content svn now complains that the local files are missing and that there is a conflicting update which ultimately wants to see the files deleted. Good job svn.

Should svn resolve not work, for whatever reason, you can do the following:

Initial situation: Local files are missing, update is conflicting.

$ svn st
!  +  C foo
      >   local edit, incoming delete upon update
!  +  C bar
      >   local edit, incoming delete upon update

Recreate the conflicting files:

$ touch foo bar

If the conflict is about directories then replace touch with mkdir.

New situation: Local files to be added to the repository (yeah right, svn, whatever you say), update still conflicting.

$ svn st
A  +  C foo
      >   local edit, incoming delete upon update
A  +  C bar
      >   local edit, incoming delete upon update

Revert the files to the state svn likes them (that means deleted):

$ svn revert foo bar

New situation: Local files not known to svn, update no longer conflicting.

$ svn st
?       foo
?       bar

Now we can delete the files:

$ rm foo bar

If the conflict is about directories then replace rm with rm -r.

svn no longer complains:

$ svn st

Done.

WPF Datagrid Get Selected Cell Value

Worked For me

object item = dgwLoadItems.SelectedItem;
string ID = (dgwLoadItems.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
MessageBox.Show(ID);

How to select a value in dropdown javascript?

function setSelectedIndex(s, v) {
    for ( var i = 0; i < s.options.length; i++ ) {
        if ( s.options[i].value == v ) {
            s.options[i].selected = true;
            return;
        }
    }
}

Where s is the dropdown and v is the value

What is the largest Safe UDP Packet Size on the Internet

Given that IPV6 has a size of 1500, I would assert that carriers would not provide separate paths for IPV4 and IPV6 (they are both IP with different types), forcing them to equipment for ipv4 that would be old, redundant, more costly to maintain and less reliable. It wouldn't make any sense. Besides, doing so might easily be considered providing preferential treatment for some traffic -- a no no under rules they probably don't care much about (unless they get caught).

So 1472 should be safe for external use (though that doesn't mean an app like DNS that doesn't know about EDNS will accept it), and if you are talking internal nets, you can more likely know your network layout in which case jumbo packet sizes apply for for non-fragmented packets so for 4096 - 4068 bytes, and for intel's cards with 9014 byte buffers, a package size of ... wait...8086 bytes, would be the max...coincidence? snicker

****UPDATE****

Various answers give maximum values allowed by 1 SW vendor or various answers assuming encapsulation. The user didn't ask for the lowest value possible (like "0" for a safe UDP size), but the largest safe packet size.

Encapsulation values for various layers can be included multiple times. Since once you've encapsulated a stream -- there is nothing prohibiting, say, a VPN layer below that and a complete duplication of encapsulation layers above that.

Since the question was about maximum safe values, I'm assuming that they are talking about the maximum safe value for a UDP packet that can be received. Since no UDP packet is guaranteed, if you receive a UDP packet, the largest safe size would be 1 packet over IPv4 or 1472 bytes.

Note -- if you are using IPv6, the maximum size would be 1452 bytes, as IPv6's header size is 40 bytes vs. IPv4's 20 byte size (and either way, one must still allow 8 bytes for the UDP header).

How to render a DateTime object in a Twig template

{{game.gameDate | date('c')}}  // 2014-02-05T16:45:22+00:00

For full date time string including timezone offset.

Convert Mat to Array/Vector in OpenCV

cv::Mat m;
m.create(10, 10, CV_32FC3);

float *array = (float *)malloc( 3*sizeof(float)*10*10 );
cv::MatConstIterator_<cv::Vec3f> it = m.begin<cv::Vec3f>();
for (unsigned i = 0; it != m.end<cv::Vec3f>(); it++ ) {
    for ( unsigned j = 0; j < 3; j++ ) {
        *(array + i ) = (*it)[j];
        i++;
    }
}

Now you have a float array. In case of 8 bit, simply change float to uchar, Vec3f to Vec3b and CV_32FC3 to CV_8UC3.

Php - Your PHP installation appears to be missing the MySQL extension which is required by WordPress

When I upgraded my website PHP from version 5.6 to 7.2, I encountered this problem “Your PHP installation appears to be missing the MySQL extension which is required by WordPress”. It turns out that mysql extension is no longer supported in PHP version 7.2. It is now using mysqli extention. I am using old version of WordPress which still using mysql extension that is why the problem existed. So what I did is upgraded the WordPress to the core. This solve the problem.

Here's the steps I followed when upgrading WordPress manually.

  1. First I created a full backup of my website. This is very important in case of mistake.
  2. I download the newest WordPress ZIP file from wordpress.org.
  3. I unzipped the file into a local directory of my computer.
  4. I went to my website root directory and deleted your ‘wp-includes’ and ‘wp-admin’ directories. I used sFTP connection using Filezilla software.
  5. I uploaded the new wp-includes and wp-admin directories from the new version of WordPress I unzipped to my website root directory and replaced the directories I just deleted.
  6. I did not delete the wp-content directory or any of the files in that directory. I just copied over the files from the wp-content directory in the new version of WordPress to my existing wp-content directory. All existing files with the same name have been overwritten.
  7. I copied all files from the root (‘/’) directory of the new version of WordPress that I unzipped into my website root directory (or the root directory of your WordPress installation). Existing files has been overwritten and new files has been copied across. wp-config.php file was not be affected because WordPress has never distributed with a wp-config.php file.
  8. I compare wp-config-sample.php which was distributed with WordPress but did not find anything to change so I just used the old one.
  9. I cleared my browser cache to ensure I can see all changes.
  10. I checked the site and there is no error now. The upgrade was completed.

Select from table by knowing only date without time (ORACLE)

You could use the between function to get all records between 2010-08-03 00:00:00:000 AND 2010-08-03 23:59:59:000

Best way to write to the console in PowerShell

Default behaviour of PowerShell is just to dump everything that falls out of a pipeline without being picked up by another pipeline element or being assigned to a variable (or redirected) into Out-Host. What Out-Host does is obviously host-dependent.

Just letting things fall out of the pipeline is not a substitute for Write-Host which exists for the sole reason of outputting text in the host application.

If you want output, then use the Write-* cmdlets. If you want return values from a function, then just dump the objects there without any cmdlet.

Datatables - Search Box outside datatable

This one helped me for DataTables Version 1.10.4, because its new API

var oTable = $('#myTable').DataTable();    
$('#myInputTextField').keyup(function(){
   oTable.search( $(this).val() ).draw();
})

How to calculate the intersection of two sets?

Use the retainAll() method of Set:

Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets

If you want to preserve the sets, create a new set to hold the intersection:

Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);

The javadoc of retainAll() says it's exactly what you want:

Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.

Java 8 - Best way to transform a list: map or foreach?

I prefer the second way.

When you use the first way, if you decide to use a parallel stream to improve performance, you'll have no control over the order in which the elements will be added to the output list by forEach.

When you use toList, the Streams API will preserve the order even if you use a parallel stream.

How to handle screen orientation change when progress dialog and background thread active?

i have found and easier solution to handle threads when orientation change. You can just keep an static reference to your activity/fragment and verify if its null before acting on the ui. I suggest using a try catch too:

 public class DashListFragment extends Fragment {
     private static DashListFragment ACTIVE_INSTANCE;

     @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ACTIVE_INSTANCE = this;

        new Handler().postDelayed(new Runnable() {
            public void run() {
                try {
                        if (ACTIVE_INSTANCE != null) {
                            setAdapter(); // this method do something on ui or use context
                        }
                }
                catch (Exception e) {}


            }
        }, 1500l);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        ACTIVE_INSTANCE = null;
    }


}

How to build & install GLFW 3 and use it in a Linux project

Step 1: Installing GLFW 3 on your system with CMAKE

For this install, I was using KUbuntu 13.04, 64bit.

The first step is to download the latest version (assuming versions in the future work in a similar way) from www.glfw.org, probably using this link.

The next step is to extract the archive, and open a terminal. cd into the glfw-3.X.X directory and run cmake -G "Unix Makefiles" you may need elevated privileges, and you may also need to install build dependencies first. To do this, try sudo apt-get build-dep glfw or sudo apt-get build-dep glfw3 or do it manually, as I did using sudo apt-get install cmake xorg-dev libglu1-mesa-dev... There may be other libs you require such as the pthread libraries... Apparently I had them already. (See the -l options given to the g++ linker stage, below.)

Now you can type make and then make install, which will probably require you to sudo first.

Okay, you should get some verbose output on the last three CMake stages, telling you what has been built or where it has been placed. (In /usr/include, for example.)

Step 2: Create a test program and compile

The next step is to fire up vim ("what?! vim?!" you say) or your preferred IDE / text editor... I didn't use vim, I used Kate, because I am on KUbuntu 13.04... Anyway, download or copy the test program from here (at the bottom of the page) and save, exit.

Now compile using g++ -std=c++11 -c main.cpp - not sure if c++11 is required but I used nullptr so, I needed it... You may need to upgrade your gcc to version 4.7, or the upcoming version 4.8... Info on that here.

Then fix your errors if you typed the program by hand or tried to be "too clever" and something didn't work... Then link it using this monster! g++ main.o -o main.exec -lGL -lGLU -lglfw3 -lX11 -lXxf86vm -lXrandr -lpthread -lXi So you see, in the "install build dependencies" part, you may also want to check you have the GL, GLU, X11 Xxf86vm (whatever that is) Xrandr posix-thread and Xi (whatever that is) development libraries installed also. Maybe update your graphics drivers too, I think GLFW 3 may require OpenGL version 3 or higher? Perhaps someone can confirm that? You may also need to add the linker options -ldl -lXinerama -lXcursor to get it to work correctly if you are getting undefined references to dlclose (credit to @user2255242).

And, yes, I really did need that many -ls!

Step 3: You are finished, have a nice day!

Hopefully this information was correct and everything worked for you, and you enjoyed writing the GLFW test program. Also hopefully this guide has helped, or will help, a few people in the future who were struggling as I was today yesterday!

By the way, all the tags are the things I searched for on stackoverflow looking for an answer that didn't exist. (Until now.) Hopefully they are what you searched for if you were in a similar position to myself.

Author Note:

This might not be a good idea. This method (using sudo make install) might be harzardous to your system. (See Don't Break Debian)

Ideally I, or someone else, should propose a solution which does not just install lib files etc into the system default directories as these should be managed by package managers such as apt, and doing so may cause a conflict and break your package management system.

See the new "2020 answer" for an alternative solution.

boundingRectWithSize for NSAttributedString returning wrong size

Turns out that EVERY part of an NSAttributedString must have a dictionary set with at least NSFontAttributeName and NSForegroundColorAttributeName set, if you wish boundingRectWithSize to actually work!

I don't see that documented anywhere.

How to input a regex in string.replace?

This tested snippet should do it:

import re
line = re.sub(r"</?\[\d+>", "", line)

Edit: Here's a commented version explaining how it works:

line = re.sub(r"""
  (?x) # Use free-spacing mode.
  <    # Match a literal '<'
  /?   # Optionally match a '/'
  \[   # Match a literal '['
  \d+  # Match one or more digits
  >    # Match a literal '>'
  """, "", line)

Regexes are fun! But I would strongly recommend spending an hour or two studying the basics. For starters, you need to learn which characters are special: "metacharacters" which need to be escaped (i.e. with a backslash placed in front - and the rules are different inside and outside character classes.) There is an excellent online tutorial at: www.regular-expressions.info. The time you spend there will pay for itself many times over. Happy regexing!

Trying to SSH into an Amazon Ec2 instance - permission error

You are likely using the wrong username to login:

  • most Ubuntu images have a user ubuntu
  • Amazon's AMI is ec2-user
  • most Debian images have either root or admin

To login, you need to adjust your ssh command:

ssh -l USERNAME_HERE -i .ssh/yourkey.pem public-ec2-host

HTH

How do I scroll the UIScrollView when the keyboard appears?

Here is a Swift 3 compatible answer, that will also work with view controllers within a navigation controller - as they will change the scroll views contentInset.top property.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    self.registerKeyboardNotifications()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    self.unregisterKeyboardNotifications()
}

func registerKeyboardNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.keyboardDidShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func unregisterKeyboardNotifications() {
    NotificationCenter.default.removeObserver(self)
}


func keyboardDidShow(notification: NSNotification) {
    let userInfo: NSDictionary = notification.userInfo! as NSDictionary
    let keyboardInfo = userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue
    let keyboardSize = keyboardInfo.cgRectValue.size

    // Get the existing contentInset for the scrollView and set the bottom property to be the height of the keyboard
    var contentInset = self.scrollView.contentInset
    contentInset.bottom = keyboardSize.height

    self.scrollView.contentInset = contentInset
    self.scrollView.scrollIndicatorInsets = contentInset
}

func keyboardWillHide(notification: NSNotification) {
    var contentInset = self.scrollView.contentInset
    contentInset.bottom = 0

    self.scrollView.contentInset = contentInset
    self.scrollView.scrollIndicatorInsets = UIEdgeInsets.zero
}

Tab separated values in awk

You need to set the OFS variable (output field separator) to be a tab:

echo "$line" | 
awk -v var="$mycol_new" -F $'\t' 'BEGIN {OFS = FS} {$3 = var; print}'

(make sure you quote the $line variable in the echo statement)

Where does Android app package gets installed on phone

System apps installed /system/app/ or /system/priv-app. Other apps can be installed in /data/app or /data/preload/.

Connect to your android mobile with USB and run the following commands. You will see all the installed packages.

$ adb shell 

$ pm list packages -f

SQL join on multiple columns in same tables

Join like this:

ON a.userid = b.sourceid AND a.listid = b.destinationid;

HRESULT: 0x800A03EC on Worksheet.range

Looking at the various responses above, and drawing on my own recent experience (I got this error code doing something completely unrelated -- setting Application.Calculation) I conclude that the same error code is used to indicate multiple unrelated problems. So @Garreh you should probably be asking a new question (not that anyone will be able to help based on the error code alone). I've seen the same thing working with Word interop from C#, where the same HRESULT seems to be used for almost every kind of error. I've never found any satisfactory Microsoft documentation on what the codes might mean.

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

Here is the working solution

create a new page main.html

example:

<!doctype html>
<html>
  <head>
   <title>tittle</title>
   <script>
     window.location='./index.html';
   </script>
  </head>
  <body>
  </body>
</html>

change the following in mainactivity.java

super.loadUrl("file:///android_asset/www/index.html");

to

super.loadUrl("file:///android_asset/www/main.html");

Now build your application and it works on any slow connection

refernce.

NOTE: This is a workaround I found in 2013.

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

Here one big collection of debug constants that we use. Enjoy.

// Uncomment the defitions to show additional info.

//  #define DEBUG

//  #define DEBUGWHERE_SHOWFULLINFO

//  #define DEBUG_SHOWLINES
//  #define DEBUG_SHOWFULLPATH
//  #define DEBUG_SHOWSEPARATORS
//  #define DEBUG_SHOWFULLINFO


// Definition of DEBUG functions. Only work if DEBUG is defined.
#ifdef DEBUG 

    #define debug_separator() NSLog( @"----------------------------------------------------------------------------" );

    #ifdef DEBUG_SHOWSEPARATORS
        #define debug_showSeparators() debug_separator();
    #else
        #define debug_showSeparators()
    #endif

    /// /// /// ////// ///// 

    #ifdef DEBUG_SHOWFULLPATH
        #define debug_whereFull() debug_showSeparators(); NSLog(@"Line:%d : %s : %s", __LINE__,__FILE__,__FUNCTION__); debug_showSeparators(); 
    #else
        #define debug_whereFull() debug_showSeparators(); NSLog(@"Line:%d : %s : %s", __LINE__,[ [ [ [NSString alloc] initWithBytes:__FILE__ length:strlen(__FILE__) encoding:NSUTF8StringEncoding] lastPathComponent] UTF8String ] ,__FUNCTION__); debug_showSeparators(); 
    #endif

    /// /// /// ////// ///// 

    #define debugExt(args,...) debug_separator(); debug_whereFull(); NSLog( args, ##__VA_ARGS__); debug_separator();

    /// /// /// ////// ///// Debug Print Macros

    #ifdef DEBUG_SHOWFULLINFO
        #define debug(args,...) debugExt(args, ##__VA_ARGS__);
    #else
        #ifdef DEBUG_SHOWLINES
            #define debug(args,...) debug_showSeparators(); NSLog([ NSString stringWithFormat:@"Line:%d : %@", __LINE__, args ], ##__VA_ARGS__); debug_showSeparators();
        #else
            #define debug(args,...) debug_showSeparators(); NSLog(args, ##__VA_ARGS__); debug_showSeparators();
        #endif
    #endif

    /// /// /// ////// ///// Debug Specific Types

    #define debug_object( arg ) debug( @"Object: %@", arg );
    #define debug_int( arg ) debug( @"integer: %i", arg );
    #define debug_float( arg ) debug( @"float: %f", arg );
    #define debug_rect( arg ) debug( @"CGRect ( %f, %f, %f, %f)", arg.origin.x, arg.origin.y, arg.size.width, arg.size.height );
    #define debug_point( arg ) debug( @"CGPoint ( %f, %f )", arg.x, arg.y );
    #define debug_bool( arg )   debug( @"Boolean: %@", ( arg == YES ? @"YES" : @"NO" ) );

    /// /// /// ////// ///// Debug Where Macros

    #ifdef DEBUGWHERE_SHOWFULLINFO
        #define debug_where() debug_whereFull(); 
    #else
        #define debug_where() debug(@"%s",__FUNCTION__); 
    #endif

    #define debug_where_separators() debug_separator(); debug_where(); debug_separator();

    /// /// /// ////// /////

#else
    #define debug(args,...) 
    #define debug_separator()  
    #define debug_where()   
    #define debug_where_separators()  
    #define debug_whereFull()   
    #define debugExt(args,...)
    #define debug_object( arg ) 
    #define debug_int( arg ) 
    #define debug_rect( arg )   
    #define debug_bool( arg )   
    #define debug_point( arg )
    #define debug_float( arg )
#endif

Using multiple IF statements in a batch file

Batch files have really very limited logic powers so the best you can hope to come up with is a good workaround that indirectly achieves what you want. That's not to say that you should feel they are inferior to a real language - they still demand the same attention to detail and manual debugging as a real application. It's just that you'll need to work a lot harder to make them do what you want in a robust manner.

For the OP's question it sounds like you require two specific files to exist. Just use a tally:

IF EXIST somefile.txt (
    set /a file1_status=1
)

IF EXIST someotehrfile.txt (
    set /a file2_status=1
)

set /a file_status_result=file1_status + file2_status

if %file_status_result% equ 2 (
    goto somefileexists
)

goto exit

:somefileexists
IF EXIST someotherfile.txt SET var=...

:exit

My example uses 3 variables, but you could just add 1 to file_result_status if the file exists. But if you want more granular control later in your batch file you can record the result for each file as I have done so you don't have to keep checking if a file exists later on.

How to set Sqlite3 to be case insensitive when string comparing?

You can use COLLATE NOCASE in your SELECT query:

SELECT * FROM ... WHERE name = 'someone' COLLATE NOCASE

Additionaly, in SQLite, you can indicate that a column should be case insensitive when you create the table by specifying collate nocase in the column definition (the other options are binary (the default) and rtrim; see here). You can specify collate nocase when you create an index as well. For example:

create table Test
(
  Text_Value  text collate nocase
);

insert into Test values ('A');
insert into Test values ('b');
insert into Test values ('C');

create index Test_Text_Value_Index
  on Test (Text_Value collate nocase);

Expressions involving Test.Text_Value should now be case insensitive. For example:

sqlite> select Text_Value from Test where Text_Value = 'B';
Text_Value      
----------------
b               

sqlite> select Text_Value from Test order by Text_Value;
Text_Value      
----------------
A               
b               
C    

sqlite> select Text_Value from Test order by Text_Value desc;
Text_Value      
----------------
C               
b               
A               

The optimiser can also potentially make use of the index for case-insensitive searching and matching on the column. You can check this using the explain SQL command, e.g.:

sqlite> explain select Text_Value from Test where Text_Value = 'b';
addr              opcode          p1          p2          p3                               
----------------  --------------  ----------  ----------  ---------------------------------
0                 Goto            0           16                                           
1                 Integer         0           0                                            
2                 OpenRead        1           3           keyinfo(1,NOCASE)                
3                 SetNumColumns   1           2                                            
4                 String8         0           0           b                                
5                 IsNull          -1          14                                           
6                 MakeRecord      1           0           a                                
7                 MemStore        0           0                                            
8                 MoveGe          1           14                                           
9                 MemLoad         0           0                                            
10                IdxGE           1           14          +                                
11                Column          1           0                                            
12                Callback        1           0                                            
13                Next            1           9                                            
14                Close           1           0                                            
15                Halt            0           0                                            
16                Transaction     0           0                                            
17                VerifyCookie    0           4                                            
18                Goto            0           1                                            
19                Noop            0           0                                            

Response::json() - Laravel 5.1

use the helper function in laravel 5.1 instead:

return response()->json(['name' => 'Abigail', 'state' => 'CA']);

This will create an instance of \Illuminate\Routing\ResponseFactory. See the phpDocs for possible parameters below:

/**
* Return a new JSON response from the application.
*
* @param string|array $data
* @param int $status
* @param array $headers
* @param int $options
* @return \Symfony\Component\HttpFoundation\Response 
* @static 
*/
public static function json($data = array(), $status = 200, $headers = array(), $options = 0){

    return \Illuminate\Routing\ResponseFactory::json($data, $status, $headers, $options);
}

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

Most of what I write has already been covered by Pressacco, but this is specific to SpecFlow.

I was getting this message for the <specFlow> element and therefore I added a specflow.xsd file to the solution this answer (with some modifications to allow for the <plugins> element).

Thereafter I (like Pressacco), right clicked within the file buffer of app.config and selected properties, and within Schemas, I added "specflow.xsd" to the end. The entirety of Schemas now reads:

"C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\1033\DotNetConfig.xsd" "C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\EntityFrameworkConfig_6_1_0.xsd" "C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\RazorCustomSchema.xsd" "specflow.xsd"

Create SQL identity as primary key?

Simple change to syntax is all that is needed:

 create table ImagenesUsuario (
   idImagen int not null identity(1,1) primary key
 )

By explicitly using the "constraint" keyword, you can give the primary key constraint a particular name rather than depending on SQL Server to auto-assign a name:

 create table ImagenesUsuario (
   idImagen int not null identity(1,1) constraint pk_ImagenesUsario primary key
 )

Add the "CLUSTERED" keyword if that makes the most sense based on your use of the table (i.e., the balance of searches for a particular idImagen and amount of writing outweighs the benefits of clustering the table by some other index).

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

Try to this cors npm modules.

var cors = require('cors')

var app = express()
app.use(cors())

This module provides many features to fine tune cors setting such as domain whitelisting, enabling cors for specific apis etc.

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

Arhhh this got me and I spent a lot of time troubleshooting it. The problem was my tests were being executed in Parellel (the default with XUnit).

To make my test run sequentially I decorated each class with this attribute:

[Collection("Sequential")]

This is how I worked it out: Execute unit tests serially (rather than in parallel)


I mock up my EF In Memory context with GenFu:

private void CreateTestData(TheContext dbContext)
{
    GenFu.GenFu.Configure<Employee>()
       .Fill(q => q.EmployeeId, 3);
    var employee = GenFu.GenFu.ListOf<Employee>(1);

    var id = 1;
    GenFu.GenFu.Configure<Team>()
        .Fill(p => p.TeamId, () => id++).Fill(q => q.CreatedById, 3).Fill(q => q.ModifiedById, 3);
    var Teams = GenFu.GenFu.ListOf<Team>(20);
    dbContext.Team.AddRange(Teams);

    dbContext.SaveChanges();
}

When Creating Test Data, from what I can deduct, it was alive in two scopes (once in the Employee's Tests while the Team tests were running):

public void Team_Index_should_return_valid_model()
{
    using (var context = new TheContext(CreateNewContextOptions()))
    {
        //Arrange
        CreateTestData(context);
        var controller = new TeamController(context);

        //Act
        var actionResult = controller.Index();

        //Assert
        Assert.NotNull(actionResult);
        Assert.True(actionResult.Result is ViewResult);
        var model = ModelFromActionResult<List<Team>>((ActionResult)actionResult.Result);
        Assert.Equal(20, model.Count);
    }
}

Wrapping both Test Classes with this sequential collection attribute has cleared the apparent conflict.

[Collection("Sequential")]

Additional references:

https://github.com/aspnet/EntityFrameworkCore/issues/7340
EF Core 2.1 In memory DB not updating records
http://www.jerriepelser.com/blog/unit-testing-aspnet5-entityframework7-inmemory-database/
http://gunnarpeipman.com/2017/04/aspnet-core-ef-inmemory/
https://github.com/aspnet/EntityFrameworkCore/issues/12459
Preventing tracking issues when using EF Core SqlLite in Unit Tests

Spring Data JPA - "No Property Found for Type" Exception

In Addition to the suggestions, I would also suggest annotating your Repository interface with @Repository.

The Spring IOC may not detect this as a repository and thus be unable to detect the entity and its corresponding property.

Create Setup/MSI installer in Visual Studio 2017

Other answers posted here for this question did not work for me using the latest Visual Studio 2017 Enterprise edition (as of 2018-09-18).

Instead, I used this method:

  1. Close all but one instance of Visual Studio.
  2. In the running instance, access the menu Tools->Extensions and Updates.
  3. In that dialog, choose Online->Visual Studio Marketplace->Tools->Setup & Deployment.
  4. From the list that appears, select Microsoft Visual Studio 2017 Installer Projects.

Once installed, close and restart Visual Studio. Go to File->New Project and search for the word Installer. You'll know you have the correct templates installed if you see a list that looks something like this:

enter image description here

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

How can I calculate the time between 2 Dates in typescript

In order to calculate the difference you have to put the + operator,

that way typescript converts the dates to numbers.

+new Date()- +new Date("2013-02-20T12:01:04.753Z")

From there you can make a formula to convert the difference to minutes or hours.

Adding and using header (HTTP) in nginx

You can use upstream headers (named starting with $http_) and additional custom headers. For example:

add_header X-Upstream-01 $http_x_upstream_01;
add_header X-Hdr-01  txt01;

next, go to console and make request with user's header:

curl -H "X-Upstream-01: HEADER1" -I http://localhost:11443/

the response contains X-Hdr-01, seted by server and X-Upstream-01, seted by client:

HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 30 Nov 2015 23:54:30 GMT
Content-Type: text/html;charset=UTF-8
Connection: keep-alive
X-Hdr-01: txt01
X-Upstream-01: HEADER1

How to supply value to an annotation from a Constant java

I am thinking this may not be possible in Java because annotation and its parameters are resolved at compile time.

With Seam 2 http://seamframework.org/ you were able to resolve annotation parameters at runtime, with expression language inside double quotes.

In Seam 3 http://seamframework.org/Seam3/Solder, this feature is the module Seam Solder

Trim spaces from start and end of string

Here is some methods I've been used in the past to trim strings in js:

String.prototype.ltrim = function( chars ) {
    chars = chars || "\\s*";
    return this.replace( new RegExp("^[" + chars + "]+", "g"), "" );
}

String.prototype.rtrim = function( chars ) {
    chars = chars || "\\s*";
    return this.replace( new RegExp("[" + chars + "]+$", "g"), "" );
}
String.prototype.trim = function( chars ) {
    return this.rtrim(chars).ltrim(chars);
}

How do you add a JToken to an JObject?

TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)


The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.

  • JToken = The mother of all other types. It can be A JValue, JProperty, JArray, or JObject. This is to provide a modular design to the parsing mechanism.
  • JValue = any Json value type (string, int, boolean).
  • JProperty = any JValue or JContainer (see below) paired with a name (identifier). For example "name":"value".
  • JContainer = The mother of all types which contain other types (JObject, JValue).
  • JObject = a JContainer type that holds a collection of JProperties
  • JArray = a JContainer type that holds a collection JValue or JContainer.

Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.

What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name"), and then create another JProperty of your desire and then add it after this using AddAfterSelf method. You are done then.

For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm

This is the code I modified.

public class Program
{
  public static void Main()
  {
    try
    {
      string jsonText = @"
      {
        ""food"": {
          ""fruit"": {
            ""apple"": {
              ""colour"": ""red"",
              ""size"": ""small""
            },
            ""orange"": {
              ""colour"": ""orange"",
              ""size"": ""large""
            }
          }
        }
      }";

      var foodJsonObj = JObject.Parse(jsonText);
      var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");

      var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
      fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));

      Console.WriteLine(foodJsonObj.ToString());
    }
    catch (Exception ex)
    {
      Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
    }
  }
}

Can I limit the length of an array in JavaScript?

You're not using splice correctly:

arr.splice(4, 1)

this will remove 1 item at index 4. see here

I think you want to use slice:

arr.slice(0,5)

this will return elements in position 0 through 4.

This assumes all the rest of your code (cookies etc) works correctly

Error: the entity type requires a primary key

When I used the Scaffold-DbContext command, it didn't include the "[key]" annotation in the model files or the "entity.HasKey(..)" entry in the "modelBuilder.Entity" blocks. My solution was to add a line like this in every "modelBuilder.Entity" block in the *Context.cs file:

entity.HasKey(X => x.Id);

I'm not saying this is better, or even the right way. I'm just saying that it worked for me.

Android - set TextView TextStyle programmatically?

As mentioned here, this feature is not currently supported.

What's a clean way to stop mongod on Mac OS X?

The solutions provided by others used to work for me but is not working for me anymore, which is as below.

brew services stop mongodb
brew services start mongodb

brew services list gives

Name              Status  User      Plist
mongodb-community started XXXXXXXXX /Users/XXXXXXXXX/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist

So I used mongodb-community instead of mongodb which worked for me

brew services stop mongodb-community
brew services start mongodb-community

How to empty ("truncate") a file on linux that already exists and is protected in someway?

Since sudo will not work with redirection >, I like the tee command for this purpose

echo "" | sudo tee fileName

How do I disable log messages from the Requests library?

For anybody using logging.config.dictConfig you can alter the requests library log level in the dictionary like this:

'loggers': {
    '': {
        'handlers': ['file'],
        'level': level,
        'propagate': False
    },
    'requests.packages.urllib3': {
        'handlers': ['file'],
        'level': logging.WARNING
    }
}

Which to use <div class="name"> or <div id="name">?

ID's must be unique (only be given to one element in the DOM at a time), whereas classes don't have to be. You've already discovered the CSS . class and # ID prefixes, so that's pretty much it.

how to get last insert id after insert query in codeigniter active record

From the documentation:

$this->db->insert_id()

The insert ID number when performing database inserts.

Therefore, you could use something like this:

$lastid = $this->db->insert_id();

Why is it bad style to `rescue Exception => e` in Ruby?

That's a specific case of the rule that you shouldn't catch any exception you don't know how to handle. If you don't know how to handle it, it's always better to let some other part of the system catch and handle it.

Get all photos from Instagram which have a specific hashtag with PHP

If you only need to display the images base on a tag, then there is not to include the wrapper class "instagram.class.php". As the Media & Tag Endpoints in Instagram API do not require authentication. You can use the following curl based function to retrieve results based on your tag.

 function callInstagram($url)
    {
    $ch = curl_init();
    curl_setopt_array($ch, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => 2
    ));

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
    }

    $tag = 'YOUR_TAG_HERE';
    $client_id = "YOUR_CLIENT_ID";
    $url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id;

    $inst_stream = callInstagram($url);
    $results = json_decode($inst_stream, true);

    //Now parse through the $results array to display your results... 
    foreach($results['data'] as $item){
        $image_link = $item['images']['low_resolution']['url'];
        echo '<img src="'.$image_link.'" />';
    }

Angular 2 Scroll to bottom (Chat style)

Here's another good solution on stackblitz.

Alternatively:

The accepted answer is a good solution, but it can be improved since your content/chat may often scroll to the bottom involuntarily given how the ngAfterViewChecked() lifecycle hook works.

Here's an improved version...

COMPONENT

import {..., AfterViewChecked, ElementRef, ViewChild, OnInit} from 'angular2/core'
@Component({
    ...
})
export class ChannelComponent implements OnInit, AfterViewChecked {
    @ViewChild('scrollMe') private myScrollContainer: ElementRef;

    /**Add the variable**/
    scrolledToBottom = false;

    ngAfterViewChecked() {        
        this.scrollToBottom();        
    } 

    scrollToBottom(): void {
        try {
          /**Add the condition**/
          if(!this.scrolledToBottom){
             this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
          }   
        } catch(err) { }                 
    }

    /**Add the method**/
    onScroll(){
      this.scrolledToBottom = true;
    }
}

TEMPLATE

<!--Add a scroll event listener-->
<div #scrollMe 
     style="overflow: scroll; height: xyz;"
     (scroll)="onScroll()">
    <div class="..." 
        *ngFor="..."
        ...>  
    </div>
</div>

How to get Git to clone into current directory

The solution for Windows is to clone the repository to other folder and then copy and paste to the original location or just copy the .git invisible folder.

How to check if an option is selected?

If you need to check option selected state for specific value:

$('#selectorId option[value=YOUR_VALUE]:selected')

Best way to import Observable from rxjs

Update for RxJS 6 (April 2018)

It is now perfectly fine to import directly from rxjs. (As can be seen in Angular 6+). Importing from rxjs/operators is also fine and it is actually no longer possible to import operators globally (one of major reasons for refactoring rxjs 6 and the new approach using pipe). Thanks to this treeshaking can now be used as well.

Sample code from rxjs repo:

import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';

range(1, 200)
  .pipe(filter(x => x % 2 === 1), map(x => x + x))
  .subscribe(x => console.log(x));

Backwards compatibility for rxjs < 6?

rxjs team released a compatibility package on npm that is pretty much install & play. With this all your rxjs 5.x code should run without any issues. This is especially useful now when most of the dependencies (i.e. modules for Angular) are not yet updated.

Checkout multiple git repos into same Jenkins workspace

Checking out more than one repo at a time in a single workspace is not possible with Jenkins + Git Plugin.

As a workaround, you can either have multiple upstream jobs which checkout a single repo each and then copy to your final project workspace (Problematic on a number of levels), or you can set up a shell scripting step which checks out each needed repo to the job workspace at build time.

Previously the Multiple SCM plugin could help with this issue but it is now deprecated. From the Multiple SCM plugin page: "Users should migrate to https://wiki.jenkins-ci.org/display/JENKINS/Pipeline+Plugin . Pipeline offers a better way of checking out of multiple SCMs, and is supported by the Jenkins core development team."

Upload files from Java client to a HTTP server

click link get example file upload clint java with apache HttpComponents

http://hc.apache.org/httpcomponents-client-ga/httpmime/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java

and library downalod link

https://hc.apache.org/downloads.cgi

use 4.5.3.zip it's working fine in my code

and my working code..

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class ClientMultipartFormPost {

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

          CloseableHttpClient httpclient = HttpClients.createDefault();
          try {
             HttpPost httppost = new HttpPost("http://localhost:8080/MyWebSite1/UploadDownloadFileServlet");

             FileBody bin = new FileBody(new File("E:\\meter.jpg"));
             StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

             HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("bin", bin)
                .addPart("comment", comment)
                .build();


             httppost.setEntity(reqEntity);

             System.out.println("executing request " + httppost.getRequestLine());
             CloseableHttpResponse response = httpclient.execute(httppost);
           try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                     System.out.println("Response content length: " +    resEntity.getContentLength());
                }
              EntityUtils.consume(resEntity);
             } finally {
                 response.close();
            }
       } finally {
          httpclient.close();
      }
   }

}

Laravel Eloquent groupBy() AND also return count of each group

$post = Post::select(DB::raw('count(*) as user_count, category_id'))
              ->groupBy('category_id')
              ->get();

This is an example which results count of post by category.

C# winforms combobox dynamic autocomplete

I Also come across these kind of requirements recently.I set the below properties with out writing the code it works.see if this helps you.

enter image description here

CSS word-wrapping in div

It's pretty hard to say definitively without seeing what the rendered html looks like and what styles are being applied to the elements within the treeview div, but the thing that jumps out at me right away is the

overflow-x: scroll;

What happens if you remove that?

How to place a div below another div?

what about changing the position: relative on your #content #text div to position: absolute

#content #text {
   position:absolute;
   width:950px;
   height:215px;
   color:red;
}

http://jsfiddle.net/CaZY7/12/

then you can use the css properties left and top to position within the #content div

Launch a shell command with in a python script, wait for the termination and return to the script

The os.exec*() functions replace the current programm with the new one. When this programm ends so does your process. You probably want os.system().

Wordpress - Images not showing up in the Media Library

I faced same issue on my wordpress site. After the lot of debugging i fixed my problem step by step like this.

  1. First add given below code your db-config.php
define('SCRIPT_DEBUG', TRUE);
define('WP_DEBUG', TRUE);
define( 'WP_DEBUG_LOG', true );
  1. Then goto /wp-includes/js/wp-util.js files and find the code $.ajax( options ) on line number 100 insert given below code into your file
deferred.jqXHR = $.ajax( options ).done( function( response ) {
  try {
      response = JSON.parse(response);
  } catch (Exception) {
      response = response;
  }

Please check your may be resolved.

  1. if you Removed constant from db-config.php
define('SCRIPT_DEBUG', TRUE);
define('WP_DEBUG', TRUE);
define( 'WP_DEBUG_LOG', true );   
  1. Then compress your /wp-includes/js/wp-util.js file code and put your compressed code into /wp-includes/js/wp-util.min.js

*change your own risk if your update your wordpress version your changed may be lost.

How do I use a char as the case in a switch-case?

Here's an example:

public class Main {

    public static void main(String[] args) {

        double val1 = 100;
        double val2 = 10;
        char operation = 'd';
        double result = 0;

        switch (operation) {

            case 'a':
                result = val1 + val2; break;

            case 's':
                result = val1 - val2; break;
            case 'd':
                if (val2 != 0)
                    result = val1 / val2; break;
            case 'm':
                result = val1 * val2; break;

            default: System.out.println("Not a defined operation");


        }

        System.out.println(result);
    }
}

Replace line break characters with <br /> in ASP.NET MVC Razor view

I prefer this method as it doesn't require manually emitting markup. I use this because I'm rendering Razor Pages to strings and sending them out via email, which is an environment where the white-space styling won't always work.

public static IHtmlContent RenderNewlines<TModel>(this IHtmlHelper<TModel> html, string content)
{
    if (string.IsNullOrEmpty(content) || html is null)
    {
        return null;
    }

    TagBuilder brTag = new TagBuilder("br");
    IHtmlContent br = brTag.RenderSelfClosingTag();
    HtmlContentBuilder htmlContent = new HtmlContentBuilder();

    // JAS: On the off chance a browser is using LF instead of CRLF we strip out CR before splitting on LF.
    string lfContent = content.Replace("\r", string.Empty, StringComparison.InvariantCulture);
    string[] lines = lfContent.Split('\n', StringSplitOptions.None);
    foreach(string line in lines)
    {
        _ = htmlContent.Append(line);
        _ = htmlContent.AppendHtml(br);
    }

    return htmlContent;
}

How do I cast a JSON Object to a TypeScript class?

In TypeScript you can do a type assertion using an interface and generics like so:

var json = Utilities.JSONLoader.loadFromFile("../docs/location_map.json");
var locations: Array<ILocationMap> = JSON.parse(json).location;

Where ILocationMap describes the shape of your data. The advantage of this method is that your JSON could contain more properties but the shape satisfies the conditions of the interface.

However, this does NOT add class instance methods.

How to change colors of a Drawable in Android?

Too late but in case someone need it:

   fun setDrawableColor(drawable: Drawable, color: Int) :Drawable {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            drawable.colorFilter = BlendModeColorFilter(color, BlendMode.SRC_ATOP)
            return drawable
        } else {
            drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
            return drawable
        }
    }

What is the difference between print and puts?

If you would like to output array within string using puts, you will get the same result as if you were using print:

puts "#{[0, 1, nil]}":
[0, 1, nil]

But if not withing a quoted string then yes. The only difference is between new line when we use puts.

What is the common header format of Python files?

Also see PEP 263 if you are using a non-ascii characterset

Abstract

This PEP proposes to introduce a syntax to declare the encoding of a Python source file. The encoding information is then used by the Python parser to interpret the file using the given encoding. Most notably this enhances the interpretation of Unicode literals in the source code and makes it possible to write Unicode literals using e.g. UTF-8 directly in an Unicode aware editor.

Problem

In Python 2.1, Unicode literals can only be written using the Latin-1 based encoding "unicode-escape". This makes the programming environment rather unfriendly to Python users who live and work in non-Latin-1 locales such as many of the Asian countries. Programmers can write their 8-bit strings using the favorite encoding, but are bound to the "unicode-escape" encoding for Unicode literals.

Proposed Solution

I propose to make the Python source code encoding both visible and changeable on a per-source file basis by using a special comment at the top of the file to declare the encoding.

To make Python aware of this encoding declaration a number of concept changes are necessary with respect to the handling of Python source code data.

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given.

To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:

      # coding=<encoding name>

or (using formats recognized by popular editors)

      #!/usr/bin/python
      # -*- coding: <encoding name> -*-

or

      #!/usr/bin/python
      # vim: set fileencoding=<encoding name> :

...

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

I got the same error but from a backend job (SSIS job). Upon checking the database's Log file growth setting, the log file was limited growth of 1GB. So what happened is when the job ran and it asked SQL server to allocate more log space, but the growth limit of the log declined caused the job to failed. I modified the log growth and set it to grow by 50MB and Unlimited Growth and the error went away.

Text in HTML Field to disappear when clicked?

try this one out.

<label for="user">user</label>
<input type="text" name="user" 
onfocus="if(this.value==this.defaultValue)this.value=''"    
onblur="if(this.value=='')this.value=this.defaultValue" 
value="username" maxlength="19" />

hope this helps.

Get underlined text with Markdown

You can wrote **_bold and italic_** and re-style it to underlined text, like this:

strong>em,
em>strong,
b>i,
i>b {
    font-style:normal;
    font-weight:normal;
    text-decoration:underline;
}

- java.lang.NullPointerException - setText on null object reference

The problem is the tv.setText(text). The variable tv is probably null and you call the setText method on that null, which you can't. My guess that the problem is on the findViewById method, but it's not here, so I can't tell more, without the code.

string to string array conversion in java

String array = array of characters ?

Or do you have a string with multiple words each of which should be an array element ?

String[] array = yourString.split(wordSeparator);

Oracle: If Table Exists

declare
   c int;
begin
   select count(*) into c from user_tables where table_name = upper('table_name');
   if c = 1 then
      execute immediate 'drop table table_name';
   end if;
end;

That's for checking whether a table in the current schema exists. For checking whether a given table already exists in a different schema, you'd have to use all_tables instead of user_tables and add the condition all_tables.owner = upper('schema_name')

How to include a class in PHP

Include a class example with the use keyword from Command Line Interface:

PHP Namespaces don't work on the commandline unless you also include or require the php file. When the php file is sitting in the webspace where it is interpreted by the php daemon then you don't need the require line. All you need is the 'use' line.

  1. Create a new directory /home/el/bin

  2. Make a new file called namespace_example.php and put this code in there:

    <?php
        require '/home/el/bin/mylib.php';
        use foobarwhatever\dingdong\penguinclass;
    
        $mypenguin = new penguinclass();
        echo $mypenguin->msg();
    ?>
    
  3. Make another file called mylib.php and put this code in there:

    <?php
    namespace foobarwhatever\dingdong;
    class penguinclass 
    {
        public function msg() {
            return "It's a beautiful day chris, come out and play! " . 
                   "NO!  *SLAM!*  taka taka taka taka."; 
        }   
    }
    ?>   
    
  4. Run it from commandline like this:

    el@apollo:~/bin$ php namespace_example.php 
    
  5. Which prints:

    It's a beautiful day chris, come out and play!
    NO!  *SLAM!*  taka taka taka taka
    

See notes on this in the comments here: http://php.net/manual/en/language.namespaces.importing.php

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

I had the issue the imports for the routing module must come after the child module, this might not be directly related to this post but it would have helped me if I read this:

https://angular.io/guide/router#module-import-order-matters

imports: [
  BrowserModule,
  FormsModule,
  ChildModule,
  AppRoutingModule
],

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.

I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.

  1. Go to the "Manage NuGet Packages"
  2. Select the Installed Package "Microsoft ASP.NET Web API 2.1"
  3. Click Manage and check the projects that I manually added before.

Importing images from a directory (Python) to list or dictionary

from PIL import Image
import os, os.path

imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
    ext = os.path.splitext(f)[1]
    if ext.lower() not in valid_images:
        continue
    imgs.append(Image.open(os.path.join(path,f)))
   

What are DDL and DML?

DDL is Data Definition Language: Just think you are defining the DB. So we use CREATE,ALTER TRUNCATE commands.
DML is after defining we are Manipulating the data. So we use SELECT,INSERT, UPDATE, DELETE command.

Remember DDL commands are auto-committed. You don't need to use COMMIT statements.
DML (Data Manipulation Language) commands need to be commited/rolled back.

How to know if a DateTime is between a DateRange in C#

Usually I create Fowler's Range implementation for such things.

public interface IRange<T>
{
    T Start { get; }
    T End { get; }
    bool Includes(T value);
    bool Includes(IRange<T> range);
}

public class DateRange : IRange<DateTime>         
{
    public DateRange(DateTime start, DateTime end)
    {
        Start = start;
        End = end;
    }

    public DateTime Start { get; private set; }
    public DateTime End { get; private set; }

    public bool Includes(DateTime value)
    {
        return (Start <= value) && (value <= End);
    }

    public bool Includes(IRange<DateTime> range)
    {
        return (Start <= range.Start) && (range.End <= End);
    }
}

Usage is pretty simple:

DateRange range = new DateRange(startDate, endDate);
range.Includes(date)

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

In XML there can be only one root element - you have two - heading and song.

If you restructure to something like:

<?xml version="1.0" encoding="UTF-8"?>
<song> 
 <heading>
 The Twelve Days of Christmas
 </heading>
 ....
</song>

The error about well-formed XML on the root level should disappear (though there may be other issues).

How to wait for a number of threads to complete?

instead of join(), which is an old API, you can use CountDownLatch. I have modified your code as below to fulfil your requirement.

import java.util.concurrent.*;
class DoSomethingInAThread implements Runnable{
    CountDownLatch latch;
    public DoSomethingInAThread(CountDownLatch latch){
        this.latch = latch;
    } 
    public void run() {
        try{
            System.out.println("Do some thing");
            latch.countDown();
        }catch(Exception err){
            err.printStackTrace();
        }
    }
}

public class CountDownLatchDemo {
    public static void main(String[] args) {
        try{
            CountDownLatch latch = new CountDownLatch(1000);
            for (int n=0; n<1000; n++) {
                Thread t = new Thread(new DoSomethingInAThread(latch));
                t.start();
            }
            latch.await();
            System.out.println("In Main thread after completion of 1000 threads");
        }catch(Exception err){
            err.printStackTrace();
        }
    }
}

Explanation:

  1. CountDownLatch has been initialized with given count 1000 as per your requirement.

  2. Each worker thread DoSomethingInAThread will decrement the CountDownLatch, which has been passed in constructor.

  3. Main thread CountDownLatchDemo await() till the count has become zero. Once the count has become zero, you will get below line in output.

    In Main thread after completion of 1000 threads
    

More info from oracle documentation page

public void await()
           throws InterruptedException

Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted.

Refer to related SE question for other options:

wait until all threads finish their work in java

JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?

If you came here searching OpenID Connect (OIDC): OAuth 2.0 != OIDC

I recognize that this is tagged for oauth 2.0 and NOT OIDC, however there is frequently a conflation between the 2 standards since both standards can use JWTs and the aud claim. And one (OIDC) is basically an extension of the other (OAUTH 2.0). (I stumbled across this question looking for OIDC myself.)

OAuth 2.0 Access Tokens##

For OAuth 2.0 Access tokens, existing answers pretty well cover it. Additionally here is one relevant section from OAuth 2.0 Framework (RFC 6749)

For public clients using implicit flows, this specification does not provide any method for the client to determine what client an access token was issued to.
...
Authenticating resource owners to clients is out of scope for this specification. Any specification that uses the authorization process as a form of delegated end-user authentication to the client (e.g., third-party sign-in service) MUST NOT use the implicit flow without additional security mechanisms that would enable the client to determine if the access token was issued for its use (e.g., audience- restricting the access token).

OIDC ID Tokens##

OIDC has ID Tokens in addition to Access tokens. The OIDC spec is explicit on the use of the aud claim in ID Tokens. (openid-connect-core-1.0)

aud
REQUIRED. Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 client_id of the Relying Party as an audience value. It MAY also contain identifiers for other audiences. In the general case, the aud value is an array of case sensitive strings. In the common special case when there is one audience, the aud value MAY be a single case sensitive string.

furthermore OIDC specifies the azp claim that is used in conjunction with aud when aud has more than one value.

azp
OPTIONAL. Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value.

SQL Server - copy stored procedures from one db to another

I originally found this post looking for a solution to copying stored procedures from my remote production database to my local development database. After success using the suggested approach in this thread, I realized I grew increasingly lazy (or resourceful, whichever you prefer) and wanted this to be automated. I came across this link, which proved to be very helpful (thank you vincpa), and I extended upon it, resulting in the following file (schema_backup.ps1):

$server             = "servername"
$database           = "databaseName"
$output_path        = "D:\prod_schema_backup"
$login = "username"
$password = "password"

$schema             = "dbo"
$table_path         = "$output_path\table\"
$storedProcs_path   = "$output_path\stp\"
$views_path         = "$output_path\view\"
$udfs_path          = "$output_path\udf\"
$textCatalog_path   = "$output_path\fulltextcat\"
$udtts_path         = "$output_path\udtt\"

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo")  | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended")  | out-null
$srvConn = new-object Microsoft.SqlServer.Management.Common.ServerConnection
$srvConn.ServerInstance = $server
$srvConn.LoginSecure = $false
$srvConn.Login = $login
$srvConn.Password = $password
$srv        = New-Object Microsoft.SqlServer.Management.SMO.Server($srvConn)
$db         = New-Object ("Microsoft.SqlServer.Management.SMO.Database")
$tbl        = New-Object ("Microsoft.SqlServer.Management.SMO.Table")
$scripter   = New-Object Microsoft.SqlServer.Management.SMO.Scripter($srvConn)

# Get the database and table objects
$db = $srv.Databases[$database]

$tbl            = $db.tables | Where-object { $_.schema -eq $schema  -and -not $_.IsSystemObject } 
$storedProcs    = $db.StoredProcedures | Where-object { $_.schema -eq $schema -and -not $_.IsSystemObject } 
$views          = $db.Views | Where-object { $_.schema -eq $schema } 
$udfs           = $db.UserDefinedFunctions | Where-object { $_.schema -eq $schema -and -not $_.IsSystemObject } 
$catlog         = $db.FullTextCatalogs
$udtts          = $db.UserDefinedTableTypes | Where-object { $_.schema -eq $schema } 

# Set scripter options to ensure only data is scripted
$scripter.Options.ScriptSchema  = $true;
$scripter.Options.ScriptData    = $false;

#Exclude GOs after every line
$scripter.Options.NoCommandTerminator   = $false;
$scripter.Options.ToFileOnly            = $true
$scripter.Options.AllowSystemObjects    = $false
$scripter.Options.Permissions           = $true
$scripter.Options.DriAllConstraints     = $true
$scripter.Options.SchemaQualify         = $true
$scripter.Options.AnsiFile              = $true

$scripter.Options.SchemaQualifyForeignKeysReferences = $true

$scripter.Options.Indexes               = $true
$scripter.Options.DriIndexes            = $true
$scripter.Options.DriClustered          = $true
$scripter.Options.DriNonClustered       = $true
$scripter.Options.NonClusteredIndexes   = $true
$scripter.Options.ClusteredIndexes      = $true
$scripter.Options.FullTextIndexes       = $true

$scripter.Options.EnforceScriptingOptions   = $true

function CopyObjectsToFiles($objects, $outDir) {
    #clear out before 
    Remove-Item $outDir* -Force -Recurse
    if (-not (Test-Path $outDir)) {
        [System.IO.Directory]::CreateDirectory($outDir)
    }   

    foreach ($o in $objects) { 

        if ($o -ne $null) {

            $schemaPrefix = ""

            if ($o.Schema -ne $null -and $o.Schema -ne "") {
                $schemaPrefix = $o.Schema + "."
            }

            #removed the next line so I can use the filename to drop the stored proc 
            #on the destination and recreate it
            #$scripter.Options.FileName = $outDir + $schemaPrefix + $o.Name + ".sql"
            $scripter.Options.FileName = $outDir + $schemaPrefix + $o.Name
            Write-Host "Writing " $scripter.Options.FileName
            $scripter.EnumScript($o)
        }
    }
}

# Output the scripts
CopyObjectsToFiles $tbl $table_path
CopyObjectsToFiles $storedProcs $storedProcs_path
CopyObjectsToFiles $views $views_path
CopyObjectsToFiles $catlog $textCatalog_path
CopyObjectsToFiles $udtts $udtts_path
CopyObjectsToFiles $udfs $udfs_path

Write-Host "Finished at" (Get-Date)
$srv.ConnectionContext.Disconnect()

I have a .bat file that calls this, and is called from Task Scheduler. After the call to the Powershell file, I have:

for /f %f in ('dir /b d:\prod_schema_backup\stp\') do sqlcmd /S localhost /d dest_db /Q "DROP PROCEDURE %f"

That line will go thru the directory and drop the procedures it is going to recreate. If this wasn't a development environment, I would not like programmatically dropping procedures this way. I then rename all the stored procedure files to have .sql:

powershell Dir d:\prod_schema_backup\stp\ | Rename-Item -NewName { $_.name + ".sql" }

And then run:

for /f %f in ('dir /b d:\prod_schema_backup\stp\') do sqlcmd /S localhost /d dest_db /E /i "%f".sql

And that iterates through all the .sql files and recreates the stored procedures. I hope that any part of this will prove to be helpful to someone.

Vector of Vectors to create matrix

What you have initialized is a vector of vectors, so you definitely have to include a vector to be inserted("Pushed" in the terminology of vectors) in the original vector you have named matrix in your example.

One more thing, you cannot directly insert values in the vector using the operator "cin". Use a variable which takes input and then insert the same in the vector.

Please try this out :

int num;
for(int i=0; i<RR; i++){

      vector<int>inter_mat;       //Intermediate matrix to help insert(push) contents of whole row at a time

      for(int j=0; j<CC; j++){
           cin>>num;             //Extra variable in helping push our number to vector
           vin.push_back(num);   //Inserting numbers in a row, one by one 
          }

      v.push_back(vin);          //Inserting the whole row at once to original 2D matrix 
}

Best way to log POST data in Apache?

You can also use the built-in forensic log feature.

In Java, should I escape a single quotation mark (') in String (double quoted)?

It's best practice only to escape the quotes when you need to - if you can get away without escaping it, then do!

The only times you should need to escape are when trying to put " inside a string, or ' in a character:

String quotes = "He said \"Hello, World!\"";
char quote = '\'';

Remove all items from a FormArray in Angular

Update: Angular 8 finally got method to clear the Array FormArray.clear()

Right way to convert data.frame to a numeric matrix, when df also contains strings?

I manually filled NAs by exporting the CSV then editing it and reimporting, as below.

Perhaps one of you experts might explain why this procedure worked so well (the first file had columns with data of types char, INT and num (floating point numbers)), which all became char type after STEP 1; but at the end of STEP 3 R correctly recognized the datatype of each column).

# STEP 1:
MainOptionFile <- read.csv("XLUopt_XLUstk_v3.csv",
                            header=T, stringsAsFactors=FALSE)
#... STEP 2:
TestFrame <- subset(MainOptionFile, str_locate(option_symbol,"120616P00034000") > 0)
write.csv(TestFrame, file = "TestFrame2.csv")
# ...
# STEP 3:
# I made various amendments to `TestFrame2.csv`, including replacing all missing data cells with appropriate numbers. I then read that amended data frame back into R as follows:    
XLU_34P_16Jun12 <- read.csv("TestFrame2_v2.csv",
                            header=T,stringsAsFactors=FALSE)

On arrival back in R, all columns had their correct measurement levels automatically recognized by R!

jQuery hover and class selector

I would suggest not to use JavaScript for this kind of simple interaction. CSS is capable of doing it (even in Internet Explorer 6) and it will be much more responsive than doing it with JavaScript.

You can use the ":hover" CSS pseudo-class but in order to make it work with Internet Explorer 6, you must use it on an "a" element.

.menuItem
{
    display: inline;
    background-color: #000;

    /* width and height should not work on inline elements */
    /* if this works, your browser is doing the rendering  */
    /* in quirks mode which will not be compatible with    */
    /* other browsers - but this will not work on touch mobile devices like android */

}
.menuItem a:hover 
{
    background-color:#F00;
}

Create thumbnail image

You have to use GetThumbnailImage method in the Image class:

https://msdn.microsoft.com/en-us/library/8t23aykb%28v=vs.110%29.aspx

Here's a rough example that takes an image file and makes a thumbnail image from it, then saves it back to disk.

Image image = Image.FromFile(fileName);
Image thumb = image.GetThumbnailImage(120, 120, ()=>false, IntPtr.Zero);
thumb.Save(Path.ChangeExtension(fileName, "thumb"));

It is in the System.Drawing namespace (in System.Drawing.dll).

Behavior:

If the Image contains an embedded thumbnail image, this method retrieves the embedded thumbnail and scales it to the requested size. If the Image does not contain an embedded thumbnail image, this method creates a thumbnail image by scaling the main image.


Important: the remarks section of the Microsoft link above warns of certain potential problems:

The GetThumbnailImage method works well when the requested thumbnail image has a size of about 120 x 120 pixels. If you request a large thumbnail image (for example, 300 x 300) from an Image that has an embedded thumbnail, there could be a noticeable loss of quality in the thumbnail image.

It might be better to scale the main image (instead of scaling the embedded thumbnail) by calling the DrawImage method.

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

NUMBER (precision, scale) means precision number of total digits, of which scale digits are right of the decimal point.

NUMBER(2,2) in other words means a number with 2 digits, both of which are decimals. You may mean to use NUMBER(4,2) to get 4 digits, of which 2 are decimals. Currently you can just insert values with a zero integer part.

More info at the Oracle docs.

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

we had similar header issue with Amazon (AWS) S3 presigned Post failing on some browsers.

point was to tell bucket CORS to expose header <ExposeHeader>Access-Control-Allow-Origin</ExposeHeader>

more details in this answer: https://stackoverflow.com/a/37465080/473040

Eloquent ->first() if ->exists()

An answer has already been accepted, but in these situations, a more elegant solution in my opinion would be to use error handling.

    try {
        $user = User::where('mobile', Input::get('mobile'))->first();
    } catch (ErrorException $e) {
        // Do stuff here that you need to do if it doesn't exist.
        return View::make('some.view')->with('msg', $e->getMessage());
    }

How to define an empty object in PHP

In addition to zombat's answer if you keep forgetting stdClass

   function object(){

        return new stdClass();

    }

Now you can do:

$str='';
$array=array();
$object=object();

Call a function from another file?

If your file is in the different package structure and you want to call it from a different package, then you can call it in that fashion:

Let's say you have following package structure in your python project:

Python package and file structure

in - com.my.func.DifferentFunction python file you have some function, like:

def add(arg1, arg2):
    return arg1 + arg2

def sub(arg1, arg2) :
    return arg1 - arg2

def mul(arg1, arg2) :
    return arg1 * arg2

And you want to call different functions from Example3.py, then following way you can do it:

Define import statement in Example3.py - file for import all function

from com.my.func.DifferentFunction import *

or define each function name which you want to import

from com.my.func.DifferentFunction import add, sub, mul

Then in Example3.py you can call function for execute:

num1 = 20
num2 = 10

print("\n add : ", add(num1,num2))
print("\n sub : ", sub(num1,num2))
print("\n mul : ", mul(num1,num2))

Output:

 add :  30

 sub :  10

 mul :  200

JavaScript null check

In your case use data==null (which is true ONLY for null and undefined - on second picture focus on rows/columns null-undefined)

_x000D_
_x000D_
function test(data) {_x000D_
    if (data != null) {_x000D_
        console.log('Data: ', data);_x000D_
    }_x000D_
}_x000D_
_x000D_
test();          // the data=undefined_x000D_
test(null);      // the data=null_x000D_
test(undefined); // the data=undefined_x000D_
_x000D_
test(0); _x000D_
test(false); _x000D_
test('something');
_x000D_
_x000D_
_x000D_

Here you have all (src):

if

enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here

Python timedelta in years

this function returns the difference in years between two dates (taken as strings in ISO format, but it can easily modified to take in any format)

import time
def years(earlydateiso,  laterdateiso):
    """difference in years between two dates in ISO format"""

    ed =  time.strptime(earlydateiso, "%Y-%m-%d")
    ld =  time.strptime(laterdateiso, "%Y-%m-%d")
    #switch dates if needed
    if  ld < ed:
        ld,  ed = ed,  ld            

    res = ld[0] - ed [0]
    if res > 0:
        if ld[1]< ed[1]:
            res -= 1
        elif  ld[1] == ed[1]:
            if ld[2]< ed[2]:
                res -= 1
    return res

Insert data into hive table

If you already have a table pre_loaded_tbl with some data. You can use a trick to load the data into your table with following query

INSERT INTO TABLE tweet_table 
  SELECT  "my_data" AS my_column 
    FROM   pre_loaded_tbl 
   LIMIT   5;

Also please note that "my_data" is independent of any data in the pre_loaded_tbl. You can select any data and write any column name (here my_data and my_column). Hive does not require it to have same column name. However structure of select statement should be same as that of your tweet_table. You can use limit to determine how many times you can insert into the tweet_table.

However if you haven't' created any table, you will have to load the data using file copy or load data commands in above answers.

Pass multiple parameters to rest API - Spring

(1) Is it possible to pass a JSON object to the url like in Ex.2?

No, because http://localhost:8080/api/v1/mno/objectKey/{"id":1, "name":"Saif"} is not a valid URL.

If you want to do it the RESTful way, use http://localhost:8080/api/v1/mno/objectKey/1/Saif, and defined your method like this:

@RequestMapping(path = "/mno/objectKey/{id}/{name}", method = RequestMethod.GET)
public Book getBook(@PathVariable int id, @PathVariable String name) {
    // code here
}

(2) How can we pass and parse the parameters in Ex.1?

Just add two request parameters, and give the correct path.

@RequestMapping(path = "/mno/objectKey", method = RequestMethod.GET)
public Book getBook(@RequestParam int id, @RequestParam String name) {
    // code here
}

UPDATE (from comment)

What if we have a complicated parameter structure ?

"A": [ {
    "B": 37181,
    "timestamp": 1160100436,
    "categories": [ {
        "categoryID": 2653,
        "timestamp": 1158555774
    }, {
        "categoryID": 4453,
        "timestamp": 1158555774
    } ]
} ]

Send that as a POST with the JSON data in the request body, not in the URL, and specify a content type of application/json.

@RequestMapping(path = "/mno/objectKey", method = RequestMethod.POST, consumes = "application/json")
public Book getBook(@RequestBody ObjectKey objectKey) {
    // code here
}

How to commit a change with both "message" and "description" from the command line?

In case you want to improve the commit message with header and body after you created the commit, you can reword it. This approach is more useful because you know what the code does only after you wrote it.

git rebase -i origin/master

Then, your commits will appear:

pick e152ce2 Update framework
pick ffcf91e Some magic
pick fa672e1 Update comments

Select the commit you want to reword and save.

pick e152ce2 Update framework
reword ffcf91e Some magic
pick fa672e1 Update comments

Now, you have the opportunity to add header and body, where the first line will be the header.

Create perpetuum mobile

Redesign laws of physics with a pinch of imagination. Open a wormhole in 23 dimensions. Add protection to avoid high instability.

Apache won't follow symlinks (403 Forbidden)

I was having a similar problem that I could not resolve for a long time on my new server. In addition to palacsint's answer, a good question to ask is: are you using Apache 2.4? In Apache 2.4 there is a different mechanism for setting the permissions that do not work when done using the above configuration, so I used the solution explained in this blog post.

Basically, what I needed to do was convert my config file from:

Alias /demo /usr/demo/html

<Directory "/usr/demo/html">
    Options FollowSymLinks
    AllowOverride None
    Order allow,deny
    allow from all

</Directory>

to:

Alias /demo /usr/demo/html

<Directory "/usr/demo/html">
    Options FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

Note how the Order and allow lines have been replaced by Require all granted

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

Close Form Button Event

This should handle cases of clicking on [x] or ALT+F4

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   if (e.CloseReason == CloseReason.UserClosing)
   {
      DialogResult result = MessageBox.Show("Do you really want to exit?", "Dialog Title", MessageBoxButtons.YesNo);
      if (result == DialogResult.Yes)
      {
          Environment.Exit(0);
      }
      else 
      {
         e.Cancel = true;
      }
   }
   else
   {
      e.Cancel = true;
   }
}   

How to display line numbers in 'less' (GNU)

From the manual:

-N or --LINE-NUMBERS Causes a line number to be displayed at the beginning of each line in the display.

You can also toggle line numbers without quitting less by typing -N.

It is possible to toggle any of less's command line options in this way.

Greyscale Background Css Images

I know it's a really old question, but it's the first result on duckduckgo, so I wanted to share what I think it's a better and more modern solution.

You can use background-blend-mode property to achieve a greyscale image:

#something {
  background-color: #fff;
  background-image: url("yourimage");
  background-blend-mode: luminosity;
}

If you want to remove the effect, just change the blend-mode to initial.

You may need to play a little bit with the background-color if this element is over something with a background. What I've found is that the greyscale does not depend on the actual color but on the alpha value. So, if you have a blue background on the parent, set the same background on #something.

You can also use two images, one with color and the other without and set both as background and play with other blend modes.

https://www.w3schools.com/cssref/pr_background-blend-mode.asp

It won't work on Edge though.

EDIT: I've miss the "fade" part of the question.

If you wan't to make it fade from/to grayscale, you can use a css transition on the background color changeing it's alpha value:

#something {
  background-color: rgba(255,255,255,1);
  background-image: url("yourimage");
  background-blend-mode: luminosity;
  transition: background-color 1s ease-out;
}
#something:hover {
  background-color: rgba(255,255,255,0);
}

I'm also adding a codepen example for completeness https://codepen.io/anon/pen/OBKKVZ

Exporting results of a Mysql query to excel?

The typical way to achieve this is to export to CSV and then load the CSV into Excel.
You can using any MySQL command line tool to do this by including the INTO OUTFILE clause on your SELECT statement:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'file.csv'
FIELDS TERMINATED BY ','

See this link for detailed options.

Alternatively, you can use mysqldump to store dump into a separated value format using the --tab option, see this link.

mysqldump -u<user> -p<password> -h<host> --where=jtaskResult=2429 --tab=<file.csv> <database> TaskResult

Hint: If you don't specify an absoulte path but use something like INTO OUTFILE 'output.csv' or INTO OUTFILE './output.csv', it will store the output file to the directory specified by show variables like 'datadir';.

invalid new-expression of abstract class type

If you use C++11, you can use the specifier "override", and it will give you a compiler error if your aren't correctly overriding an abstract method. You probably have a method that doesn't match exactly with an abstract method in the base class, so your aren't actually overriding it.

http://en.cppreference.com/w/cpp/language/override

Display back button on action bar

Try this code, considers it only if you need the back button.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //YOUR CODE
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    //YOUR CODE
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    onBackPressed();
    return true;
}

pandas dataframe columns scaling with sklearn

I know it's a very old comment, but still:

Instead of using single bracket (dfTest['A']), use double brackets (dfTest[['A']]).

i.e: min_max_scaler.fit_transform(dfTest[['A']]).

I believe this will give the desired result.

Easier way to create circle div than using an image?

For circle, create a div element and then enter width = 2 times of the border radius = 2 times padding. Also line-height = 0 For example, with 50px as radii of the circle, the below code works well:

width: 100px;
padding: 50px 0;
border: solid;
line-height: 0px;
border-radius: 50px;

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

Take a look at this WPF metro-styled window with optional glowing borders.

This is a stand-alone application using no other libraries than Microsoft.Windows.Shell (included) to create metro-styled windows with optional glowing borders.

Supports Windows all the way back to XP (.NET4).

How can I install Python's pip3 on my Mac?

To install or upgrade pip, download get-pip.py from the official site. Then run the following command:

sudo python get-pip.py 

and it will install pip for your python version which runs the script.

Convert file to byte array and vice versa

You can't do this. A File is just an abstract way to refer to a file in the file system. It doesn't contain any of the file contents itself.

If you're trying to create an in-memory file that can be referred to using a File object, you aren't going to be able to do that, either, as explained in this thread, this thread, and many other places..

Get a file name from a path

For long time I was looking for a function able to properly decompose file path. For me this code is working perfectly for both Linux and Windows.

void decomposePath(const char *filePath, char *fileDir, char *fileName, char *fileExt)
{
    #if defined _WIN32
        const char *lastSeparator = strrchr(filePath, '\\');
    #else
        const char *lastSeparator = strrchr(filePath, '/');
    #endif

    const char *lastDot = strrchr(filePath, '.');
    const char *endOfPath = filePath + strlen(filePath);
    const char *startOfName = lastSeparator ? lastSeparator + 1 : filePath;
    const char *startOfExt = lastDot > startOfName ? lastDot : endOfPath;

    if(fileDir)
        _snprintf(fileDir, MAX_PATH, "%.*s", startOfName - filePath, filePath);

    if(fileName)
        _snprintf(fileName, MAX_PATH, "%.*s", startOfExt - startOfName, startOfName);

    if(fileExt)
        _snprintf(fileExt, MAX_PATH, "%s", startOfExt);
}

Example results are:

[]
  fileDir:  ''
  fileName: ''
  fileExt:  ''

[.htaccess]
  fileDir:  ''
  fileName: '.htaccess'
  fileExt:  ''

[a.exe]
  fileDir:  ''
  fileName: 'a'
  fileExt:  '.exe'

[a\b.c]
  fileDir:  'a\'
  fileName: 'b'
  fileExt:  '.c'

[git-archive]
  fileDir:  ''
  fileName: 'git-archive'
  fileExt:  ''

[git-archive.exe]
  fileDir:  ''
  fileName: 'git-archive'
  fileExt:  '.exe'

[D:\Git\mingw64\libexec\git-core\.htaccess]
  fileDir:  'D:\Git\mingw64\libexec\git-core\'
  fileName: '.htaccess'
  fileExt:  ''

[D:\Git\mingw64\libexec\git-core\a.exe]
  fileDir:  'D:\Git\mingw64\libexec\git-core\'
  fileName: 'a'
  fileExt:  '.exe'

[D:\Git\mingw64\libexec\git-core\git-archive.exe]
  fileDir:  'D:\Git\mingw64\libexec\git-core\'
  fileName: 'git-archive'
  fileExt:  '.exe'

[D:\Git\mingw64\libexec\git.core\git-archive.exe]
  fileDir:  'D:\Git\mingw64\libexec\git.core\'
  fileName: 'git-archive'
  fileExt:  '.exe'

[D:\Git\mingw64\libexec\git-core\git-archiveexe]
  fileDir:  'D:\Git\mingw64\libexec\git-core\'
  fileName: 'git-archiveexe'
  fileExt:  ''

[D:\Git\mingw64\libexec\git.core\git-archiveexe]
  fileDir:  'D:\Git\mingw64\libexec\git.core\'
  fileName: 'git-archiveexe'
  fileExt:  ''

I hope this helps you also :)

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

Flatten List in LINQ

With query syntax:

var values =
from inner in outer
from value in inner
select value;

How do I move a file (or folder) from one folder to another in TortoiseSVN?

If you want to move files around and keep the csproj files up to date, the easiest way is to use a Visual Studio plugin like AnkhSVN. That will automatically commit both the move action (as an delete + add with history, because that's how Subversion works) and a change in the .csproj

Django Cookies, how can I set them?

You could manually set the cookie, but depending on your use case (and if you might want to add more types of persistent/session data in future) it might make more sense to use Django's sessions feature. This will let you get and set variables tied internally to the user's session cookie. Cool thing about this is that if you want to store a lot of data tied to a user's session, storing it all in cookies will add a lot of weight to HTTP requests and responses. With sessions the session cookie is all that is sent back and forth (though there is the overhead on Django's end of storing the session data to keep in mind).

python's re: return True if string contains regex pattern

Here's a function that does what you want:

import re

def is_match(regex, text):
    pattern = re.compile(regex, text)
    return pattern.search(text) is not None

The regular expression search method returns an object on success and None if the pattern is not found in the string. With that in mind, we return True as long as the search gives us something back.

Examples:

>>> is_match('ba[rzd]', 'foobar')
True
>>> is_match('ba[zrd]', 'foobaz')
True
>>> is_match('ba[zrd]', 'foobad')
True
>>> is_match('ba[zrd]', 'foobam')
False

c++ exception : throwing std::string

Simplest way to throw an Exception in C++:

#include <iostream>
using namespace std;
void purturb(){
    throw "Cannot purturb at this time.";
}
int main() {
    try{
        purturb();
    }
    catch(const char* msg){
        cout << "We caught a message: " << msg << endl;
    }
    cout << "done";
    return 0;
}

This prints:

We caught a message: Cannot purturb at this time.
done

If you catch the thrown exception, the exception is contained and the program will ontinue. If you do not catch the exception, then the program exists and prints:

This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.

In Objective-C, how do I test the object type?

Simple, [yourobject class] it will return the class name of yourobject.

How to update an "array of objects" with Firestore?

Edit 08/13/2018: There is now support for native array operations in Cloud Firestore. See Doug's answer below.


There is currently no way to update a single array element (or add/remove a single element) in Cloud Firestore.

This code here:

firebase.firestore()
.collection('proprietary')
.doc(docID)
.set(
  { sharedWith: [{ who: "[email protected]", when: new Date() }] },
  { merge: true }
)

This says to set the document at proprietary/docID such that sharedWith = [{ who: "[email protected]", when: new Date() } but to not affect any existing document properties. It's very similar to the update() call you provided however the set() call with create the document if it does not exist while the update() call will fail.

So you have two options to achieve what you want.

Option 1 - Set the whole array

Call set() with the entire contents of the array, which will require reading the current data from the DB first. If you're concerned about concurrent updates you can do all of this in a transaction.

Option 2 - Use a subcollection

You could make sharedWith a subcollection of the main document. Then adding a single item would look like this:

firebase.firestore()
  .collection('proprietary')
  .doc(docID)
  .collection('sharedWith')
  .add({ who: "[email protected]", when: new Date() })

Of course this comes with new limitations. You would not be able to query documents based on who they are shared with, nor would you be able to get the doc and all of the sharedWith data in a single operation.

Malformed String ValueError ast.literal_eval() with String representation of Tuple

I know this is an old question, but I think found a very simple answer, in case anybody needs it.

If you put string quotes inside your string ("'hello'"), ast_literaleval() will understand it perfectly.

You can use a simple function:

    def doubleStringify(a):
        b = "\'" + a + "\'"
        return b

Or probably more suitable for this example:

    def perfectEval(anonstring):
        try:
            ev = ast.literal_eval(anonstring)
            return ev
        except ValueError:
            corrected = "\'" + anonstring + "\'"
            ev = ast.literal_eval(corrected)
            return ev

In Android EditText, how to force writing uppercase?

You should put android:inputType="textCapCharacters" with Edittext in xml file.

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

Reloading the page gives wrong GET request with AngularJS HTML5 mode

I'm answering this question from the larger question:

When I add $locationProvider.html5Mode(true), my site will not allow pasting of urls. How do I configure my server to work when html5Mode is true?

When you have html5Mode enabled, the # character will no longer be used in your urls. The # symbol is useful because it requires no server side configuration. Without #, the url looks much nicer, but it also requires server side rewrites. Here are some examples:

For Express Rewrites with AngularJS, you can solve this with the following updates:

app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/app/views/index.html'));
});

and

<!-- FOR ANGULAR ROUTING -->
<base href="/">

and

app.use('/',express.static(__dirname + '/public'));

Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use

How to kill a windows service using PID -

  1. open command prompt and type netstat -ano
  2. find the PID of the ports which are in used, in this case, it will be 8080, 8005,8009. Let's say PID of these ports are 5760.
  3. Now Type taskkill /f /pid 5760
  4. it will close the PID and ports will be available for use. Now you can start tomcat as normal by Windows services or by eclipse itself.

Thanks

kill a Windows service that's stuck on stopping or starting

Finding square root without using sqrt function?

As I found this question is old and have many answers but I have an answer which is simple and working great..

#define EPSILON 0.0000001 // least minimum value for comparison
double SquareRoot(double _val) {
    double low = 0; 
    double high = _val;
    double mid = 0; 

    while (high - low > EPSILON) {
            mid = low + (high - low) / 2; // finding mid value
            if (mid*mid > _val) {
                high = mid;
            } else {
                low = mid;
            }    
    }   
    return mid;
}

I hope it will be helpful for future users.

Can constructors throw exceptions in Java?

Yes, they can throw exceptions. If so, they will only be partially initialized and if non-final, subject to attack.

The following is from the Secure Coding Guidelines 2.0.

Partially initialized instances of a non-final class can be accessed via a finalizer attack. The attacker overrides the protected finalize method in a subclass, and attempts to create a new instance of that subclass. This attempt fails (in the above example, the SecurityManager check in ClassLoader's constructor throws a security exception), but the attacker simply ignores any exception and waits for the virtual machine to perform finalization on the partially initialized object. When that occurs the malicious finalize method implementation is invoked, giving the attacker access to this, a reference to the object being finalized. Although the object is only partially initialized, the attacker can still invoke methods on it (thereby circumventing the SecurityManager check).

What is the meaning of "this" in Java?

Quoting an article at programming.guide:


this has two uses in a Java program.

1. As a reference to the current object

The syntax in this case usually looks something like

this.someVariable = someVariable;

This type of use is described here: The 'this' reference (with examples)

2. To call a different constructor

The syntax in this case typically looks something like

MyClass() {
    this(DEFAULT_VALUE); // delegate to other constructor
}

MyClass(int value) {
    // ...
}

This type of use is described here: this(…) constructor call (with examples)

Prevent div from moving while resizing the page

1 - remove the margin from your BODY CSS.

2 - wrap all of your html in a wrapper <div id="wrapper"> ... all your body content </div>

3 - Define the CSS for the wrapper:

This will hold everything together, centered on the page.

#wrapper {
    margin-left:auto;
    margin-right:auto;
    width:960px;
}

TypeError: unsupported operand type(s) for -: 'str' and 'int'

  1. The reason this is failing is because (Python 3) input returns a string. To convert it to an integer, use int(some_string).

  2. You do not typically keep track of indices manually in Python. A better way to implement such a function would be

    def cat_n_times(s, n):
        for i in range(n):
            print(s) 
    
    text = input("What would you like the computer to repeat back to you: ")
    num = int(input("How many times: ")) # Convert to an int immediately.
    
    cat_n_times(text, num)
    
  3. I changed your API above a bit. It seems to me that n should be the number of times and s should be the string.

When to use margin vs padding in CSS

From https://www.w3schools.com/css/css_boxmodel.asp

Explanation of the different parts:

  • Content - The content of the box, where text and images appear

  • Padding - Clears an area around the content. The padding is transparent

  • Border - A border that goes around the padding and content

  • Margin - Clears an area outside the border. The margin is transparent

Illustration of CSS box model

Live example (play around by changing the values): https://www.w3schools.com/css/tryit.asp?filename=trycss_boxmodel

How to get a Char from an ASCII Character Code in c#

Two options:

char c1 = '\u0001';
char c1 = (char) 1;

What is C# analog of C++ std::pair?

Unfortunately, there is none. You can use the System.Collections.Generic.KeyValuePair<K, V> in many situations.

Alternatively, you can use anonymous types to handle tuples, at least locally:

var x = new { First = "x", Second = 42 };

The last alternative is to create an own class.

Elasticsearch query to return all records

size param increases the hits displayed from from the default(10) to 500.

http://localhost:9200/[indexName]/_search?pretty=true&size=500&q=*:*

Change the from step by step to get all the data.

http://localhost:9200/[indexName]/_search?size=500&from=0

TCPDF not render all CSS properties

In the first place, you should note that PDF and HTML and different formats that hardly have anything in common. If TCPDF allows you to provide input data using HTML and CSS it's because it implements a simple parser for these two languages and tries to figure out how to translate that into PDF. So it's logical that TCPDF only supports a little subset of the HTML and CSS specification and, even in supported stuff, it's probably not as perfect as in first class web browsers.

Said that, the question is: what's supported and what's not? The documentation basically skips the issue and let's you enjoy the trial and error method.

Having a look at the source code, we can see there's a protected method called TCPDF::getHtmlDomArray() that, among other things, parses CSS declarations. I can see stuff like font-family, list-style-type or text-indent but there's no margin or padding as far as I can see and, definitively, there's no float at all.

To sum up: with TCPDF, you can use CSS for some basic formatting. If you need to convert from HTML to PDF, it's the wrong tool. (If that's the case, may I suggest wkhtmltopdf?)

Numpy AttributeError: 'float' object has no attribute 'exp'

You convert type np.dot(X, T) to float32 like this:

z=np.array(np.dot(X, T),dtype=np.float32)

def sigmoid(X, T):
    return (1.0 / (1.0 + np.exp(-z)))

Hopefully it will finally work!

How to restore PostgreSQL dump file into Postgres databases?

You might need to set permissions at the database level that allows your schema owner to restore the dump.

NPM: npm-cli.js not found when running npm

Copy the directory named npm from your installed node path (In my case the npm directory was available in C:\Program Files\nodejs\node_modules).

Navigate to C:\Users\%USERNAME%\AppData\Roaming\npm\node_modules and paste the copied npm directory there.

This method worked for me when I had the same error. . .

How to get the cell value by column name not by index in GridView in asp.net

Although its a long time but this relatively small piece of code seems easy to read and get:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
   int index;
   string cellContent;

    foreach (TableCell tc in ((GridView)sender).HeaderRow.Cells)
    {
       if( tc.Text.Equals("yourColumnName") )
       {
         index = ((GridView)sender).HeaderRow.Cells.GetCellIndex(tc);
         cellContent = ((GridView)sender).SelectedRow.Cells[index].Text;
         break;
       }
    }
}

intellij idea - Error: java: invalid source release 1.9

In Project Structure in Project SDK: modify SDK to 11 or higher and in Project language level: modify to 11 - Local variable syntax for lambda parameters

Change header background color of modal of twitter bootstrap

The corners are actually in .modal-content

So you may try this:

.modal-content {
  background-color: #0480be;
}
.modal-body {
  background-color: #fff;
}

If you change the color of the header or footer, the rounded corners will be drawn over.

Javascript counting number of objects in object

In recent browsers you can use:

Object.keys(obj.Data).length

See MDN

For older browsers, use the for-in loop in Michael Geary's answer.

HTTP POST and GET using cURL in Linux

*nix provides a nice little command which makes our lives a lot easier.

GET:

with JSON:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource

with XML:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource

POST:

For posting data:

curl --data "param1=value1&param2=value2" http://hostname/resource

For file upload:

curl --form "[email protected]" http://hostname/resource

RESTful HTTP Post:

curl -X POST -d @filename http://hostname/resource

For logging into a site (auth):

curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/

Pretty-printing the curl results:

For JSON:

If you use npm and nodejs, you can install json package by running this command:

npm install -g json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json

If you use pip and python, you can install pjson package by running this command:

pip install pjson

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson

If you use Python 2.6+, json tool is bundled within.

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool

If you use gem and ruby, you can install colorful_json package by running this command:

gem install colorful_json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson

If you use apt-get (aptitude package manager of your Linux distro), you can install yajl-tools package by running this command:

sudo apt-get install yajl-tools

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource |  json_reformat

For XML:

If you use *nix with Debian/Gnome envrionment, install libxml2-utils:

sudo apt-get install libxml2-utils

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format -

or install tidy:

sudo apt-get install tidy

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i -

Saving the curl response to a file

curl http://hostname/resource >> /path/to/your/file

or

curl http://hostname/resource -o /path/to/your/file

For detailed description of the curl command, hit:

man curl

For details about options/switches of the curl command, hit:

curl -h

Selecting last element in JavaScript array

var arr = [1, 2, 3];
arr.slice(-1).pop(); // return 3 and arr = [1, 2, 3]

This will return undefined if the array is empty and this will not change the value of the array.

WebDriver: check if an element exists?

As I understand it, this is the default way of using the web driver.

How to click or tap on a TextView text

in textView

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:onClick="onClick"
    android:clickable="true"

You must also implement View.OnClickListener and in On Click method can use intent

    Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
           intent.setData(Uri.parse("https://youraddress.com"));    
            startActivity(intent);

I tested this solution works fine.

Adding hours to JavaScript Date object?

The below code is to add 4 hours to date(example today's date)

var today = new Date();
today.setHours(today.getHours() + 4);

It will not cause error if you try to add 4 to 23 (see the docs):

If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly

Get the current user, within an ApiController action, without passing the userID as a parameter

Karan Bhandari's answer is good, but the AccountController added in a project is very likely a Mvc.Controller. To convert his answer for use in an ApiController change HttpContext.Current.GetOwinContext() to Request.GetOwinContext() and make sure you have added the following 2 using statements:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

The simplest way to resize an UIImage?

Here's a Swift version of Paul Lynch's answer

func imageWithImage(image:UIImage, scaledToSize newSize:CGSize) -> UIImage{
    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
    image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
    let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}

And as an extension:

public extension UIImage {
    func copy(newSize: CGSize, retina: Bool = true) -> UIImage? {
        // In next line, pass 0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
        // Pass 1 to force exact pixel size.
        UIGraphicsBeginImageContextWithOptions(
            /* size: */ newSize,
            /* opaque: */ false,
            /* scale: */ retina ? 0 : 1
        )
        defer { UIGraphicsEndImageContext() }

        self.draw(in: CGRect(origin: .zero, size: newSize))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

How do I create a batch file timer to execute / call another batch throughout the day

better code that doesn't involve ping:

SET COUNTER=0
:loop
SET /a COUNTER=%COUNTER%+1
XCOPY "Server\*" "c:\minecraft\backups\server_backup_%COUNTER%" /i /s
timeout /t 600 /nobreak >nul
goto loop

600 seconds is 10 minutes, however you can set it whatever time you'd like

How can I loop over entries in JSON?

To decode json, you have to pass the json string. Currently you're trying to pass an object:

>>> response = urlopen(url)
>>> response
<addinfourl at 2146100812 whose fp = <socket._fileobject object at 0x7fe8cc2c>>

You can fetch the data with response.read().

Length of array in function argument

Regarding int main():

According to the Standard, argv points to a NULL-terminated array (of pointers to null-terminated strings). (5.1.2.2.1:1).

That is, argv = (char **){ argv[0], ..., argv[argc - 1], 0 };.

Hence, size calculation is performed by a function which is a trivial modification of strlen().

argc is only there to make argv length calculation O(1).

The count-until-NULL method will NOT work for generic array input. You will need to manually specify size as a second argument.