Programs & Examples On #Nservicebus

NServiceBus is a highly pluggable, reliable, open source Enterprise Service Bus built on .NET.

Fastest way to download a GitHub project

Use

git clone https://github.com/<path>/repository
or
git clone https://github.com/<path>/<master>.git

examples

git clone https://github.com/spring-projects/spring-data-graph-examples
git clone https://github.com/spring-projects/spring-data-graph-examples.git

How do I get the current GPS location programmatically in Android?

You can find the location either by GPS_PROVIDER or NETWORK_PROVIDER.

Overview of location services in Android.

Here is one example which try to find the location using GPS. If your GPS is not available then try to use network for find the location.

GPSTracker.java

 public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // Flag for GPS status
    boolean isGPSEnabled = false;

    // Flag for network status
    boolean isNetworkEnabled = false;

    // Flag for GPS status
    boolean canGetLocation = false;

    Location location; // Location
    double latitude; // Latitude
    double longitude; // Longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // Getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // Getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // No network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // If GPS enabled, get latitude/longitude using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }


    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app.
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }


    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }


    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/Wi-Fi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }


    /**
     * Function to show settings alert dialog.
     * On pressing the Settings button it will launch Settings Options.
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing the Settings button.
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // On pressing the cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }


    @Override
    public void onLocationChanged(Location location) {
    }


    @Override
    public void onProviderDisabled(String provider) {
    }


    @Override
    public void onProviderEnabled(String provider) {
    }


    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

Activity -AndroidGPSTrackingActivity.java

    public class AndroidGPSTrackingActivity extends Activity {

    Button btnShowLocation;

    // GPSTracker class
    GPSTracker gps;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

        // Show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Create class object
                gps = new GPSTracker(AndroidGPSTrackingActivity.this);

                // Check if GPS enabled
                if(gps.canGetLocation()) {

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    // \n is for new line
                    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                } else {
                    // Can't get location.
                    // GPS or network is not enabled.
                    // Ask user to enable GPS/network in settings.
                    gps.showSettingsAlert();
                }
            }
        });
    }
}

Layout- main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button android:id="@+id/btnShowLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Location"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

Update rows in one table with data from another table based on one column in each being equal

merge into t2 t2 
using (select * from t1) t1
on (t2.user_id = t1.user_id)
when matched then update
set
   t2.c1 = t1.c1
,  t2.c2 = t1.c2

MySQL does not start when upgrading OSX to Yosemite or El Capitan

My Mac decided to restart itself randomly; causing a whole slew of errors. One of which, was mysql refusing to start up properly. I went through many SO questions/answers as well as other sites.

Ultimately what ended up resolving MY issue was this:

1) Creating the file (/usr/local/mysql/data/.local.pid

2) chmod 777 on that file

3) executing mysql.server start (mine was located in/usr/local/bin/mysql.server)

Select values of checkbox group with jQuery

You could use the checked selector to grab only the selected ones (negating the need to know the count or to iterate over them all yourself):

$("input[name='user_group[]']:checked")

With those checked items, you can either create a collection of those values or do something to the collection:

var values = new Array();
$.each($("input[name='user_group[]']:checked"), function() {
  values.push($(this).val());
  // or you can do something to the actual checked checkboxes by working directly with  'this'
  // something like $(this).hide() (only something useful, probably) :P
});

Pythonically add header to a csv file

This worked for me.

header = ['row1', 'row2', 'row3']
some_list = [1, 2, 3]
with open('test.csv', 'wt', newline ='') as file:
    writer = csv.writer(file, delimiter=',')
    writer.writerow(i for i in header)
    for j in some_list:
        writer.writerow(j)

Access nested dictionary items via a list of keys?

It seems more pythonic to use a for loop. See the quote from What’s New In Python 3.0.

Removed reduce(). Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable.

def nested_get(dic, keys):    
    for key in keys:
        dic = dic[key]
    return dic

Note that the accepted solution doesn't set non-existing nested keys (it raises KeyError). Using the approach below will create non-existing nodes instead:

def nested_set(dic, keys, value):
    for key in keys[:-1]:
        dic = dic.setdefault(key, {})
    dic[keys[-1]] = value

The code works in both Python 2 and 3.

What is the best way to create a string array in python?

def _remove_regex(input_text, regex_pattern):
    findregs = re.finditer(regex_pattern, input_text) 
    for i in findregs: 
        input_text = re.sub(i.group().strip(), '', input_text)
    return input_text

regex_pattern = r"\buntil\b|\bcan\b|\bboat\b"
_remove_regex("row and row and row your boat until you can row no more", regex_pattern)

\w means that it matches word characters, a|b means match either a or b, \b represents a word boundary

Calculating how many minutes there are between two times

Try this

DateTime startTime = varValue
DateTime endTime = varTime

TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (minutes): " + span.TotalMinutes );

Edit: If are you trying 'span.Minutes', this will return only the minutes of timespan [0~59], to return sum of all minutes from this interval, just use 'span.TotalMinutes'.

How to get query string parameter from MVC Razor markup?

Similar thread

<div id="wrap" class=' @(ViewContext.RouteData.Values["iframe"] == 1 ? /*do sth*/ : /*do sth else*/')> </div>

EDIT 01-10-2014: Since this question is so popular this answer has been improved.

The example above will only get the values from RouteData, so only from the querystrings which are caught by some registered route. To get the querystring value you have to get to the current HttpRequest. Fastest way is by calling (as TruMan pointed out) `Request.Querystring' so the answer should be:

<div id="wrap" class=' @(Request.QueryString["iframe"] == 1 ? /*do sth*/ : /*do sth else*/')> </div>

You can also check RouteValues vs QueryString MVC?

EDIT 03-05-2019: Above solution is working for .NET Framework.
As others pointed out if you would like to get query string value in .NET Core you have to use Query object from Context.Request path. So it would be:

<div id="wrap" class=' @(Context.Request.Query["iframe"] == new StringValues("1") ? /*do sth*/ : /*do sth else*/')> </div>

Please notice I am using StringValues("1") in the statement because Query returns StringValues struct instead of pure string. That's cleanes way for this scenerio which I've found.

How to remove a virtualenv created by "pipenv run"

I know that question is a bit old but

In root of project where Pipfile is located you could run

pipenv --venv

which returns

/Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

and then remove this env by typing

rm -rf /Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

How to set Apache Spark Executor memory

Since you are running Spark in local mode, setting spark.executor.memory won't have any effect, as you have noticed. The reason for this is that the Worker "lives" within the driver JVM process that you start when you start spark-shell and the default memory used for that is 512M. You can increase that by setting spark.driver.memory to something higher, for example 5g. You can do that by either:

  • setting it in the properties file (default is $SPARK_HOME/conf/spark-defaults.conf),

    spark.driver.memory              5g
    
  • or by supplying configuration setting at runtime

    $ ./bin/spark-shell --driver-memory 5g
    

Note that this cannot be achieved by setting it in the application, because it is already too late by then, the process has already started with some amount of memory.

The reason for 265.4 MB is that Spark dedicates spark.storage.memoryFraction * spark.storage.safetyFraction to the total amount of storage memory and by default they are 0.6 and 0.9.

512 MB * 0.6 * 0.9 ~ 265.4 MB

So be aware that not the whole amount of driver memory will be available for RDD storage.

But when you'll start running this on a cluster, the spark.executor.memory setting will take over when calculating the amount to dedicate to Spark's memory cache.

Daemon not running. Starting it now on port 5037

Reference link: http://www.programering.com/a/MTNyUDMwATA.html

Steps I followed 1) Execute the command adb nodaemon server in command prompt Output at command prompt will be: The following error occurred cannot bind 'tcp:5037' The original ADB server port binding failed

2) Enter the following command query which using port 5037 netstat -ano | findstr "5037" The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288

3) View the task manager, close all adb.exe

4) Restart eclipse or other IDE

The above steps worked for me.

Sending email through Gmail SMTP server with C#

I've had some problems sending emails from my gmail account too, which were due to several of the aforementioned situations. Here's a summary of how I got it working, and keeping it flexible at the same time:

  • First of all setup your GMail account:
    • Enable IMAP and assert the right maximum number of messages (you can do so here)
    • Make sure your password is at least 7 characters and is strong (according to Google)
    • Make sure you don't have to enter a captcha code first. You can do so by sending a test email from your browser.
  • Make changes in web.config (or app.config, I haven't tried that yet but I assume it's just as easy to make it work in a windows application):
<configuration>
    <appSettings>
        <add key="EnableSSLOnMail" value="True"/>   
    </appSettings>

    <!-- other settings --> 

    ...

    <!-- system.net settings -->
    <system.net>
        <mailSettings>
            <smtp from="[email protected]" deliveryMethod="Network">
                <network 
                    defaultCredentials="false" 
                    host="smtp.gmail.com" 
                    port="587" 
                    password="stR0ngPassW0rd" 
                    userName="[email protected]"
                    />
                <!-- When using .Net 4.0 (or later) add attribute: enableSsl="true" and you're all set-->
            </smtp>
        </mailSettings>
    </system.net>
</configuration>
Add a Class to your project:

Imports System.Net.Mail

Public Class SSLMail

    Public Shared Sub SendMail(ByVal e As System.Web.UI.WebControls.MailMessageEventArgs)

        GetSmtpClient.Send(e.Message)

        'Since the message is sent here, set cancel=true so the original SmtpClient will not try to send the message too:
        e.Cancel = True

    End Sub

    Public Shared Sub SendMail(ByVal Msg As MailMessage)
        GetSmtpClient.Send(Msg)
    End Sub

    Public Shared Function GetSmtpClient() As SmtpClient

        Dim smtp As New Net.Mail.SmtpClient
        'Read EnableSSL setting from web.config
        smtp.EnableSsl = CBool(ConfigurationManager.AppSettings("EnableSSLOnMail"))
        Return smtp
    End Function

End Class

And now whenever you want to send emails all you need to do is call SSLMail.SendMail:

e.g. in a Page with a PasswordRecovery control:

Partial Class RecoverPassword
Inherits System.Web.UI.Page

Protected Sub RecoverPwd_SendingMail(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MailMessageEventArgs) Handles RecoverPwd.SendingMail
    e.Message.Bcc.Add("[email protected]")
    SSLMail.SendMail(e)
End Sub

End Class

Or anywhere in your code you can call:

SSLMail.SendMail(New system.Net.Mail.MailMessage("[email protected]","[email protected]", "Subject", "Body"})

I hope this helps anyone who runs into this post! (I used VB.NET but I think it's trivial to convert it to any .NET language.)

Trying to SSH into an Amazon Ec2 instance - permission error

.400 protects it by making it read only and only for the owner.
You can find the answer from the ASW guide.

chmod 400 yourPrivateKey.pem

enter image description here

font awesome icon in select option

In case anybody wants to use the latest Version (v5.7.2)

Please find my latest version (inspired by Victors answer).

It includes all Free Icons of the "Regular"-Set: https://fontawesome.com/icons?d=gallery&s=regular&m=free

Index.html

<head>
   ...
   <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
   ...
</head>

CSS:

select {
    font-family: 'Lato', 'Font Awesome 5 Free';
    font-weight: 900;
}

HTML:

<select id="icon">
    <option value="address-book">&#xf2b9; address-book</option>
    <option value="address-card">&#xf2bb; address-card</option>
    <option value="angry">&#xf556; angry</option>
    <option value="arrow-alt-circle-down">&#xf358; arrow-alt-circle-down</option>
    <option value="arrow-alt-circle-left">&#xf359; arrow-alt-circle-left</option>
    <option value="arrow-alt-circle-right">&#xf35a; arrow-alt-circle-right</option>
    <option value="arrow-alt-circle-up">&#xf35b; arrow-alt-circle-up</option>
    <option value="bell">&#xf0f3; bell</option>
    <option value="bell-slash">&#xf1f6; bell-slash</option>
    <option value="bookmark">&#xf02e; bookmark</option>
    <option value="building">&#xf1ad; building</option>
    <option value="calendar">&#xf133; calendar</option>
    <option value="calendar-alt">&#xf073; calendar-alt</option>
    <option value="calendar-check">&#xf274; calendar-check</option>
    <option value="calendar-minus">&#xf272; calendar-minus</option>
    <option value="calendar-plus">&#xf271; calendar-plus</option>
    <option value="calendar-times">&#xf273; calendar-times</option>
    <option value="caret-square-down">&#xf150; caret-square-down</option>
    <option value="caret-square-left">&#xf191; caret-square-left</option>
    <option value="caret-square-right">&#xf152; caret-square-right</option>
    <option value="caret-square-up">&#xf151; caret-square-up</option>
    <option value="chart-bar">&#xf080; chart-bar</option>
    <option value="check-circle">&#xf058; check-circle</option>
    <option value="check-square">&#xf14a; check-square</option>
    <option value="circle">&#xf111; circle</option>
    <option value="clipboard">&#xf328; clipboard</option>
    <option value="clock">&#xf017; clock</option>
    <option value="clone">&#xf24d; clone</option>
    <option value="closed-captioning">&#xf20a; closed-captioning</option>
    <option value="comment">&#xf075; comment</option>
    <option value="comment-alt">&#xf27a; comment-alt</option>
    <option value="comment-dots">&#xf4ad; comment-dots</option>
    <option value="comments">&#xf086; comments</option>
    <option value="compass">&#xf14e; compass</option>
    <option value="copy">&#xf0c5; copy</option>
    <option value="copyright">&#xf1f9; copyright</option>
    <option value="credit-card">&#xf09d; credit-card</option>
    <option value="dizzy">&#xf567; dizzy</option>
    <option value="dot-circle">&#xf192; dot-circle</option>
    <option value="edit">&#xf044; edit</option>
    <option value="envelope">&#xf40e0 envelope </option>
    <option value="envelope-open">&#xf2b6; envelope-open</option>
    <option value="eye">&#xf06e; eye</option>
    <option value="eye-slash">&#xf070; eye-slash</option>
    <option value="file">&#xf15b; file</option>
    <option value="file-alt">&#xf15c; file-alt</option>
    <option value="file-archive">&#xf1c6; file-archive</option>
    <option value="file-audio">&#xf1c7; file-audio</option>
    <option value="file-code">&#xf1c9; file-code</option>
    <option value="file-excel">&#xf1c3; file-excel </option>
    <option value="file-image">&#xf1c5; file-image</option>
    <option value="file-pdf">&#xf1c1; file-pdf</option>
    <option value="file-powerpoint">&#xf1c4; file-powerpoint</option>
    <option value="file-video">&#xf1c8; file-video</option>
    <option value="file-word">&#xf1c2; file-word</option>
    <option value="flag">&#xf024; flag</option>
    <option value="flushed">&#xf579; flushed</option>
    <option value="folder">&#xf07b; folder</option>
    <option value="folder-open">&#xf07c; folder-open </option>
    <option value="frown">&#xf119; frown</option>
    <option value="frown-open">&#xf57a; frown-open</option>
    <option value="futbol">&#xf1e3; futbol</option>
    <option value="gem">&#xf3a5; gem</option>
    <option value="grimace">&#xf57f; grimace</option>
    <option value="grin">&#xf580; grin</option>
    <option value="grin-alt">&#xf581; grin-alt</option>
    <option value="grin-beam">&#xf582; grin-beam</option>
    <option value="grin-beam-sweet">&#xf583; grin-beam-sweet </option>
    <option value="grin-hearts">&#xf584; grin-hearts</option>
    <option value="grin-squint">&#xf585; grin-squint</option>
    <option value="grin-squint-tears">&#xf586; grin-squint-tears</option>
    <option value="grin-stars">&#xf587; grin-stars</option>
    <option value="grin-tears">&#xf588; grin-tears</option>
    <option value="grin-tongue">&#xf589; grin-tongue</option>
    <option value="grin-tongue-squint">&#xf58a; grin-tongue-squint</option>
    <option value="grin-tongue-wink">&#xf58b; grin-tongue-wink</option>
    <option value="grin-wink">&#xf58c; grin-wink </option>
    <option value="hand-lizard">&#xf258; hand-lizard</option>
    <option value="hand-paper">&#xf256; hand-paper</option>
    <option value="hand-peace">&#xf25b; hand-peace</option>
    <option value="hand-point-down">&#xf0a7; hand-point-down</option>
    <option value="hand-point-left">&#xf0a5; hand-point-left</option>
    <option value="hand-point-right">&#xf0a4; hand-point-right</option>
    <option value="hand-point-up">&#xf0a6; hand-point-up</option>
    <option value="hand-pointer">&#xf25a; hand-pointer</option>
    <option value="hand-rock">&#xf255; hand-rock </option>
    <option value="hand-scissors">&#xf257; hand-scissors</option>
    <option value="hand-spock">&#xf259; hand-spock</option>
    <option value="handshake">&#xf2b5; handshake</option>
    <option value="hdd">&#xf0a0; hdd</option>
    <option value="heart">&#xf004; heart</option>
    <option value="home">&#xf015; home</option>
    <option value="hospital">&#xf0f8; hospital</option>
    <option value="hourglass">&#xf254; hourglass</option>
    <option value="id-badge">&#xf2c1; id-badge</option>
    <option value="id-card">&#xf2c2; id-card </option>
    <option value="image">&#xf03e; image</option>
    <option value="images">&#xf302; images</option>
    <option value="keyboard">&#xf11c; keyboard</option>
    <option value="kiss">&#xf596; kiss</option>
    <option value="kiss-beam">&#xf597; kiss-beam</option>
    <option value="kiss-wink-heart">&#xf598; kiss-wink-heart</option>
    <option value="laugh">&#xf599; laugh</option>
    <option value="laugh-beam">&#xf59a; laugh-beam</option>
    <option value="laugh-squint">&#xf59b; laugh-squint </option>
    <option value="laugh-wink">&#xf59c; laugh-wink</option>
    <option value="lemon">&#xf094; lemon</option>
    <option value="life-ring">&#xf1cd; life-ring</option>
    <option value="lightbulb">&#xf0eb; lightbulb</option>
    <option value="list-alt">&#xf022; list-alt</option>
    <option value="map">&#xf279; map</option>
    <option value="meh">&#xf11a; meh</option>
    <option value="meh-blank">&#xf5a4; meh-blank</option>
    <option value="meh-rolling-eyes">&#xf5a5; meh-rolling-eyes </option>
    <option value="minus-square">&#xf146; minus-square</option>
    <option value="money-bill-alt">&#xf3d1; money-bill-alt</option>
    <option value="moon">&#xf186; moon</option>
    <option value="newspaper">&#xf1ea; newspaper</option>
    <option value="object-group">&#xf247; object-group</option>
    <option value="object-upgroup">&#xf248; object-upgroup</option>
    <option value="paper-plane">&#xf1d8; paper-plane</option>
    <option value="pause-circle">&#xf28b; pause-circle</option>
    <option value="play-circle">&#xf144; play-circle </option>
    <option value="plus-square">&#xf0fe; plus-square</option>
    <option value="question-circle">&#xf059; question-circle</option>
    <option value="registered">&#xf25d; registered</option>
    <option value="sad-cry">&#xf5b3; sad-cry</option>
    <option value="sad-tear">&#xf5b4; sad-tear</option>
    <option value="save">&#xf0c7; save</option>
    <option value="share-square">&#xf14d; share-square</option>
    <option value="smile">&#xf118; smile</option>
    <option value="smile-beam">&#xf5b8; smile-beam </option>
    <option value="smile-wink">&#xf4da; smile-wink</option>
    <option value="snowflake">&#xf2dc; snowflake</option>
    <option value="square">&#xf0c8; square</option>
    <option value="star">&#xf005; star</option>
    <option value="star-half">&#xf089; star-half</option>
    <option value="sticky-note">&#xf249; sticky-note</option>
    <option value="stop-circle">&#xf28d; stop-circle</option>
    <option value="sun">&#xf185; sun</option>
    <option value="surprise">&#xf5c2; surprise </option>
    <option value="thumbs-down">&#xf165; thumbs-down</option>
    <option value="thumbs-up">&#xf1164; thumbs-up</option>
    <option value="times-circle">&#xf057; times-circle</option>
    <option value="tired">&#xf5c8; tired</option>
    <option value="trash-alt">&#xf2ed; trash-alt</option>
    <option value="user">&#xf007; user</option>
    <option value="user-circle">&#xf2bd; user-circle</option>
    <option value="window-close">&#xf410; window-close</option>
    <option value="window-maximize">&#xf2d0; window-maximize </option>
    <option value="window-minimize">&#xf2d1; window-minimize</option>
    <option value="window-restore">&#xf2d2; window-restore</option>
</select>

lambda expression for exists within list

I would look at the Join operator:

from r in list join i in listofIds on r.Id equals i select r

I'm not sure how this would be optimized over the Contains methods, but at least it gives the compiler a better idea of what you're trying to do. It's also sematically closer to what you're trying to achieve.

Edit: Extension method syntax for completeness (now that I've figured it out):

var results = listofIds.Join(list, i => i, r => r.Id, (i, r) => r);

Fastest way to determine if record exists

I've used this in the past and it doesn't require a full table scan to see if something exists. It's super fast...

UPDATE TableName SET column=value WHERE column=value
IF @@ROWCOUNT=0
BEGIN
     --Do work
END             

How do I create a nice-looking DMG for Mac OS X using command-line tools?

There's a little Bash script called create-dmg that builds fancy DMGs with custom backgrounds, custom icon positioning and volume name.

I've built it many years ago for the company that I ran at the time; it survives on other people's contribution since then, and reportedly works well.

There's also node-appdmg which looks like a more modern and active effort based on Node.js; check it out as well.

no matching function for call to ' '

You are trying to pass pointers (which you do not delete, thus leaking memory) where references are needed. You do not really need pointers here:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);

cout << "Numarul complex este: " << firstComplexNumber << endl;
//                                  ^^^^^^^^^^^^^^^^^^ No need to dereference now

// ...

Complex::distanta(firstComplexNumber, secondComplexNumber);

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

If you have date as a datetime.datetime (or a datetime.date) instance and want to combine it via a time from a datetime.time instance, then you can use the classmethod datetime.datetime.combine:

import datetime
dt = datetime.datetime(2020, 7, 1)
t = datetime.time(12, 34)
combined = datetime.datetime.combine(dt.date(), t)

Content Type application/soap+xml; charset=utf-8 was not supported by service

I had the same problem, got it working by "binding" de service with the service behaviour by doing this :

Gave a name to the behaviour

<serviceBehaviors>
        <behavior name="YourBehaviourNameHere">

And making a reference to your behaviour in your service

<services>
  <service name="WCFTradeLibrary.TradeService" behaviorConfiguration="YourBehaviourNameHere">

The whole thing would be :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="basicHttp" allowCookies="true"
                 maxReceivedMessageSize="20000000"
                 maxBufferSize="20000000"
                 maxBufferPoolSize="20000000">
          <readerQuotas maxDepth="32"
               maxArrayLength="200000000"
               maxStringContentLength="200000000"/>
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
     <service name="WCFTradeLibrary.TradeService" behaviourConfiguration="YourBehaviourNameHere">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttp" contract="WCFTradeLibrary.ITradeService">          
         </endpoint>
     </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="YourBehaviourNameHere">
          <!-- To avoid disclosing metadata information, 
          set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faul`enter code here`ts for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception info`enter code here`rmation -->
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

</configuration>

Java: Integer equals vs. ==

You can't compare two Integer with a simple == they're objects so most of the time references won't be the same.

There is a trick, with Integer between -128 and 127, references will be the same as autoboxing uses Integer.valueOf() which caches small integers.

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.


Resources :

On the same topic :

cursor.fetchall() vs list(cursor) in Python

list(cursor) works because a cursor is an iterable; you can also use cursor in a loop:

for row in cursor:
    # ...

A good database adapter implementation will fetch rows in batches from the server, saving on the memory footprint required as it will not need to hold the full result set in memory. cursor.fetchall() has to return the full list instead.

There is little point in using list(cursor) over cursor.fetchall(); the end effect is then indeed the same, but you wasted an opportunity to stream results instead.

What is .Net Framework 4 extended?

It's the part of the .NET Framework that isn't contained within the Client Profile. See MSDN for more info; specifically:

The .NET Framework is made up of the .NET Framework 4 Client Profile and .NET Framework 4 Extended components that exist separately in Programs and Features.

Could not resolve '...' from state ''

I've just had this same issue with Ionic.

It turns out nothing was wrong with my code, I simply had to quit the ionic serve session and run ionic serve again.

After going back into the app, my states worked fine.

I would also suggest pressing save on your app.js file a few times if you are running gulp, to make sure everything gets re-compiled.

Read environment variables in Node.js

To retrieve environment variables in Node.JS you can use process.env.VARIABLE_NAME, but don't forget that assigning a property on process.env will implicitly convert the value to a string.

Avoid Boolean Logic

Even if your .env file defines a variable like SHOULD_SEND=false or SHOULD_SEND=0, the values will be converted to strings (“false” and “0” respectively) and not interpreted as booleans.

if (process.env.SHOULD_SEND) {
 mailer.send();
} else {
  console.log("this won't be reached with values like false and 0");
}

Instead, you should make explicit checks. I’ve found depending on the environment name goes a long way.

 db.connect({
  debug: process.env.NODE_ENV === 'development'
 });

Most popular screen sizes/resolutions on Android phones

DEVELOPER-DOCS


  • 240*320-ldpi
  • 240*400-ldpi
  • 240*432-ldpi

  • 320*480-mdpi
  • 480*800-mdpi
  • 480*854-mdpi
  • 1024*600-mdpi
  • 1280*800-mdpi

  • 480*800-hdpi
  • 480*854-hdpi
  • 280*280-hdpi
  • 320*320-hdpi

  • 720*1280-xhdpi
  • 1200*1290-xhdpi
  • 2560*1600-xhdpi
  • 768*1280-xhdpi

  • 1080*1920-xxhdpi
  • 800*1280-tvdpi

I use these reference to make my app

Quoting an answer from another stackOverflow post for more details

---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------
Device                          Inches  ResolutionPX    Density         DPI     ResolutionDP    AspectRatios        SysNavYorN  ContentResolutionDP
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------                                                          
Galaxy Y                                 320 x  240     ldpi    0.75    120      427 x 320      4:3     1.3333                   427 x 320
?                                        400 x  240     ldpi    0.75    120      533 x 320      5:3     1.6667                   533 x 320
?                                        432 x  240     ldpi    0.75    120      576 x 320      9:5     1.8000                   576 x 320
Galaxy Ace                               480 x  320     mdpi    1       160      480 x 320      3:2     1.5000                   480 x 320
Nexus S                                  800 x  480     hdpi    1.5     240      533 x 320      5:3     1.6667                   533 x 320
"Galaxy SIII    Mini"                    800 x  480     hdpi    1.5     240      533 x 320      5:3     1.6667                   533 x 320
?                                        854 x  480     hdpi    1.5     240      569 x 320      427:240 1.7792                   569 x 320

Galaxy SIII                             1280 x  720     xhdpi   2       320      640 x 360      16:9    1.7778                   640 x 360
Galaxy Nexus                            1280 x  720     xhdpi   2       320      640 x 360      16:9    1.7778                   640 x 360
HTC One X                       4.7"    1280 x  720     xhdpi   2       320      640 x 360      16:9    1.7778                   640 x 360
Nexus 5                         5"      1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778      YES          592 x 360
Galaxy S4                       5"      1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778                   640 x 360
HTC One                         5"      1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778                   640 x 360
Galaxy Note III                 5.7"    1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778                   640 x 360
HTC One Max                     5.9"    1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778                   640 x 360
Galaxy Note II                  5.6"    1280 x  720     xhdpi   2       320      640 x 360      16:9    1.7778                   640 x 360
Nexus 4                         4.4"    1200 x  768     xhdpi   2       320      600 x 384      25:16   1.5625      YES          552 x 384
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------
Device                          Inches  ResolutionPX    Density         DPI     ResolutionDP    AspectRatios        SysNavYorN  ContentResolutionDP
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------
?                                        800 x  480     mdpi    1       160      800 x 480      5:3     1.6667                   800 x 480
?                                        854 x  480     mdpi    1       160      854 x 480      427:240 1.7792                   854 x 480
Galaxy Mega                     6.3"    1280 x  720     hdpi    1.5     240      853 x 480      16:9    1.7778                   853 x 480
Kindle Fire HD                  7"      1280 x  800     hdpi    1.5     240      853 x 533      8:5     1.6000                   853 x 533
Galaxy Mega                     5.8"     960 x  540     tvdpi   1.33333 213.333  720 x 405      16:9    1.7778                   720 x 405
Sony Xperia Z Ultra             6.4"    1920 x 1080     xhdpi   2       320      960 x 540      16:9    1.7778                   960 x 540

Kindle Fire (1st & 2nd gen)     7"      1024 x  600     mdpi    1       160     1024 x 600      128:75  1.7067                  1024 x 600
Tesco Hudl                      7"      1400 x  900     hdpi    1.5     240      933 x 600      14:9    1.5556                   933 x 600
Nexus 7 (1st gen/2012)          7"      1280 x  800     tvdpi   1.33333 213.333  960 x 600      8:5     1.6000      YES          912 x 600
Nexus 7 (2nd gen/2013)          7"      1824 x 1200     xhdpi   2       320      912 x 600      38:25   1.5200      YES          864 x 600
Kindle Fire HDX                 7"      1920 x 1200     xhdpi   2       320      960 x 600      8:5     1.6000                   960 x 600
?                                        800 x  480     ldpi    0.75    120     1067 x 640      5:3     1.6667                  1067 x 640
?                                        854 x  480     ldpi    0.75    120     1139 x 640      427:240 1.7792                  1139 x 640

Kindle Fire HD                  8.9"    1920 x 1200     hdpi    1.5     240     1280 x 800      8:5     1.6000                  1280 x 800
Kindle Fire HDX                 8.9"    2560 x 1600     xhdpi   2       320     1280 x 800      8:5     1.6000                  1280 x 800
Galaxy Tab 2                    10"     1280 x  800     mdpi    1       160     1280 x 800      8:5     1.6000                  1280 x 800
Galaxy Tab 3                    10"     1280 x  800     mdpi    1       160     1280 x 800      8:5     1.6000                  1280 x 800
ASUS Transformer                10"     1280 x  800     mdpi    1       160     1280 x 800      8:5     1.6000                  1280 x 800
ASUS Transformer 2              10"     1920 x 1200     hdpi    1.5     240     1280 x 800      8:5     1.6000                  1280 x 800
Nexus 10                        10"     2560 x  1600    xhdpi   2       320     1280 x 800      8:5     1.6000                  1280 x 800
Galaxy Note 10.1                10"     2560 x  1600    xhdpi   2       320     1280 x 800      8:5     1.6000                  1280 x 800
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------
Device                          Inches  ResolutionPX    Density         DPI     ResolutionDP    AspectRatios        SysNavYorN  ContentResolutionDP
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------

Link a .css on another folder

I dont get it clearly, do you want to link an external css as the structure of files you defined above? If yes then just use the link tag :

    <link rel="stylesheet" type="text/css" href="file.css">

so basically for files that are under your website folder (folder containing your index) you directly call it. For each successive folder use the "/" for example in your case :

    <link rel="stylesheet" type="text/css" href="Fonts/Font1/file name">
    <link rel="stylesheet" type="text/css" href="Fonts/Font2/file name">

Generate UML Class Diagram from Java Project

I´d say MoDisco is by far the most powerful one (though probably not the easiest one to work with).

MoDisco is a generic reverse engineering framework (so that you can customize your reverse engineering project, with MoDisco you can even reverse engineer the behaviour of the java methods, not only the structure and signatures) but also includes some predefined features like the generation of class diagrams out of Java code that you need.

How to print multiple variable lines in Java

System.out.println("First Name: " + firstname);
System.out.println("Last Name: " + lastname);

or

System.out.println(String.format("First Name: %s", firstname));
System.out.println(String.format("Last Name: %s", lastname));

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

I don't think there's a builtin function in angular for doing this, but you can do this by creating a separate scope property containing all the header names, and you can fill this property automatically like this:

var data = {
  foo: 'a',
  bar: 'b'
};

$scope.objectHeaders = [];

for ( property in data ) {
  $scope.objectHeaders.push(property); 
}

// Output: [ 'foo', 'bar' ]

How to run multiple SQL commands in a single SQL connection?

Just enable this property in your connection string:

sqb.MultipleActiveResultSets = true;

This property allows one open connection for multiple datareaders.

How to disable Google asking permission to regularly check installed apps on my phone?

In Nexus 5, Go to Settings -> Google -> Security and uncheck "Scan device for Security threats" and "Improve harmful app detection".

What is ANSI format?

When using single-byte characters, the ASCII format defines the first 127 characters. The extended characters from 128-255 are defined by various ANSI code pages to allow limited support for other languages. In order to make sense of an ANSI encoded string, you need to know which code page it uses.

Maximum packet size for a TCP connection

There're no packets in TCP API.

There're packets in underlying protocols often, like when TCP is done over IP, which you have no interest in, because they have nothing to do with the user except for very delicate performance optimizations which you are probably not interested in (according to the question's formulation).

If you ask what is a maximum number of bytes you can send() in one API call, then this is implementation and settings dependent. You would usually call send() for chunks of up to several kilobytes, and be always ready for the system to refuse to accept it totally or partially, in which case you will have to manually manage splitting into smaller chunks to feed your data into the TCP send() API.

How do I exit a WPF application programmatically?

Try

App.Current.Shutdown();

For me

Application.Current.Shutdown(); 

didn't work.

How to change font in ipython notebook

In addition to the suggestion by Konrad here, I'd like to suggest jupyter themes, which seems to have more options, such as line-height, font size, cell width etc.

Command line usage:

jt  [-h] [-l] [-t THEME] [-f MONOFONT] [-fs MONOSIZE] [-nf NBFONT]
[-nfs NBFONTSIZE] [-tf TCFONT] [-tfs TCFONTSIZE] [-dfs DFFONTSIZE]
[-m MARGINS] [-cursw CURSORWIDTH] [-cursc CURSORCOLOR] [-vim]
[-cellw CELLWIDTH] [-lineh LINEHEIGHT] [-altp] [-P] [-T] [-N]
[-r] [-dfonts]

Removing leading zeroes from a field in a SQL statement

In case you want to remove the leading zeros from a string with a unknown size.

You may consider using the STUFF command.

Here is an example of how it would work.

SELECT ISNULL(STUFF(ColumnName
                   ,1
                   ,patindex('%[^0]%',ColumnName)-1
                   ,'')
             ,REPLACE(ColumnName,'0','')
             )

See in fiddler various scenarios it will cover

https://dbfiddle.uk/?rdbms=sqlserver_2012&fiddle=14c2dca84aa28f2a7a1fac59c9412d48

jQuery show/hide not working

Demo

_x000D_
_x000D_
$( '.expand' ).click(function() {_x000D_
  $( '.img_display_content' ).toggle();_x000D_
});
_x000D_
.wrap {_x000D_
    margin-left:auto;_x000D_
    margin-right:auto;_x000D_
    width:40%;_x000D_
}_x000D_
_x000D_
.img_display_header {_x000D_
    height:20px;_x000D_
    background-color:#CCC;_x000D_
    display:block;_x000D_
    border:#333 solid 1px;_x000D_
    margin-bottom: 2px;_x000D_
}_x000D_
_x000D_
.expand {_x000D_
 float:right;_x000D_
 height: 100%;_x000D_
 padding-right:5px;_x000D_
 cursor:pointer;_x000D_
}_x000D_
_x000D_
.img_display_content {_x000D_
    width: 100%;_x000D_
    height:100px;   _x000D_
    background-color:#0F3;_x000D_
    margin-top: -2px;_x000D_
    display:none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="wrap">_x000D_
<div class="img_display_header">_x000D_
<div class="expand">+</div>_x000D_
</div>_x000D_
<div class="img_display_content"></div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://api.jquery.com/toggle/
"Display or hide the matched elements."

This is much shorter in code than using show() and hide() methods.

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

If you want to compare to a string literal you need to put it in (single) quotes:

<xsl:if test="Count != 'N/A'">

docker entrypoint running bash script gets "permission denied"

  1. "Permission denied" prevents your script from being invoked at all. Thus, the only syntax that could be possibly pertinent is that of the first line (the "shebang"), which should look like #!/usr/bin/env bash, or #!/bin/bash, or similar depending on your target's filesystem layout.

  2. Most likely the filesystem permissions not being set to allow execute. It's also possible that the shebang references something that isn't executable, but this is far less likely.

  3. Mooted by the ease of repairing the prior issues.


The simple reading of

docker: Error response from daemon: oci runtime error: exec: "/usr/src/app/docker-entrypoint.sh": permission denied.

...is that the script isn't marked executable.

RUN ["chmod", "+x", "/usr/src/app/docker-entrypoint.sh"]

will address this within the container. Alternately, you can ensure that the local copy referenced by the Dockerfile is executable, and then use COPY (which is explicitly documented to retain metadata).

if var == False

Python uses not instead of ! for negation.

Try

if not var: 
    print "learnt stuff"

instead

How can I remove 3 characters at the end of a string in php?

<?php echo substr("abcabcabc", 0, -3); ?>

How to read/write from/to file using Go?

Using io.Copy

package main

import (
    "io"
    "log"
    "os"
)

func main () {
    // open files r and w
    r, err := os.Open("input.txt")
    if err != nil {
        panic(err)
    }
    defer r.Close()

    w, err := os.Create("output.txt")
    if err != nil {
        panic(err)
    }
    defer w.Close()

    // do the actual work
    n, err := io.Copy(w, r)
    if err != nil {
        panic(err)
    }
    log.Printf("Copied %v bytes\n", n)
}

If you don't feel like reinventing the wheel, the io.Copy and io.CopyN may serve you well. If you check the source of the io.Copy function, it is nothing but one of the Mostafa's solutions (the 'basic' one, actually) packaged in the Go library. They are using a significantly larger buffer than he is, though.

How to view the SQL queries issued by JPA?

Example using log4j (src\log4j.xml):

<?xml version="1.0" encoding="UTF-8" ?>

<appender name="CA" class="org.apache.log4j.AsyncAppender">
    <param name="BufferSize" value="512"/>
    <appender-ref ref="CA_OUTPUT"/>
</appender>
<appender name="CA_OUTPUT" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="[%p] %d %c %M - %m%n"/>
    </layout>
</appender>

<logger name="org.hibernate.SQL" additivity="false">
    <level value="DEBUG"/>
    <appender-ref ref="CA"/>
</logger>

<root>
    <level value="WARN"/>
    <appender-ref ref="CA"/>
</root>

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

Get text of the selected option with jQuery

Close, you can use

$('#select_2 option:selected').html()

Converting unix time into date-time via excel

in case the above does not work for you. for me this did not for some reasons;

the UNIX numbers i am working on are from the Mozilla place.sqlite dates.

to make it work : i splitted the UNIX cells into two cells : one of the first 10 numbers (the date) and the other 4 numbers left (the seconds i believe)

Then i used this formula, =(A1/86400)+25569 where A1 contains the cell with the first 10 number; and it worked

How can I close a window with Javascript on Mozilla Firefox 3?

If the browser people see this as a security and/or usability problem, then the answer to your question is to simply not close the window, since by definition they will come up with solutions for your workaround anyway. There is a nice summation about the reasoning why the choice have been in the firefox bug database https://bugzilla.mozilla.org/show_bug.cgi?id=190515#c70

So what can you do?

Change the specification of your website, so that you have a solution for these people. You could for instance take it as an opportunity to direct them to a partner.

That is, see it as a handoff to someone else that (potentially) needs it. As an example, Hanselman had a recent article about what to do in the other similar situation, namely 404 errors: http://www.hanselman.com/blog/PutMissingKidsOnYour404PageEntirelyClientSideSolutionWithYQLJQueryAndMSAjax.aspx

Eclipse plugin for generating a class diagram

Must it be an Eclipse plug-in? I use doxygen, just supply your code folder, it handles the rest.

Parse JSON in TSQL

CREATE FUNCTION dbo.parseJSON( @JSON NVARCHAR(MAX))
RETURNS @hierarchy TABLE
  (
   element_id INT IDENTITY(1, 1) NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */
   sequenceNo [int] NULL, /* the place in the sequence for the element */
   parent_ID INT,/* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */
   Object_ID INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */
   NAME NVARCHAR(2000),/* the name of the object */
   StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */
   ValueType VARCHAR(10) NOT null /* the declared type of the value represented as a string in StringValue*/
  )
AS
BEGIN
  DECLARE
    @FirstObject INT, --the index of the first open bracket found in the JSON string
    @OpenDelimiter INT,--the index of the next open bracket found in the JSON string
    @NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string
    @NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string
    @Type NVARCHAR(10),--whether it denotes an object or an array
    @NextCloseDelimiterChar CHAR(1),--either a '}' or a ']'
    @Contents NVARCHAR(MAX), --the unparsed contents of the bracketed expression
    @Start INT, --index of the start of the token that you are parsing
    @end INT,--index of the end of the token that you are parsing
    @param INT,--the parameter at the end of the next Object/Array token
    @EndOfName INT,--the index of the start of the parameter at end of Object/Array token
    @token NVARCHAR(200),--either a string or object
    @value NVARCHAR(MAX), -- the value as a string
    @SequenceNo int, -- the sequence number within a list
    @name NVARCHAR(200), --the name as a string
    @parent_ID INT,--the next parent ID to allocate
    @lenJSON INT,--the current length of the JSON String
    @characters NCHAR(36),--used to convert hex to decimal
    @result BIGINT,--the value of the hex symbol being parsed
    @index SMALLINT,--used for parsing the hex value
    @Escape INT --the index of the next escape character


  DECLARE @Strings TABLE /* in this temporary table we keep all strings, even the names of the elements, since they are 'escaped' in a different way, and may contain, unescaped, brackets denoting objects or lists. These are replaced in the JSON string by tokens representing the string */
    (
     String_ID INT IDENTITY(1, 1),
     StringValue NVARCHAR(MAX)
    )
  SELECT--initialise the characters to convert hex to ascii
    @characters='0123456789abcdefghijklmnopqrstuvwxyz',
    @SequenceNo=0, --set the sequence no. to something sensible.
  /* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */
    @parent_ID=0;
  WHILE 1=1 --forever until there is nothing more to do
    BEGIN
      SELECT
        @start=PATINDEX('%[^a-zA-Z]["]%', @json collate SQL_Latin1_General_CP850_Bin);--next delimited string
      IF @start=0 BREAK --no more so drop through the WHILE loop
      IF SUBSTRING(@json, @start+1, 1)='"'
        BEGIN --Delimited Name
          SET @start=@Start+1;
          SET @end=PATINDEX('%[^\]["]%', RIGHT(@json, LEN(@json+'|')-@start) collate SQL_Latin1_General_CP850_Bin);
        END
      IF @end=0 --no end delimiter to last string
        BREAK --no more
      SELECT @token=SUBSTRING(@json, @start+1, @end-1)
      --now put in the escaped control characters
      SELECT @token=REPLACE(@token, FROMString, TOString)
      FROM
        (SELECT
          '\"' AS FromString, '"' AS ToString
         UNION ALL SELECT '\\', '\'
         UNION ALL SELECT '\/', '/'
         UNION ALL SELECT '\b', CHAR(08)
         UNION ALL SELECT '\f', CHAR(12)
         UNION ALL SELECT '\n', CHAR(10)
         UNION ALL SELECT '\r', CHAR(13)
         UNION ALL SELECT '\t', CHAR(09)
        ) substitutions
      SELECT @result=0, @escape=1
  --Begin to take out any hex escape codes
      WHILE @escape>0
        BEGIN
          SELECT @index=0,
          --find the next hex escape sequence
          @escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token collate SQL_Latin1_General_CP850_Bin)
          IF @escape>0 --if there is one
            BEGIN
              WHILE @index<4 --there are always four digits to a \x sequence  
                BEGIN
                  SELECT --determine its value
                    @result=@result+POWER(16, @index)
                    *(CHARINDEX(SUBSTRING(@token, @escape+2+3-@index, 1),
                                @characters)-1), @index=@index+1 ;

                END
                -- and replace the hex sequence by its unicode value
              SELECT @token=STUFF(@token, @escape, 6, NCHAR(@result))
            END
        END
      --now store the string away
      INSERT INTO @Strings (StringValue) SELECT @token
      -- and replace the string with a token
      SELECT @JSON=STUFF(@json, @start, @end+1,
                    '@string'+CONVERT(NVARCHAR(5), @@identity))
    END
  -- all strings are now removed. Now we find the first leaf. 
  WHILE 1=1  --forever until there is nothing more to do
  BEGIN

  SELECT @parent_ID=@parent_ID+1
  --find the first object or list by looking for the open bracket
  SELECT @FirstObject=PATINDEX('%[{[[]%', @json collate SQL_Latin1_General_CP850_Bin)--object or array
  IF @FirstObject = 0 BREAK
  IF (SUBSTRING(@json, @FirstObject, 1)='{')
    SELECT @NextCloseDelimiterChar='}', @type='object'
  ELSE
    SELECT @NextCloseDelimiterChar=']', @type='array'
  SELECT @OpenDelimiter=@firstObject

  WHILE 1=1 --find the innermost object or list...
    BEGIN
      SELECT
        @lenJSON=LEN(@JSON+'|')-1
  --find the matching close-delimiter proceeding after the open-delimiter
      SELECT
        @NextCloseDelimiter=CHARINDEX(@NextCloseDelimiterChar, @json,
                                      @OpenDelimiter+1)
  --is there an intervening open-delimiter of either type
      SELECT @NextOpenDelimiter=PATINDEX('%[{[[]%',
             RIGHT(@json, @lenJSON-@OpenDelimiter)collate SQL_Latin1_General_CP850_Bin)--object
      IF @NextOpenDelimiter=0
        BREAK
      SELECT @NextOpenDelimiter=@NextOpenDelimiter+@OpenDelimiter
      IF @NextCloseDelimiter<@NextOpenDelimiter
        BREAK
      IF SUBSTRING(@json, @NextOpenDelimiter, 1)='{'
        SELECT @NextCloseDelimiterChar='}', @type='object'
      ELSE
        SELECT @NextCloseDelimiterChar=']', @type='array'
      SELECT @OpenDelimiter=@NextOpenDelimiter
    END
  ---and parse out the list or name/value pairs
  SELECT
    @contents=SUBSTRING(@json, @OpenDelimiter+1,
                        @NextCloseDelimiter-@OpenDelimiter-1)
  SELECT
    @JSON=STUFF(@json, @OpenDelimiter,
                @NextCloseDelimiter-@OpenDelimiter+1,
                '@'+@type+CONVERT(NVARCHAR(5), @parent_ID))
  WHILE (PATINDEX('%[A-Za-z0-9@+.e]%', @contents collate SQL_Latin1_General_CP850_Bin))<>0
    BEGIN
      IF @Type='Object' --it will be a 0-n list containing a string followed by a string, number,boolean, or null
        BEGIN
          SELECT
            @SequenceNo=0,@end=CHARINDEX(':', ' '+@contents)--if there is anything, it will be a string-based name.
          SELECT  @start=PATINDEX('%[^A-Za-z@][@]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)--AAAAAAAA
          SELECT @token=SUBSTRING(' '+@contents, @start+1, @End-@Start-1),
            @endofname=PATINDEX('%[0-9]%', @token collate SQL_Latin1_General_CP850_Bin),
            @param=RIGHT(@token, LEN(@token)-@endofname+1)
          SELECT
            @token=LEFT(@token, @endofname-1),
            @Contents=RIGHT(' '+@contents, LEN(' '+@contents+'|')-@end-1)
          SELECT  @name=stringvalue FROM @strings
            WHERE string_id=@param --fetch the name
        END
      ELSE
        SELECT @Name=null,@SequenceNo=@SequenceNo+1
      SELECT
        @end=CHARINDEX(',', @contents)-- a string-token, object-token, list-token, number,boolean, or null
      IF @end=0
        SELECT  @end=PATINDEX('%[A-Za-z0-9@+.e][^A-Za-z0-9@+.e]%', @Contents+' ' collate SQL_Latin1_General_CP850_Bin)
          +1
       SELECT
        @start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)
      --select @start,@end, LEN(@contents+'|'), @contents 
      SELECT
        @Value=RTRIM(SUBSTRING(@contents, @start, @End-@Start)),
        @Contents=RIGHT(@contents+' ', LEN(@contents+'|')-@end)
      IF SUBSTRING(@value, 1, 7)='@object'
        INSERT INTO @hierarchy
          (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
          SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 8, 5),
            SUBSTRING(@value, 8, 5), 'object'
      ELSE
        IF SUBSTRING(@value, 1, 6)='@array'
          INSERT INTO @hierarchy
            (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
            SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 7, 5),
              SUBSTRING(@value, 7, 5), 'array'
        ELSE
          IF SUBSTRING(@value, 1, 7)='@string'
            INSERT INTO @hierarchy
              (NAME, SequenceNo, parent_ID, StringValue, ValueType)
              SELECT @name, @SequenceNo, @parent_ID, stringvalue, 'string'
              FROM @strings
              WHERE string_id=SUBSTRING(@value, 8, 5)
          ELSE
            IF @value IN ('true', 'false')
              INSERT INTO @hierarchy
                (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                SELECT @name, @SequenceNo, @parent_ID, @value, 'boolean'
            ELSE
              IF @value='null'
                INSERT INTO @hierarchy
                  (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                  SELECT @name, @SequenceNo, @parent_ID, @value, 'null'
              ELSE
                IF PATINDEX('%[^0-9]%', @value collate SQL_Latin1_General_CP850_Bin)>0
                  INSERT INTO @hierarchy
                    (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                    SELECT @name, @SequenceNo, @parent_ID, @value, 'real'
                ELSE
                  INSERT INTO @hierarchy
                    (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                    SELECT @name, @SequenceNo, @parent_ID, @value, 'int'
      if @Contents=' ' Select @SequenceNo=0
    END
  END
INSERT INTO @hierarchy (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
  SELECT '-',1, NULL, '', @parent_id-1, @type
--
   RETURN
END
GO

---Pase JSON

Declare @pars varchar(MAX) = 
' {"shapes":[{"type":"polygon","geofenceName":"","geofenceDescription":"",
"geofenceCategory":"1","color":"#1E90FF","paths":[{"path":[{
"lat":"26.096254906968525","lon":"65.709228515625"}
,{"lat":"28.38173504322308","lon":"66.741943359375"}
,{"lat":"26.765230565697482","lon":"68.983154296875"}
,{"lat":"26.254009699865737","lon":"68.609619140625"}
,{"lat":"25.997549919572112","lon":"68.104248046875"}
,{"lat":"26.843677401113002","lon":"67.115478515625"}
,{"lat":"25.363882272740255","lon":"65.819091796875"}]}]}]}'
Select * from parseJSON(@pars) AS MyResult 

SQL LEFT-JOIN on 2 fields for MySQL

Let's try this way:

select 
    a.ip, 
    a.os, 
    a.hostname, 
    a.port, 
    a.protocol, 
    b.state
from a
left join b 
    on a.ip = b.ip 
        and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/

So, in where clause you can filter result set by column from right table only on this way:

...
where b.somecolumn <> (=) null

How to break out of the IF statement

In this case, insert a single else:

public void Method()
{
    if(something)
    {
        // some code
        if(something2)
        {
            // now I should break from ifs and go to te code outside ifs
        }
        else return;
    }
    // The code i want to go if the second if is true
}

Generally: There is no break in an if/else sequence, simply arrange your code correctly in if / if else / else clauses.

How do C++ class members get initialized if I don't do it explicitly?

Members with a constructor will have their default constructor called for initialisation.

You cannot depend on the contents of the other types.

Passing command line arguments in Visual Studio 2010?

Visual Studio 2015:

Project => Your Application Properties. Each argument can be separated using space. If you have a space in between for the same argument, put double quotes as shown in the example below.

enter image description here

        static void Main(string[] args)
        {
            if(args == null || args.Length == 0)
            {
                Console.WriteLine("Please specify arguments!");
            }
            else
            {
                Console.WriteLine(args[0]);     // First
                Console.WriteLine(args[1]);     // Second Argument
            }
        }

addEventListener, "change" and option selection

You need a click listener which calls addActivityItem if less than 2 options exist:

var activities = document.getElementById("activitySelector");

activities.addEventListener("click", function() {
    var options = activities.querySelectorAll("option");
    var count = options.length;
    if(typeof(count) === "undefined" || count < 2)
    {
        addActivityItem();
    }
});

activities.addEventListener("change", function() {
    if(activities.value == "addNew")
    {
        addActivityItem();
    }
});

function addActivityItem() {
    // ... Code to add item here
}

A live demo is here on JSfiddle.

string.Replace in AngularJs

var oldString = "stackoverflow";
var str=oldString.replace(/stackover/g,"NO");
$scope.newString= str;

It works for me. Use an intermediate variable.

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

Simulating ENTER keypress in bash script

You might find the yes command useful.

See man yes

What does "commercial use" exactly mean?

If the usage of something is part of the process of you making money, then it's generally considered a commercial use. If the purpose of the site is to, through some means or another, directly or indirectly, make you money, then it's probably commercial use.

If, on the other hand, something is merely incidental (not part of the process of production/working, but instead simply tacked on to the side), there are potential grounds for it not to be considered commercial use.

How do I get my Maven Integration tests to run

By default, Maven only runs tests that have Test somewhere in the class name.

Rename to IntegrationTest and it'll probably work.

Alternatively you can change the Maven config to include that file but it's probably easier and better just to name your tests SomethingTest.

From Inclusions and Exclusions of Tests:

By default, the Surefire Plugin will automatically include all test classes with the following wildcard patterns:

  • \*\*/Test\*.java - includes all of its subdirectory and all java filenames that start with "Test".
  • \*\*/\*Test.java - includes all of its subdirectory and all java filenames that end with "Test".
  • \*\*/\*TestCase.java - includes all of its subdirectory and all java filenames that end with "TestCase".

If the test classes does not go with the naming convention, then configure Surefire Plugin and specify the tests you want to include.

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

These are the steps I took (I'm on Linux).

  • Switched to Software rendering (works but is too slow)
  • Tried running on commanline and an error displayed.
  • Forced emulator to use the system graphic drivers.

First, as @jlars62 suggested, I tried using Switching the Graphics to "Software" and this DID work. However, the performance is far to slow so I dug a little deeper.

Then I tried running the device from the console, as @CaptainCrunch suggestion. (My device was created in Android Studio; emulator in the Sdk may be in a different place on your system)

$ ~/Android/Sdk/emulator/emulator -avd Nexus_6_Edited_768Mb_API_23

For me this produced the following error:

libGL error: unable to load driver: i965_dri.so 
libGL error: driver
pointer missing libGL error: failed to load driver: i965 
...

Which I tracked down (on ArchLinux) to mean it's using the wrong graphic drivers (Android Sdk comes with it's own). You can force the system ones on the commandline with -use-system-libs:

$ ~/Android/Sdk/emulator/emulator -avd Nexus_6_Edited_768Mb_API_23 -use-system-libs

To force Android Studio to do this you can intercept the call to "emulator" like so (See Mike42) :

$ cd ~/Android/Sdk/tools/
$ mv emulator emulator.0
$ touch emulator
$ chmod +x emulator

In the new emulator file add this:

#!/bin/sh
set -ex
$0.0 $@ -use-system-libs

What's the best way to add a full screen background image in React Native

(This has been deprecated now you can use ImageBackground)

This is how I've done it. The main deal was getting rid of the static fixed sizes.

class ReactStrap extends React.Component {
  render() {
    return (
      <Image source={require('image!background')} style={styles.container}>
        ... Your Content ...
      </Image>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
    // remove width and height to override fixed static size
    width: null,
    height: null,
  }
};

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Was following one of training with Spring webmvc 4.2.3, while I'm using Spring webmvc 5.2.3 they suggested to create a form

<form:form modelAttribute="aNewAccount" method="get" action="/accountCreated">

that was causing the "disclose" error.

Altered as below to make it work. Looks like method above was the culprit.

<form:form modelAttribute="aNewAccount" action="accountCreated.html">

in fact, exploring further, method="post" in form annotation would work if properly declared:

@RequestMapping(value="/accountCreated", method=RequestMethod.POST)

Regular expression - starting and ending with a letter, accepting only letters, numbers and _

seeing how the rules are fairly complicated, I'd suggest the following:

/^[a-z](\w*)[a-z0-9]$/i

match the whole string and capture intermediate characters. Then either with the string functions or the following regex:

/__/

check if the captured part has two underscores in a row. For example in Python it would look like this:

>>> import re
>>> def valid(s):
    match = re.match(r'^[a-z](\w*)[a-z0-9]$', s, re.I)
    if match is not None:
        return match.group(1).count('__') == 0
    return False

Fixing npm path in Windows 8 and 10

steps 1 in the user variable and system variable

  C:\Program Files\nodejs

then check both node -v and the npm -v then try to update the the npm i -g npm

What's the difference between using "let" and "var"?

enter image description here

Take a look at this image, I created one very simple example for demonstration of const and let variables. As you can see, when you try to change const variable, you will get the error (Attempting to override 'name' which is constant'), but take a look at let variable...

First we declare let age = 33, and later assign some other value age = 34;, which is ok, we dont have any errors when we try to change let variable

.gitignore all the .DS_Store files in every folder and subfolder

If .DS_Store was never added to your git repository, simply add it to your .gitignore file.

If you don't have one, create a file called

.gitignore

In the root directory of your app and simply write

**/.DS_Store

In it. This will never allow the .DS_Store file to sneak in your git.

But, if it's already there, write in your terminal:

find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch

then commit and push the changes to remove the .DS_Store from your remote repo:

git commit -m "Remove .DS_Store from everywhere"

git push origin master

And now add .DS_Store to your .gitignore file, and then again commit and push with the 2 last pieces of code (git commit..., git push...)

use jQuery's find() on JSON object

jQuery doesn't work on plain object literals. You can use the below function in a similar way to search all 'id's (or any other property), regardless of its depth in the object:

function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));
        } else if (i == key && obj[key] == val) {
            objects.push(obj);
        }
    }
    return objects;
}

Use like so:

getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects

What regular expression will match valid international phone numbers?

This works for me, without 00, 001, 0011 etc prefix though:

/^\+*(\d{3})*[0-9,\-]{8,}/

What port is used by Java RMI connection?

With reference to other answers above, here is my view -

there are ports involved on both client and server side.

  • for server/remote side, if you export the object without providing a port , remote object would use a random port to listen.

  • a client, when looks up the remote object, it would always use a random port on its side and will connect to the remote object port as listed above.

windows batch file rename

@echo off
pushd "pathToYourFolder" || exit /b
for /f "eol=: delims=" %%F in ('dir /b /a-d *_*.jpg') do (
  for /f "tokens=1* eol=_ delims=_" %%A in ("%%~nF") do ren "%%F" "%%~nB_%%A%%~xF"
)
popd

Note: The name is split at the first occurrence of _. If a file is named "part1_part2_part3.jpg", then it will be renamed to "part2_part3_part1.jpg"

Getting the count of unique values in a column in bash

To see a frequency count for column two (for example):

awk -F '\t' '{print $2}' * | sort | uniq -c | sort -nr

fileA.txt

z    z    a
a    b    c
w    d    e

fileB.txt

t    r    e
z    d    a
a    g    c

fileC.txt

z    r    a
v    d    c
a    m    c

Result:

  3 d
  2 r
  1 z
  1 m
  1 g
  1 b

How do I get which JRadioButton is selected from a ButtonGroup

Use the isSelected() method. It will tell you the state of your radioButton. Using it in combination with a loop(say for loop) you can find which one has been selected.

Input group - two inputs close to each other

To show more than one inputs inline without using "form-inline" class you can use the next code:

<div class="input-group">
    <input type="text" class="form-control" value="First input" />
    <span class="input-group-btn"></span>
    <input type="text" class="form-control" value="Second input" />
</div>

Then using CSS selectors:

/* To remove space between text inputs */
.input-group > .input-group-btn:empty {
    width: 0px;
}

Basically you have to insert an empty span tag with "input-group-btn" class between input tags.

If you want to see more examples of input groups and bootstrap-select groups take a look at this URL: http://jsfiddle.net/vkhusnulina/gze0Lcm0

SSIS Excel Connection Manager failed to Connect to the Source

Simple workaround is to open the file and simply press save button in Excel (no need to change the format). once saved in excel it will start to work and you should be able to see its sheets in the DFT.

JQuery Redirect to URL after specified time

I have made a simple demo that prompts for X number of seconds and redirects to set url. If you don't want to wait until the end of the count, just click on the counter to redirect with no time. Simple counter that will count down while pulsing time in the midle of the page. You can run it onclick or while some page is loaded.

LIVE DEMO ONLOAD

LIVE DEMO ONCLICK

I also made github repo for this: https://github.com/GlupiJas/redirect-counter-plugin

JS CODE EXAMPLE:

// FUNCTION CODE
function gjCountAndRedirect(secounds, url)
{

        $('#gj-counter-num').text(secounds);

        $('#gj-counter-box').show();

    var interval = setInterval(function()
    {

        secounds = secounds - 1;

        $('#gj-counter-num').text(secounds);

        if(secounds == 0)
        {

            clearInterval(interval);
            window.location = url;
            $('#gj-counter-box').hide();

        }

    }, 1000);

    $('#gj-counter-box').click(function() //comment it out -if you dont want to allo count skipping
    {
        clearInterval(interval);
        window.location = url;

    });
}

// USE EXAMPLE
$(document).ready(function() {
    //var
    var gjCountAndRedirectStatus = false; //prevent from seting multiple Interval

    //call
    $('h1').click(function(){
        if(gjCountAndRedirectStatus == false)
        {
            gjCountAndRedirect(10, document.URL);
            gjCountAndRedirectStatus = true;
        }
    });

});

Controller not a function, got undefined, while defining controllers globally

I got this problem because I had wrapped a controller-definition file in a closure:

(function() {
   ...stuff...
});

But I had forgotten to actually invoke that closure to execute that definition code and actually tell Javascript my controller existed. I.e., the above needs to be:

(function() {
   ...stuff...
})();

Note the () at the end.

How can I open a popup window with a fixed size using the HREF tag?

Since many browsers block popups by default and popups are really ugly, I recommend using lightbox or thickbox.

They are prettier and are not popups. They are extra HTML markups that are appended to your document's body with the appropriate CSS content.

http://jquery.com/demo/thickbox/

setState() inside of componentDidUpdate()

If you use setState inside componentDidUpdate it updates the component, resulting in a call to componentDidUpdate which subsequently calls setState again resulting in the infinite loop. You should conditionally call setState and ensure that the condition violating the call occurs eventually e.g:

componentDidUpdate: function() {
    if (condition) {
        this.setState({..})
    } else {
        //do something else
    }
}

In case you are only updating the component by sending props to it(it is not being updated by setState, except for the case inside componentDidUpdate), you can call setState inside componentWillReceiveProps instead of componentDidUpdate.

Including non-Python files with setup.py

None of the answers worked for me because my files were at the top level, outside the package. I used a custom build command instead.

import os
import setuptools
from setuptools.command.build_py import build_py
from shutil import copyfile

HERE = os.path.abspath(os.path.dirname(__file__))
NAME = "thepackage"

class BuildCommand(build_py):
    def run(self):
        build_py.run(self)

        if not self.dry_run:
            target_dir = os.path.join(self.build_lib, NAME)
            for fn in ["VERSION", "LICENSE.txt"]:
                copyfile(os.path.join(HERE, fn), os.path.join(target_dir,fn))

 
 
setuptools.setup(
    name=NAME,
    cmdclass={"build_py": BuildCommand},
    description=DESCRIPTION,
    ...
)

preg_match in JavaScript?

Sample code to get image links within HTML content. Like preg_match_all in PHP

let HTML = '<div class="imageset"><table><tbody><tr><td width="50%"><img src="htt ps://domain.com/uploads/monthly_2019_11/7/1.png.jpg" class="fr-fic fr-dii"></td><td width="50%"><img src="htt ps://domain.com/uploads/monthly_2019_11/7/9.png.jpg" class="fr-fic fr-dii"></td></tr></tbody></table></div>';
let re = /<img src="(.*?)"/gi;
let result = HTML.match(re);

out array

0: "<img src="htt ps://domain.com/uploads/monthly_2019_11/7/1.png.jpg""
1: "<img src="htt ps://domain.com/uploads/monthly_2019_11/7/9.png.jpg""

Reading From A Text File - Batch

Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit

But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit

Or if you'd like them to select the file from which to write in the batch you could do the following.

@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.

Conclusion

  • USE REQUIRES_NEW if you want to commit what did you do before exception (Local commit)
  • USE REQUIRED if you want to commit only when all processes are done (Global commit) And you just need to ignore "Transaction rolled back because it has been marked as rollback-only" exception. But you need to try-catch out side the caller processNextRegistrationMessage() to have a meaning log.

Let's me explain more detail:

Question: How many Transaction we have? Answer: Only one

Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.

Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction

  1. When persist() method has an exception
  2. Go to the catch outside

    Spring will set the rollBackOnly to true -> it determine we must 
    rollback the caller (processNextRegistrationMessage) also.
    
  3. The persist() will rollback itself first.

  4. Throw an UnexpectedRollbackException to inform that, we need to rollback the caller also.
  5. The try-catch in run() will catch UnexpectedRollbackException and print the stack trace

Question: Why we change PROPAGATION to REQUIRES_NEW, it works?

Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.

Thanks

Clear the value of bootstrap-datepicker

you have to do it in that way:

$('#datepicker').datepicker('clearDates');

CSS body background image fixed to full screen even when zooming in/out

You can do quite a lot with plain css...the css property background-size can be set to a number of things as well as just cover as Ranjith pointed out.

The background-size: cover setting scales the image to cover the entire screen but may mean that some of the image is off screen if the aspect ratio of the screen and image are different.

A good alternative is background-size: contain which resizes the background image to fit the smaller of width and height, ensuring that the whole image is visible but may lead to letterboxing if the aspect ratios are different.

For example:

body {
      background: url(/images/bkgd.png) no-repeat rgb(30,30,30) fixed center center;
      background-size: contain;
     }

The other options that I find less useful are: background-size: length <widthpx> <heightpx> which sets the absolute size of the background image. background-size: percentage <width> <height> background image is a percentage of the window size. (see w3schools.com's page)

CSS display:table-row does not expand when width is set to 100%

give on .view-type class float:left; or delete the float:right; of .view-name

edit: Wrap your div <div class="view-row"> with another div for example <div class="table">

and set the following css :

.table {
    display:table;
    width:100%;}

You have to use the table structure for correct results.

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

"This was a bug on the Apple portal site. They were missing a necessary field in the provisioning profile. They fixed this bug late on 6/16/09. "

Illegal mix of collations error in MySql

I have the same problem with collection warning for a field that is set from 0 to 1. All columns collections was the same. We try to change collections again but nothing fix this issue.

At the end we update the field to NULL and after that we update to 1 and this overcomes the collection problem.

How to close off a Git Branch?

after complete the code first merge branch to master then delete that branch

git checkout master
git merge <branch-name>
git branch -d <branch-name>

Matching special characters and letters in regex

I tried a bunch of these but none of them worked for all of my tests. So I found this:

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$

from this source: https://www.w3resource.com/javascript/form/password-validation.php

Form submit with AJAX passing form data to PHP without page refresh

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {
        $('form').bind('click', function (event) {
        // using this page stop being refreshing 
        event.preventDefault();

          $.ajax({
            type: 'POST',
            url: 'post.php',
            data: $('form').serialize(),
            success: function () {
              alert('form was submitted');
            }
          });
        });
      });
    </script>
  </head>
  <body>
    <form>
      <input name="time" value="00:00:00.00"><br>
      <input name="date" value="0000-00-00"><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

PHP

<?php

if(isset($_POST["date"]) || isset($_POST["time"])) {
$time="";
$date="";
if(isset($_POST['time'])){$time=$_POST['time']}
if(isset($_POST['date'])){$date=$_POST['date']}

echo $time."<br>";
echo $date;
}
?>

SELECT INTO using Oracle

select into is used in pl/sql to set a variable to field values. Instead, use

create table new_table as select * from old_table

Select first and last row from grouped data

A different base R alternative would be to first order by id and stopSequence, split them based on id and for every id we select only the first and last index and subset the dataframe using those indices.

df[sapply(with(df, split(order(id, stopSequence), id)), function(x) 
                   c(x[1], x[length(x)])), ]


#  id stopId stopSequence
#1  1      a            1
#3  1      c            3
#5  2      b            1
#6  2      c            4
#8  3      b            1
#7  3      a            3

Or similar using by

df[unlist(with(df, by(order(id, stopSequence), id, function(x) 
                   c(x[1], x[length(x)])))), ]

In C#, why is String a reference type that behaves like a value type?

Also, the way strings are implemented (different for each platform) and when you start stitching them together. Like using a StringBuilder. It allocats a buffer for you to copy into, once you reach the end, it allocates even more memory for you, in the hopes that if you do a large concatenation performance won't be hindered.

Maybe Jon Skeet can help up out here?

How can I copy the output of a command directly into my clipboard?

In Linux with xclip installed:

xclip -selection clipboard < file

How do I fix the indentation of selected lines in Visual Studio

To fix the indentation and formatting in all files of your solution:

  1. Install the Format All Files extension => close VS, execute the .vsix file and reopen VS;
  2. Menu Tools > Options... > Text Editor > All Languages > Tabs:
    1. Click on Smart (for resolving conflicts);
    2. Type the Tab Size and Indent Size you want (e.g. 2);
    3. Click on Insert Spaces if you want to replace tabs by spaces;
  3. In the Solution Explorer (Ctrl+Alt+L) right click in any file and choose from the menu Format All Files (near the bottom).

This will recursively open and save all files in your solution, setting the indentation you defined above.

You might want to check other programming languages tabs (Options...) for Code Style > Formatting as well.

Reverse Y-Axis in PyPlot

If using matplotlib you can try: matplotlib.pyplot.xlim(l, r) matplotlib.pyplot.ylim(b, t)

These two lines set the limits of the x and y axes respectively. For the x axis, the first argument l sets the left most value, and the second argument r sets the right most value. For the y axis, the first argument b sets the bottom most value, and the second argument t sets the top most value.

How to commit changes to a new branch

If I understand right, you've made a commit to changed_branch and you want to copy that commit to other_branch? Easy:

git checkout other_branch
git cherry-pick changed_branch

How to get POST data in WebAPI?

It is hard to handle multiple parameters on the action directly. The better way to do it is to create a view model class. Then you have a single parameter but the parameter contains multiple data properties.

public class MyParameters
{
    public string a { get; set; } 
    public string b { get; set; }
}

public MyController : ApiController
{
    public HttpResponseMessage Get([FromUri] MyParameters parameters) { ... }
}

Then you go to:

http://localhost:12345/api/MyController?a=par1&b=par2

Reference: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

If you want to use "/par1/par2", you can register an asp routing rule. eg routeTemplate: "API/{controller}/{action}/{a}/{b}".

See http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

C++ Boost: undefined reference to boost::system::generic_category()

This answer actually helped when using Boost and cmake.

Adding add_definitions(-DBOOST_ERROR_CODE_HEADER_ONLY) for cmake file.

My CMakeLists.txt looks like this:

cmake_minimum_required(VERSION 3.12)
project(proj)

set(CMAKE_CXX_STANDARD 17)


set(SHARED_DIR "${CMAKE_SOURCE_DIR}/../shared")

set(BOOST_LATEST_DIR            "${SHARED_DIR}/boost_1_68_0")
set(BOOST_LATEST_BIN_DIR        "${BOOST_LATEST_DIR}/stage/lib")
set(BOOST_LATEST_INCLUDE_DIR    "${BOOST_LATEST_DIR}/boost")
set(BOOST_SYSTEM                "${BOOST_LATEST_BIN_DIR}/libboost_system.so")
set(BOOST_FS                    "${BOOST_LATEST_BIN_DIR}/libboost_filesystem.so")
set(BOOST_THREAD                "${BOOST_LATEST_BIN_DIR}/libboost_thread.so")

set(HYRISE_SQL_PARSER_DIR           "${SHARED_DIR}/hyrise_sql_parser")
set(HYRISE_SQL_PARSER_BIN_DIR       "${HYRISE_SQL_PARSER_DIR}")
set(HYRISE_SQL_PARSER_INCLUDE_DIR   "${HYRISE_SQL_PARSER_DIR}/src")
set(HYRISE_SQLPARSER                "${HYRISE_SQL_PARSER_BIN_DIR}/libsqlparser.so")


include_directories(${CMAKE_SOURCE_DIR} ${BOOST_LATEST_INCLUDE_DIR} ${HYRISE_SQL_PARSER_INCLUDE_DIR})

set(BOOST_LIBRARYDIR "/usr/lib/x86_64-linux-gnu/")
set(Boost_USE_STATIC_LIBS OFF)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)

add_definitions(-DBOOST_ERROR_CODE_HEADER_ONLY)

find_package(Boost 1.68.0 REQUIRED COMPONENTS system thread filesystem)

add_executable(proj main.cpp row/row.cpp row/row.h table/table.cpp table/table.h page/page.cpp page/page.h
        processor/processor.cpp processor/processor.h engine_instance.cpp engine_instance.h utils.h
        meta_command.h terminal/terminal.cpp terminal/terminal.h)


if(Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS})
    target_link_libraries(proj PUBLIC Boost::system Boost::filesystem Boost::thread ${HYRISE_SQLPARSER})
endif()

Algorithm to compare two images

It is indeed much less simple than it seems :-) Nick's suggestion is a good one.

To get started, keep in mind that any worthwhile comparison method will essentially work by converting the images into a different form -- a form which makes it easier to pick similar features out. Usually, this stuff doesn't make for very light reading ...


One of the simplest examples I can think of is simply using the color space of each image. If two images have highly similar color distributions, then you can be reasonably sure that they show the same thing. At least, you can have enough certainty to flag it, or do more testing. Comparing images in color space will also resist things such as rotation, scaling, and some cropping. It won't, of course, resist heavy modification of the image or heavy recoloring (and even a simple hue shift will be somewhat tricky).

http://en.wikipedia.org/wiki/RGB_color_space
http://upvector.com/index.php?section=tutorials&subsection=tutorials/colorspace


Another example involves something called the Hough Transform. This transform essentially decomposes an image into a set of lines. You can then take some of the 'strongest' lines in each image and see if they line up. You can do some extra work to try and compensate for rotation and scaling too -- and in this case, since comparing a few lines is MUCH less computational work than doing the same to entire images -- it won't be so bad.

http://homepages.inf.ed.ac.uk/amos/hough.html
http://rkb.home.cern.ch/rkb/AN16pp/node122.html
http://en.wikipedia.org/wiki/Hough_transform

How do I format a date with Dart?

This give you the date like in a social network : ["today","yesterday","dayoftheweek",etc..]

void main() {
      DateTime now = new DateTime(2018,6,26);
      print(date(now));
    }
    
    String date(DateTime tm) {
      DateTime today = new DateTime.now();
      Duration oneDay = new Duration(days: 1);
      Duration twoDay = new Duration(days: 2);
      Duration oneWeek = new Duration(days: 7);
      String month;
      switch (tm.month) {
        case 1:
          month = "january";
          break;
        case 2:
          month = "february";
          break;
        case 3:
          month = "march";
          break;
        case 4:
          month = "april";
          break;
        case 5:
          month = "may";
          break;
        case 6:
          month = "june";
          break;
        case 7:
          month = "july";
          break;
        case 8:
          month = "august";
          break;
        case 9:
          month = "september";
          break;
        case 10:
          month = "october";
          break;
        case 11:
          month = "november";
          break;
        case 12:
          month = "december";
          break;
      }
    
      Duration difference = today.difference(tm);
    
      if (difference.compareTo(oneDay) < 1) {
        return "today";
      } else if (difference.compareTo(twoDay) < 1) {
        return "yesterday";
      } else if (difference.compareTo(oneWeek) < 1) {
        switch (tm.weekday) {
          case 1:
            return "monday";
          case 2:
            return "tuesday";
          case 3:
            return "wednesday";
          case 4:
            return "thursday";
          case 5:
            return "friday";
          case 6:
            return "saturday";
          case 7:
            return "sunday";
        }
      } else if (tm.year == today.year) {
        return '${tm.day} $month';
      } else {
        return '${tm.day} $month ${tm.year}';
      }
    }

How to change Oracle default data pump directory to import dumpfile?

I want change default directory dumpfile.

You could create a new directory and give it required privileges, for example:

SQL> CREATE DIRECTORY dmpdir AS '/opt/oracle';
Directory created.

SQL> GRANT read, write ON DIRECTORY dmpdir TO scott;
Grant succeeded.

To use the newly created directory, you could just add it as a parameter:

DIRECTORY=dmpdir

Oracle introduced a default directory from 10g R2, called DATA_PUMP_DIR, that can be used. To check the location, you could look into dba_directories:

SQL> select DIRECTORY_NAME, DIRECTORY_PATH from dba_directories where DIRECTORY_NAME = 'DATA_PUMP_DIR';

DIRECTORY_NAME       DIRECTORY_PATH
-------------------- --------------------------------------------------
DATA_PUMP_DIR        C:\app\Lalit/admin/orcl/dpdump/

SQL>

Submit a form using jQuery

I recommend a generic solution so you don't have to add the code for every form. Use the jquery form plugin (http://jquery.malsup.com/form/) and add this code.

$(function(){
$('form.ajax_submit').submit(function() {
    $(this).ajaxSubmit();
            //validation and other stuff
        return false; 
});

});

Spring Boot - Loading Initial Data

You can add a spring.datasource.data property to application.properties listing the sql files you want to run. Like this:

spring.datasource.data=classpath:accounts.sql, classpath:books.sql, classpath:reviews.sql

The sql insert statements in each of these files will then be run, allowing you to keep things tidy.

If you put the files in the classpath, for example in src/main/resources they will be applied. Or replace classpath: with file: and use an absolute path to the file

If you want to run DDL type SQL then use:

spring.datasource.schema=classpath:create_account_table.sql

Edit: these solutions are great to get you up and running quickly, however for a more production ready solution it would be worth looking at a framework such as flyway, or liquibase. These frameworks integrate well with spring, and provide a quick, consistent, version-controlled means of initialising schema, and standing-data.

What does "Error: object '<myvariable>' not found" mean?

The error means that R could not find the variable mentioned in the error message.

The easiest way to reproduce the error is to type the name of a variable that doesn't exist. (If you've defined x already, use a different variable name.)

x
## Error: object 'x' not found

The more complex version of the error has the same cause: calling a function when x does not exist.

mean(x)
## Error in mean(x) : 
##   error in evaluating the argument 'x' in selecting a method for function 'mean': Error: object 'x' not found

Once the variable has been defined, the error will not occur.

x <- 1:5
x
## [1] 1 2 3 4 5     
mean(x)
## [1] 3

You can check to see if a variable exists using ls or exists.

ls()        # lists all the variables that have been defined
exists("x") # returns TRUE or FALSE, depending upon whether x has been defined.

Errors like this can occur when you are using non-standard evaluation. For example, when using subset, the error will occur if a column name is not present in the data frame to subset.

d <- data.frame(a = rnorm(5))
subset(d, b > 0)
## Error in eval(expr, envir, enclos) : object 'b' not found

The error can also occur if you use custom evaluation.

get("var", "package:stats") #returns the var function
get("var", "package:utils")
## Error in get("var", "package:utils") : object 'var' not found

In the second case, the var function cannot be found when R looks in the utils package's environment because utils is further down the search list than stats.


In more advanced use cases, you may wish to read:

How do I store the select column in a variable?

select @EmpID = ID from dbo.Employee

Or

set @EmpID =(select id from dbo.Employee)

Note that the select query might return more than one value or rows. so you can write a select query that must return one row.

If you would like to add more columns to one variable(MS SQL), there is an option to use table defined variable

DECLARE @sampleTable TABLE(column1 type1)
INSERT INTO @sampleTable
SELECT columnsNumberEqualInsampleTable FROM .. WHERE ..

As table type variable do not exist in Oracle and others, you would have to define it:

DECLARE TYPE type_name IS TABLE OF (column_type | variable%TYPE | table.column%TYPE [NOT NULL] INDEX BY BINARY INTEGER;

-- Then to declare a TABLE variable of this type: variable_name type_name;

-- Assigning values to a TABLE variable: variable_name(n).field_name := 'some text';

-- Where 'n' is the index value

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

Use .gitattributes instead, with the following setting:

# Ignore all differences in line endings
*        -crlf

.gitattributes would be found in the same directory as your global .gitconfig. If .gitattributes doesn't exist, add it to that directory. After adding/changing .gitattributes you will have to do a hard reset of the repository in order to successfully apply the changes to existing files.

IntelliJ - show where errors are

In my case, IntelliJ was simply in power safe mode

delete all from table

This should be faster:

DELETE * FROM table_name;

because RDBMS don't have to look where is what.

You should be fine with truncate though:

truncate table table_name

What is the most efficient way to store tags in a database?

If you don't mind using a bit of non-standard stuff, Postgres version 9.4 and up has an option of storing a record of type JSON text array.

Your schema would be:

Table: Items
Columns: Item_ID:int, Title:text, Content:text

Table: Tags
Columns: Item_ID:int, Tag_Title:text[]

For more info, see this excellent post by Josh Berkus: http://www.databasesoup.com/2015/01/tag-all-things.html

There are more various options compared thoroughly for performance and the one suggested above is the best overall.

Get Selected value of a Combobox

A simpler way to get the selected value from a ComboBox control is:

Private Sub myComboBox_Change()
  msgbox "You selected: " + myComboBox.SelText
End Sub

How do I determine if my python shell is executing in 32bit or 64bit?

import sys
print(sys.version)

3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]

Prevent Caching in ASP.NET MVC for specific actions using an attribute

For MVC6 (DNX), there is no System.Web.OutputCacheAttribute

Note: when you set NoStore Duration parameter is not considered. It is possible to set an initial duration for first registration and override this with custom attributes.

But we have Microsoft.AspNet.Mvc.Filters.ResponseCacheFilter

 public void ConfigureServices(IServiceCollection services)
        ...
        services.AddMvc(config=>
        {
            config.Filters.Add(
                 new ResponseCacheFilter(
                    new CacheProfile() { 
                      NoStore=true
                     }));
        }
        ...
       )

It is possible to override initial filter with a custom attribute

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class NoCacheAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            var filter=filterContext.Filters.Where(t => t.GetType() == typeof(ResponseCacheFilter)).FirstOrDefault();
            if (filter != null)
            {
                ResponseCacheFilter f = (ResponseCacheFilter)filter;
                f.NoStore = true;
                //f.Duration = 0;
            }

            base.OnResultExecuting(filterContext);
        }
    }

Here is a use case

    [NoCache]
    [HttpGet]
    public JsonResult Get()
    {            
        return Json(new DateTime());
    }

Mocking python function based on input arguments

Just to show another way of doing it:

def mock_isdir(path):
    return path in ['/var/log', '/var/log/apache2', '/var/log/tomcat']

with mock.patch('os.path.isdir') as os_path_isdir:
    os_path_isdir.side_effect = mock_isdir

How to Exit a Method without Exiting the Program?

In addition to Mark's answer, you also need to be aware of scope, which (as in C/C++) is specified using braces. So:

if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
    textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
return;

will always return at that point. However:

if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
{
    textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
    return;
}

will only return if it goes into that if statement.

Merging two CSV files using Python

You need to store all of the extra rows in the files in your dictionary, not just one of them:

dict1 = {row[0]: row[1:] for row in r}
...
dict2 = {row[0]: row[1:] for row in r}

Then, since the values in the dictionaries are lists, you need to just concatenate the lists together:

w.writerows([[key] + dict1.get(key, []) + dict2.get(key, []) for key in keys])

Add legend to ggplot2 line plot

Since @Etienne asked how to do this without melting the data (which in general is the preferred method, but I recognize there may be some cases where that is not possible), I present the following alternative.

Start with a subset of the original data:

datos <-
structure(list(fecha = structure(c(1317452400, 1317538800, 1317625200, 
1317711600, 1317798000, 1317884400, 1317970800, 1318057200, 1318143600, 
1318230000, 1318316400, 1318402800, 1318489200, 1318575600, 1318662000, 
1318748400, 1318834800, 1318921200, 1319007600, 1319094000), class = c("POSIXct", 
"POSIXt"), tzone = ""), TempMax = c(26.58, 27.78, 27.9, 27.44, 
30.9, 30.44, 27.57, 25.71, 25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 
26.58, 26.18, 25.19, 24.19, 27.65, 23.92), TempMedia = c(22.88, 
22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52, 19.71, 20.73, 
23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 20.45, 19.42, 19.97, 
19.61), TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 
16.88, 16.82, 14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 
16.95, 17.55, 15.21, 14.22, 16.42)), .Names = c("fecha", "TempMax", 
"TempMedia", "TempMin"), row.names = c(NA, 20L), class = "data.frame")

You can get the desired effect by (and this also cleans up the original plotting code):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      breaks = c("TempMax", "TempMedia", "TempMin"),
                      values = c("red", "green", "blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

The idea is that each line is given a color by mapping the colour aesthetic to a constant string. Choosing the string which is what you want to appear in the legend is the easiest. The fact that in this case it is the same as the name of the y variable being plotted is not significant; it could be any set of strings. It is very important that this is inside the aes call; you are creating a mapping to this "variable".

scale_colour_manual can now map these strings to the appropriate colors. The result is enter image description here

In some cases, the mapping between the levels and colors needs to be made explicit by naming the values in the manual scale (thanks to @DaveRGP for pointing this out):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

(giving the same figure as before). With named values, the breaks can be used to set the order in the legend and any order can be used in the values.

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      breaks = c("TempMedia", "TempMax", "TempMin"),
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

Match whitespace but not newlines

A variation on Greg’s answer that includes carriage returns too:

/[^\S\r\n]/

This regex is safer than /[^\S\n]/ with no \r. My reasoning is that Windows uses \r\n for newlines, and Mac OS 9 used \r. You’re unlikely to find \r without \n nowadays, but if you do find it, it couldn’t mean anything but a newline. Thus, since \r can mean a newline, we should exclude it too.

How do I install a Python package with a .whl file?

On the MacOS, with pip installed via MacPorts into the MacPorts python2.7, I had to use @Dunes solution:

sudo python -m pip install some-package.whl

Where python was replaced by the MacPorts python in my case, which is python2.7 or python3.5 for me.

The -m option is "Run library module as script" according to the manpage.

(I had previously run sudo port install py27-pip py27-wheel to install pip and wheel into my python 2.7 installation first.)

XAMPP Start automatically on Windows 7 startup

Try to run Your XAMPP Control Panel as Run as administrator, then install Apache and MySQL.

enter image description here

When XAMPP opens, ensure that Apache and MySQL services are stopped.

enter image description here

Now just check/tick on Apache and Mysql service module.

enter image description here

Now Apache and MySQL will be added to window services. You can set these services to start when Windows boots.

Converting an integer to binary in C

short a;
short b;
short c;
short d;
short e;
short f;
short g;
short h;
int i;
char j[256];

printf("BINARY CONVERTER\n\n\n");

//uses <stdlib.h>

while(1)
{

a=0;
b=0;
c=0;
d=0;
e=0;
f=0;
g=0;
h=0;
i=0;


gets(j);
i=atoi(j);
if(i>255){
printf("int i must not pass the value 255.\n");
i=0;
}
if(i>=128){
a=1;
i=i-128;}
if(i>=64){
b=1;
i=i-64;}
if(i>=32){
c=1;
i=i-32;}
if(i>=16){
d=1;
i=i-16;}
if(i>=8){
e=1;
i=i-8;}
if(i>=4){
f=1;
i=i-4;}
if(i>=2){
g=1;
i=i-2;}
if(i>=1){
h=1;
i=i-1;}

printf("\n%d%d%d%d%d%d%d%d\n\n",a,b,c,d,e,f,g,h);
}

Design DFA accepting binary strings divisible by a number 'n'

Below, I have written an answer for n equals to 5, but you can apply same approach to draw DFAs for any value of n and 'any positional number system' e.g binary, ternary...

First lean the term 'Complete DFA', A DFA defined on complete domain in d:Q × S?Q is called 'Complete DFA'. In other words we can say; in transition diagram of complete DFA there is no missing edge (e.g. from each state in Q there is one outgoing edge present for every language symbol in S). Note: Sometime we define partial DFA as d ? Q × S?Q (Read: How does “d:Q × S?Q” read in the definition of a DFA).

Design DFA accepting Binary numbers divisible by number 'n':

Step-1: When you divide a number ? by n then reminder can be either 0, 1, ..., (n - 2) or (n - 1). If remainder is 0 that means ? is divisible by n otherwise not. So, in my DFA there will be a state qr that would be corresponding to a remainder value r, where 0 <= r <= (n - 1), and total number of states in DFA is n.
After processing a number string ? over S, the end state is qr implies that ? % n => r (% reminder operator).

In any automata, the purpose of a state is like memory element. A state in an atomata stores some information like fan's switch that can tell whether the fan is in 'off' or in 'on' state. For n = 5, five states in DFA corresponding to five reminder information as follows:

  1. State q0 reached if reminder is 0. State q0 is the final state(accepting state). It is also an initial state.
  2. State q1 reaches if reminder is 1, a non-final state.
  3. State q2 if reminder is 2, a non-final state.
  4. State q3 if reminder is 3, a non-final state.
  5. State q4 if reminder is 4, a non-final state.

Using above information, we can start drawing transition diagram TD of five states as follows:

fig-1
Figure-1

So, 5 states for 5 remainder values. After processing a string ? if end-state becomes q0 that means decimal equivalent of input string is divisible by 5. In above figure q0 is marked final state as two concentric circle.
Additionally, I have defined a transition rule d:(q0, 0)?q0 as a self loop for symbol '0' at state q0, this is because decimal equivalent of any string consist of only '0' is 0 and 0 is a divisible by n.

Step-2: TD above is incomplete; and can only process strings of '0's. Now add some more edges so that it can process subsequent number's strings. Check table below, shows new transition rules those can be added next step:

+-------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦
+------+------+-------------+---------¦
¦One   ¦1     ¦1            ¦q1       ¦
+------+------+-------------+---------¦
¦Two   ¦10    ¦2            ¦q2       ¦
+------+------+-------------+---------¦
¦Three ¦11    ¦3            ¦q3       ¦
+------+------+-------------+---------¦
¦Four  ¦100   ¦4            ¦q4       ¦
+-------------------------------------+
  1. To process binary string '1' there should be a transition rule d:(q0, 1)?q1
  2. Two:- binary representation is '10', end-state should be q2, and to process '10', we just need to add one more transition rule d:(q1, 0)?q2
    Path: ?(q0)-1?(q1)-0?(q2)
  3. Three:- in binary it is '11', end-state is q3, and we need to add a transition rule d:(q1, 1)?q3
    Path: ?(q0)-1?(q1)-1?(q3)
  4. Four:- in binary '100', end-state is q4. TD already processes prefix string '10' and we just need to add a new transition rule d:(q2, 0)?q4
    Path: ?(q0)-1?(q1)-0?(q2)-0?(q4)

fig-2 Figure-2

Step-3: Five = 101
Above transition diagram in figure-2 is still incomplete and there are many missing edges, for an example no transition is defined for d:(q2, 1)-?. And the rule should be present to process strings like '101'.
Because '101' = 5 is divisible by 5, and to accept '101' I will add d:(q2, 1)?q0 in above figure-2.
Path: ?(q0)-1?(q1)-0?(q2)-1?(q0)
with this new rule, transition diagram becomes as follows:

fig-3 Figure-3

Below in each step I pick next subsequent binary number to add a missing edge until I get TD as a 'complete DFA'.

Step-4: Six = 110.

We can process '11' in present TD in figure-3 as: ?(q0)-11?(q3) -0?(?). Because 6 % 5 = 1 this means to add one rule d:(q3, 0)?q1.

fig-4 Figure-4

Step-5: Seven = 111

+--------------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path       ¦ Add       ¦
+------+------+-------------+---------+------------+-----------¦
¦Seven ¦111   ¦7 % 5 = 2    ¦q2       ¦ q0-11?q3   ¦ q3-1?q2    ¦
+--------------------------------------------------------------+

fig-5 Figure-5

Step-6: Eight = 1000

+----------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path     ¦ Add     ¦
+------+------+-------------+---------+----------+---------¦
¦Eight ¦1000  ¦8 % 5 = 3    ¦q3       ¦q0-100?q4 ¦ q4-0?q3  ¦
+----------------------------------------------------------+

fig-6 Figure-6

Step-7: Nine = 1001

+----------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path     ¦ Add     ¦
+------+------+-------------+---------+----------+---------¦
¦Nine  ¦1001  ¦9 % 5 = 4    ¦q4       ¦q0-100?q4 ¦ q4-1?q4  ¦
+----------------------------------------------------------+

fig-7 Figure-7

In TD-7, total number of edges are 10 == Q × S = 5 × 2. And it is a complete DFA that can accept all possible binary strings those decimal equivalent is divisible by 5.

Design DFA accepting Ternary numbers divisible by number n:

Step-1 Exactly same as for binary, use figure-1.

Step-2 Add Zero, One, Two

+------------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦   Add        ¦
+-------+-------+-------------+---------+--------------¦
¦Zero   ¦0      ¦0            ¦q0       ¦ d:(q0,0)?q0  ¦
+-------+-------+-------------+---------+--------------¦
¦One    ¦1      ¦1            ¦q1       ¦ d:(q0,1)?q1  ¦
+-------+-------+-------------+---------+--------------¦
¦Two    ¦2      ¦2            ¦q2       ¦ d:(q0,2)?q3  ¦
+------------------------------------------------------+

fig-8
Figure-8

Step-3 Add Three, Four, Five

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Three  ¦10     ¦3            ¦q3       ¦ d:(q1,0)?q3 ¦
+-------+-------+-------------+---------+-------------¦
¦Four   ¦11     ¦4            ¦q4       ¦ d:(q1,1)?q4 ¦
+-------+-------+-------------+---------+-------------¦
¦Five   ¦12     ¦0            ¦q0       ¦ d:(q1,2)?q0 ¦
+-----------------------------------------------------+

fig-9
Figure-9

Step-4 Add Six, Seven, Eight

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Six    ¦20     ¦1            ¦q1       ¦ d:(q2,0)?q1 ¦
+-------+-------+-------------+---------+-------------¦
¦Seven  ¦21     ¦2            ¦q2       ¦ d:(q2,1)?q2 ¦
+-------+-------+-------------+---------+-------------¦
¦Eight  ¦22     ¦3            ¦q3       ¦ d:(q2,2)?q3 ¦
+-----------------------------------------------------+

fig-10
Figure-10

Step-5 Add Nine, Ten, Eleven

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Nine   ¦100    ¦4            ¦q4       ¦ d:(q3,0)?q4 ¦
+-------+-------+-------------+---------+-------------¦
¦Ten    ¦101    ¦0            ¦q0       ¦ d:(q3,1)?q0 ¦
+-------+-------+-------------+---------+-------------¦
¦Eleven ¦102    ¦1            ¦q1       ¦ d:(q3,2)?q1 ¦
+-----------------------------------------------------+

fig-11
Figure-11

Step-6 Add Twelve, Thirteen, Fourteen

+------------------------------------------------------+
¦Decimal ¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+--------+-------+-------------+---------+-------------¦
¦Twelve  ¦110    ¦2            ¦q2       ¦ d:(q4,0)?q2 ¦
+--------+-------+-------------+---------+-------------¦
¦Thirteen¦111    ¦3            ¦q3       ¦ d:(q4,1)?q3 ¦
+--------+-------+-------------+---------+-------------¦
¦Fourteen¦112    ¦4            ¦q4       ¦ d:(q4,2)?q4 ¦
+------------------------------------------------------+

fig-12
Figure-12

Total number of edges in transition diagram figure-12 are 15 = Q × S = 5 * 3 (a complete DFA). And this DFA can accept all strings consist over {0, 1, 2} those decimal equivalent is divisible by 5.
If you notice at each step, in table there are three entries because at each step I add all possible outgoing edge from a state to make a complete DFA (and I add an edge so that qr state gets for remainder is r)!

To add further, remember union of two regular languages are also a regular. If you need to design a DFA that accepts binary strings those decimal equivalent is either divisible by 3 or 5, then draw two separate DFAs for divisible by 3 and 5 then union both DFAs to construct target DFA (for 1 <= n <= 10 your have to union 10 DFAs).

If you are asked to draw DFA that accepts binary strings such that decimal equivalent is divisible by 5 and 3 both then you are looking for DFA of divisible by 15 ( but what about 6 and 8?).

Note: DFAs drawn with this technique will be minimized DFA only when there is no common factor between number n and base e.g. there is no between 5 and 2 in first example, or between 5 and 3 in second example, hence both DFAs constructed above are minimized DFAs. If you are interested to read further about possible mini states for number n and base b read paper: Divisibility and State Complexity.

below I have added a Python script, I written it for fun while learning Python library pygraphviz. I am adding it I hope it can be helpful for someone in someway.

Design DFA for base 'b' number strings divisible by number 'n':

So we can apply above trick to draw DFA to recognize number strings in any base 'b' those are divisible a given number 'n'. In that DFA total number of states will be n (for n remainders) and number of edges should be equal to 'b' * 'n' — that is complete DFA: 'b' = number of symbols in language of DFA and 'n' = number of states.

Using above trick, below I have written a Python Script to Draw DFA for input base and number. In script, function divided_by_N populates DFA's transition rules in base * number steps. In each step-num, I convert num into number string num_s using function baseN(). To avoid processing each number string, I have used a temporary data-structure lookup_table. In each step, end-state for number string num_s is evaluated and stored in lookup_table to use in next step.

For transition graph of DFA, I have written a function draw_transition_graph using Pygraphviz library (very easy to use). To use this script you need to install graphviz. To add colorful edges in transition diagram, I randomly generates color codes for each symbol get_color_dict function.

#!/usr/bin/env python
import pygraphviz as pgv
from pprint import pprint
from random import choice as rchoice

def baseN(n, b, syms="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
    """ converts a number `n` into base `b` string """
    return ((n == 0) and syms[0]) or (
        baseN(n//b, b, syms).lstrip(syms[0]) + syms[n % b])

def divided_by_N(number, base):
    """
    constructs DFA that accepts given `base` number strings
    those are divisible by a given `number`
    """
    ACCEPTING_STATE = START_STATE = '0'
    SYMBOL_0 = '0'
    dfa = {
        str(from_state): {
            str(symbol): 'to_state' for symbol in range(base)
        }
        for from_state in range(number)
    }
    dfa[START_STATE][SYMBOL_0] = ACCEPTING_STATE
    # `lookup_table` keeps track: 'number string' -->[dfa]--> 'end_state'
    lookup_table = { SYMBOL_0: ACCEPTING_STATE }.setdefault
    for num in range(number * base):
        end_state = str(num % number)
        num_s = baseN(num, base)
        before_end_state = lookup_table(num_s[:-1], START_STATE)
        dfa[before_end_state][num_s[-1]] = end_state
        lookup_table(num_s, end_state)
    return dfa

def symcolrhexcodes(symbols):
    """
    returns dict of color codes mapped with alphabets symbol in symbols
    """
    return {
        symbol: '#'+''.join([
            rchoice("8A6C2B590D1F4E37") for _ in "FFFFFF"
        ])
        for symbol in symbols
    }

def draw_transition_graph(dfa, filename="filename"):
    ACCEPTING_STATE = START_STATE = '0'
    colors = symcolrhexcodes(dfa[START_STATE].keys())
    # draw transition graph
    tg = pgv.AGraph(strict=False, directed=True, decorate=True)
    for from_state in dfa:
        for symbol, to_state in dfa[from_state].iteritems():
            tg.add_edge("Q%s"%from_state, "Q%s"%to_state,
                        label=symbol, color=colors[symbol],
                        fontcolor=colors[symbol])

    # add intial edge from an invisible node!
    tg.add_node('null', shape='plaintext', label='start')
    tg.add_edge('null', "Q%s"%START_STATE,)

    # make end acception state as 'doublecircle'
    tg.get_node("Q%s"%ACCEPTING_STATE).attr['shape'] = 'doublecircle'
    tg.draw(filename, prog='circo')
    tg.close()

def print_transition_table(dfa):
    print("DFA accepting number string in base '%(base)s' "
            "those are divisible by '%(number)s':" % {
                'base': len(dfa['0']),
                'number': len(dfa),})
    pprint(dfa)

if __name__ == "__main__":
    number = input ("Enter NUMBER: ")
    base = input ("Enter BASE of number system: ")
    dfa = divided_by_N(number, base)

    print_transition_table(dfa)
    draw_transition_graph(dfa)

Execute it:

~/study/divide-5/script$ python script.py 
Enter NUMBER: 5
Enter BASE of number system: 4
DFA accepting number string in base '4' those are divisible by '5':
{'0': {'0': '0', '1': '1', '2': '2', '3': '3'},
 '1': {'0': '4', '1': '0', '2': '1', '3': '2'},
 '2': {'0': '3', '1': '4', '2': '0', '3': '1'},
 '3': {'0': '2', '1': '3', '2': '4', '3': '0'},
 '4': {'0': '1', '1': '2', '2': '3', '3': '4'}}
~/study/divide-5/script$ ls
script.py filename.png
~/study/divide-5/script$ display filename

Output:

base_4_divided_5_best
DFA accepting number strings in base 4 those are divisible by 5

Similarly, enter base = 4 and number = 7 to generate - dfa accepting number string in base '4' those are divisible by '7'
Btw, try changing filename to .png or .jpeg.

References those I use to write this script:
➊ Function baseN from "convert integer to a string in a given numeric base in python"
➋ To install "pygraphviz": "Python does not see pygraphviz"
➌ To learn use of Pygraphviz: "Python-FSM"
➍ To generate random hex color codes for each language symbol: "How would I make a random hexdigit code generator using .join and for loops?"

Synchronously waiting for an async operation, and why does Wait() freeze the program here

Calling async code from synchronous code can be quite tricky.

I explain the full reasons for this deadlock on my blog. In short, there's a "context" that is saved by default at the beginning of each await and used to resume the method.

So if this is called in an UI context, when the await completes, the async method tries to re-enter that context to continue executing. Unfortunately, code using Wait (or Result) will block a thread in that context, so the async method cannot complete.

The guidelines to avoid this are:

  1. Use ConfigureAwait(continueOnCapturedContext: false) as much as possible. This enables your async methods to continue executing without having to re-enter the context.
  2. Use async all the way. Use await instead of Result or Wait.

If your method is naturally asynchronous, then you (probably) shouldn't expose a synchronous wrapper.

Fastest way to add an Item to an Array

Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
ReDim Preserve arr (3)
arr(3)=newItem

for more info Redim

Python: For each list element apply a function across the list

If I'm correct in thinking that you want to find the minimum value of a function for all possible pairs of 2 elements from a list...

l = [1,2,3,4,5]

def f(i,j):
   return i+j 

# Prints min value of f(i,j) along with i and j
print min( (f(i,j),i,j) for i in l for j in l)

How to insert a line break <br> in markdown

I know this post is about adding a single line break but I thought I would mention that you can create multiple line breaks with the backslash (\) character:

Hello
\
\
\
World!

This would result in 3 new lines after "Hello". To clarify, that would mean 2 empty lines between "Hello" and "World!". It would display like this:


Hello



World!



Personally I find this cleaner for a large number of line breaks compared to using <br>.

Note that backslashes are not recommended for compatibility reasons. So this may not be supported by your Markdown parser but it's handy when it is.

How to include jQuery in ASP.Net project?

You might be looking for this Microsoft Ajax Content Delivery Network So you could just add

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>

To your aspx page.

jQuery UI: Datepicker set year range dropdown to 100 years

Try the following:-

ChangeYear:- When set to true, indicates that the cells of the previous or next month indicated in the calendar of the current month can be selected. This option is used with options.showOtherMonths set to true.

YearRange:- Specifies the range of years in the year dropdown. (Default value: “-10:+10")

Example:-

$(document).ready(function() {
    $("#date").datepicker({
        changeYear:true,
        yearRange: "2005:2015"
    });
});

See:- set year range in jquery datepicker

How to pass parameters in $ajax POST?

You can do it using $.ajax or $.post

Using $.ajax :

    $.ajax({
      type: 'post',
      url: 'superman',
      data: { 
        'field1': 'hello', 
        'field2': 'hello1'
      },
      success: function (response) {
        alert(response.status);
      },
      error: function () {
        alert("error");
      }
   });

Using $.post :

    $.post('superman',
      { 
        'field1': 'hello', 
        'field2': 'hello1'
      },
      function (response, status) {
        alert(response.status);
      }
    );

What is the meaning of "__attribute__((packed, aligned(4))) "

The attribute packed means that the compiler will not add padding between fields of the struct. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.

aligned(4) means that the struct should be aligned to an address that is divisible by 4.

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

my solution is to use a timeout. Seems to work ok

$('input[type=text]').focus(function() {
    var _this = this;
    setTimeout(function() {
        _this.select();
    }, 10);
});

Search of table names

I'm using this and works fine

SELECT * FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME LIKE '%%'

How does the communication between a browser and a web server take place?

Your browser is sitting on top of TCP/IP, as the web is based on standards, usually port 80, what happens is when you enter an address, such as google.com, your computer where the browser is running on, creates packets of data, encapsulated at each layer accordingly to the OSI standards, (think of envelopes of different sizes, packed into each envelope of next size), OSI defines 7 layers, in one of the envelopes contains the source address and destination address(that is the website) encoded in binary.

As it reaches the 1st layer, in OSI terms, it gets transmitted across the media transmitter (such as cable, DSL).

If you are connected via ISP, the layered pack of envelopes gets transmitted to the ISP, the ISP's network system, peeks through the layered pack of envelopes by decoding in reverse order to find out the address, then the ISP checks their Domain Name System database to find out if they have a route to that address (cached in memory, if it does, it forwards it across the internet network - again layered pack of envelopes).

If it doesn't, the ISP interrogates the top level DNS server to say 'Hey, get me the route for the address as supplied by you, ie. the browser', the top level DNS server then passes the route to the ISP which is then stored in the ISP's server memory.

The layered pack of envelopes are transmitted and received by the website server after successful routing of the packets (think of routing as signposts for directions to get to the server), which in turn, unpacks the layered pack of envelopes, extracts the source address and says 'Aha, that is for me, right, I know the destination address (that is you, the browser), then the server packetizes the webpages into a packed layered envelopes and sends it back (usually in reverse route, but not always the case).

Your browser than receives the packetized envelopes and unpacks each of them. Then your computer descrambles the data and your browser renders the pages on the screen.

I hope this answer is sufficient enough for your understanding.

fatal: could not create work tree dir 'kivy'

This does happened also when you are cloning a repo without selecting any working directory. just make sure you did cd into your working directory and i believe it will work just fine.

Using margin:auto to vertically-align a div

If you know the height of the div you want to center, you can position it absolutely within its parent and then set the top value to 50%. That will put the top of the child div 50% of the way down its parent, i.e. too low. Pull it back up by setting its margin-top to half its height. So now you have the vertical midpoint of the child div sitting at the vertical midpoint of the parent - vertically centered!

Example:

_x000D_
_x000D_
.black {_x000D_
    position:absolute;_x000D_
    top:0;_x000D_
    bottom:0;_x000D_
    left:0;_x000D_
    right:0;_x000D_
    background:rgba(0,0,0,.5);_x000D_
}_x000D_
.message {_x000D_
    background:yellow;_x000D_
    width:200px;_x000D_
    margin:auto auto;_x000D_
    padding:10px;_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    margin-top: -25px;_x000D_
    height: 50px;_x000D_
}
_x000D_
<div class="black">_x000D_
    <div class="message">_x000D_
        This is a popup message._x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/yWnZ2/2/

CSS3 Transition - Fade out effect

You forgot to add a position property to the .dummy-wrap class, and the top/left/bottom/right values don't apply to statically positioned elements (the default)

http://jsfiddle.net/dYBD2/2/

CMAKE_MAKE_PROGRAM not found

I tried to use CMake to build GammaRay for Qt on Windows with mingw. So, I had the Qt installed. And I had the same problem as other users here.

The approach that worked for me is launching cmake-gui from Qt build prompt (a shortcut created by Qt installer in "Start Menu\All programs\Qt{QT_VERSION}" folder).

How to get duration, as int milli's and float seconds from <chrono>?

I don't know what "milliseconds and float seconds" means, but this should give you an idea:

#include <chrono>
#include <thread>
#include <iostream>

int main()
{
  auto then = std::chrono::system_clock::now();
  std::this_thread::sleep_for(std::chrono::seconds(1));
  auto now = std::chrono::system_clock::now();
  auto dur = now - then;
  typedef std::chrono::duration<float> float_seconds;
  auto secs = std::chrono::duration_cast<float_seconds>(dur);
  std::cout << secs.count() << '\n';
}

Update records in table from CTE

Updates you make to the CTE will be cascaded to the source table.

I have had to guess at your schema slightly, but something like this should work.

;WITH T AS
(   SELECT  InvoiceNumber, 
            DocTotal, 
            SUM(Sale + VAT) OVER(PARTITION BY InvoiceNumber) AS NewDocTotal
    FROM    PEDI_InvoiceDetail
)
UPDATE  T
SET     DocTotal = NewDocTotal

JavaScript ternary operator example with functions

If you're going to nest ternary operators, I believe you'd want to do something like this:

   var audience = (countrycode == 'eu') ? 'audienceEU' :
                  (countrycode == 'jp') ? 'audienceJP' :
                  (countrycode == 'cn') ? 'audienceCN' :
                  'audienceUS';

It's a lot more efficient to write/read than:

var audience = 'audienceUS';
if countrycode == 'eu' {
   audience = 'audienceEU';
} else if countrycode == 'jp' {
   audience = 'audienceJP';
} else if countrycode == 'cn' {
   audience = 'audienceCN';
}

As with all good programming, whitespace makes everything nice for people who have to read your code after you're done with the project.

Best cross-browser method to capture CTRL+S with JQuery?

@Eevee: As the browser becomes the home for richer and richer functionality and starts to replace desktop apps, it's just not going to be an option to forgo the use of keyboard shortcuts. Gmail's rich and intuitive set of keyboard commands was instrumental in my willingness to abandon Outlook. The keyboard shortcuts in Todoist, Google Reader, and Google Calendar all make my life much, much easier on a daily basis.

Developers should definitely be careful not to override keystrokes that already have a meaning in the browser. For example, the WMD textbox I'm typing into inexplicably interprets Ctrl+Del as "Blockquote" rather than "delete word forward". I'm curious if there's a standard list somewhere of "browser-safe" shortcuts that site developers can use and that browsers will commit to staying away from in future versions.

disable a hyperlink using jQuery

The disabled attribute isn't valid on all HTML elements I believe, see the MSDN article. That and the proper value for disabled is simply "disabled". Your best approach is to bind a click function that returns false.

How to compile for Windows on Linux with gcc/g++?

For Fedora:

# Fedora 18 or greater
sudo dnf group install "MinGW cross-compiler"

# Or (not recommended, because of its deprecation)
sudo yum groupinstall -y "MinGW cross-compiler"

How can I capture packets in Android?

Option 1 - Android PCAP

Limitation

Android PCAP should work so long as:

Your device runs Android 4.0 or higher (or, in theory, the few devices which run Android 3.2). Earlier versions of Android do not have a USB Host API

Option 2 - TcpDump

Limitation

Phone should be rooted

Option 3 - bitshark (I would prefer this)

Limitation

Phone should be rooted

Reason - the generated PCAP files can be analyzed in WireShark which helps us in doing the analysis.

Other Options without rooting your phone

  1. tPacketCapture

https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture&hl=en

Advantages

Using tPacketCapture is very easy, captured packet save into a PCAP file that can be easily analyzed by using a network protocol analyzer application such as Wireshark.

  1. You can route your android mobile traffic to PC and capture the traffic in the desktop using any network sniffing tool.

http://lifehacker.com/5369381/turn-your-windows-7-pc-into-a-wireless-hotspot

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

If you want a table where only the columns scroll horizontally, you can position: absolute the first column (and specify its width explicitly), and then wrap the entire table in an overflow-x: scroll block. Don't bother trying this in IE7, however...

Relevant HTML & CSS:

_x000D_
_x000D_
table {_x000D_
  border-collapse: separate;_x000D_
  border-spacing: 0;_x000D_
  border-top: 1px solid grey;_x000D_
}_x000D_
_x000D_
td, th {_x000D_
  margin: 0;_x000D_
  border: 1px solid grey;_x000D_
  white-space: nowrap;_x000D_
  border-top-width: 0px;_x000D_
}_x000D_
_x000D_
div {_x000D_
  width: 500px;_x000D_
  overflow-x: scroll;_x000D_
  margin-left: 5em;_x000D_
  overflow-y: visible;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
.headcol {_x000D_
  position: absolute;_x000D_
  width: 5em;_x000D_
  left: 0;_x000D_
  top: auto;_x000D_
  border-top-width: 1px;_x000D_
  /*only relevant for first row*/_x000D_
  margin-top: -1px;_x000D_
  /*compensate for top border*/_x000D_
}_x000D_
_x000D_
.headcol:before {_x000D_
  content: 'Row ';_x000D_
}_x000D_
_x000D_
.long {_x000D_
  background: yellow;_x000D_
  letter-spacing: 1em;_x000D_
}
_x000D_
<div>_x000D_
<table>_x000D_
        <tr><th class="headcol">1</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">2</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">3</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">4</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">5</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">6</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
</table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle

JavaScript data grid for millions of rows

The best Grids in my opinion are below:

My best 3 options are jqGrid, jqxGrid and DataTables. They can work with thousands of rows and support virtualization.

Open mvc view in new window from controller

You can use as follows

public ActionResult NewWindow()
{
    return Content("<script>window.open('{url}','_blank')</script>");
}

iOS 7's blurred overlay effect using CSS?

This might help you!!

This Dynamically changes the background just IOS does

.myBox {
  width: 750px;
  height: 500px;
  border: rgba(0, 0, 0, 0.5) 1px solid;
  background-color: #ffffff;
}

.blurBg {
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

.blurBg img {
  -webkit-filter: blur(50px);
  margin-top: -150px;
  margin-left: -150px;
  width: 150%;
  opacity: 0.6;
}

How to define an empty object in PHP

stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.

When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.

<?php
// ways of creating stdClass instances
$x = new stdClass;
$y = (object) null;        // same as above
$z = (object) 'a';         // creates property 'scalar' = 'a'
$a = (object) array('property1' => 1, 'property2' => 'b');
?>

stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.

<?php
// CTest does not derive from stdClass
class CTest {
    public $property1;
}
$t = new CTest;
var_dump($t instanceof stdClass);            // false
var_dump(is_subclass_of($t, 'stdClass'));    // false
echo get_class($t) . "\n";                   // 'CTest'
echo get_parent_class($t) . "\n";            // false (no parent)
?>

You cannot define a class named 'stdClass' in your code. That name is already used by the system. You can define a class named 'Object'.

You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.

(tested on PHP 5.2.8)

How to select bottom most rows?

All you need to do is reverse your ORDER BY. Add or remove DESC to it.

Organizing a multiple-file Go project

Let's explorer how the go get repository_remote_url command manages the project structure under $GOPATH. If we do a go get github.com/gohugoio/hugo It will clone the repository under

$GOPATH/src/repository_remote/user_name/project_name


$GOPATH/src/github.com/gohugoio/hugo

This is a nice way to create your initial project path. Now let's explorer what are the project types out there and how their inner structures are organized. All golang projects in the community can be categorized under

  • Libraries (no executable binaries)
  • Single Project (contains only 1 executable binary)
  • Tooling Projects (contains multiple executable binaries)

Generally golang project files can be packaged under any design principles such as DDD, POD

Most of the available go projects follows this Package Oriented Design

Package Oriented Design encourage the developer to keeps the implementation only inside it's own packages, other than the /internal package those packages can't can communicate with each other


Libraries

  • Projects such as database drivers, qt can put under this category.
  • Some libraries such as color, now follows a flat structure without any other packages.
  • Most of these library projects manages a package called internal.
  • /internal package is mainly used to hide the implementation from other projects.
  • Don't have any executable binaries, so no files that contains the main func.

 ~/$GOPATH/
    bin/
    pkg/
    src/
      repository_remote/
        user_name/
            project_name/
              internal/
              other_pkg/

Single Project

  • Projects such as hugo, etcd has a single main func in root level and.
  • Target is to generate one single binary

Tooling Projects

  • Projects such as kubernetes, go-ethereum has multiple main func organized under a package called cmd
  • cmd/ package manages the number of binaries (tools) that we want to build

 ~/$GOPATH/
    bin/
    pkg/
    src/
      repository_remote/
        user_name/
            project_name/
              cmd/
                binary_one/
                   main.go
                binary_two/
                   main.go
                binary_three/
                   main.go
              other_pkg/

How to convert a huge list-of-vector to a matrix more efficiently?

This should be equivalent to your current code, only a lot faster:

output <- matrix(unlist(z), ncol = 10, byrow = TRUE)

Bootstrap alert in a fixed floating div at the top of page

Just wrap your inner message inside a div on which you apply your padding : http://jsfiddle.net/Ez9C4/

<div id="message">
    <div style="padding: 5px;">
        <div id="inner-message" class="alert alert-error">
            <button type="button" class="close" data-dismiss="alert">&times;</button>
            test error message
        </div>
    </div>
</div>

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

I had similar issue with creating custom TableCell. The issue was that I set FileOwner to my custom class and then connected outlets.

FileOwner should remain NSObject.

Stop Excel from automatically converting certain text values to dates

EASIEST SOLUTION I just figured this out today.

  • Open in Word
  • Replace all hyphens with en dashes
  • Save and Close
  • Open in Excel

Once you are done editing, you can always open it back up in Word again to replace the en dashes with hyphens again.

How do I update an entity using spring-data-jpa?

Specifically how do I tell spring-data-jpa that users that have the same username and firstname are actually EQUAL and that it is supposed to update the entity. Overriding equals did not work.

For this particular purpose one can introduce a composite key like this:

CREATE TABLE IF NOT EXISTS `test`.`user` (
  `username` VARCHAR(45) NOT NULL,
  `firstname` VARCHAR(45) NOT NULL,
  `description` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`username`, `firstname`))

Mapping:

@Embeddable
public class UserKey implements Serializable {
    protected String username;
    protected String firstname;

    public UserKey() {}

    public UserKey(String username, String firstname) {
        this.username = username;
        this.firstname = firstname;
    }
    // equals, hashCode
}

Here is how to use it:

@Entity
public class UserEntity implements Serializable {
    @EmbeddedId
    private UserKey primaryKey;

    private String description;

    //...
}

JpaRepository would look like this:

public interface UserEntityRepository extends JpaRepository<UserEntity, UserKey>

Then, you could use the following idiom: accept DTO with user info, extract name and firstname and create UserKey, then create a UserEntity with this composite key and then invoke Spring Data save() which should sort everything out for you.

printf with std::string?

printf accepts a variable number of arguments. Those can only have Plain Old Data (POD) types. Code that passes anything other than POD to printf only compiles because the compiler assumes you got your format right. %s means that the respective argument is supposed to be a pointer to a char. In your case it is an std::string not const char*. printf does not know it because the argument type goes lost and is supposed to be restored from the format parameter. When turning that std::string argument into const char* the resulting pointer will point to some irrelevant region of memory instead of your desired C string. For that reason your code prints out gibberish.

While printf is an excellent choice for printing out formatted text, (especially if you intend to have padding), it can be dangerous if you haven't enabled compiler warnings. Always enable warnings because then mistakes like this are easily avoidable. There is no reason to use the clumsy std::cout mechanism if the printf family can do the same task in a much faster and prettier way. Just make sure you have enabled all warnings (-Wall -Wextra) and you will be good. In case you use your own custom printf implementation you should declare it with the __attribute__ mechanism that enables the compiler to check the format string against the parameters provided.

How do I expand the output display to see more columns of a pandas DataFrame?

You can also try in a loop:

for col in df.columns: 
    print(col) 

Select SQL Server database size

Also compare the results with the following query's result

EXEC sp_helpdb @dbname= 'MSDB'

It produces result similar to the following

enter image description here

There is a good article - Different ways to determine free space for SQL Server databases and database files

HttpServletRequest - how to obtain the referring URL?

Actually it's: request.getHeader("Referer"), or even better, and to be 100% sure, request.getHeader(HttpHeaders.REFERER), where HttpHeaders is com.google.common.net.HttpHeaders

Capture key press (or keydown) event on DIV element

(1) Set the tabindex attribute:

<div id="mydiv" tabindex="0" />

(2) Bind to keydown:

 $('#mydiv').on('keydown', function(event) {
    //console.log(event.keyCode);
    switch(event.keyCode){
       //....your actions for the keys .....
    }
 });

To set the focus on start:

$(function() {
   $('#mydiv').focus();
});

To remove - if you don't like it - the div focus border, set outline: none in the CSS.

See the table of keycodes for more keyCode possibilities.

All of the code assuming you use jQuery.

#

Access POST values in Symfony2 request object

Symfony doc to get request data

Finally, the raw data sent with the request body can be accessed using getContent():

$content = $request->getContent();

Accessing dict_keys element by index in Python3

Python 3

mydict = {'a': 'one', 'b': 'two', 'c': 'three'}
mykeys = [*mydict]          #list of keys
myvals = [*mydict.values()] #list of values

print(mykeys)
print(myvals)

Output

['a', 'b', 'c']
['one', 'two', 'three']

Also see this detailed answer

Setting an image for a UIButton in code

In case of Swift User

// case of normal image
let image1 = UIImage(named: "your_image_file_name_without_extension")!
button1.setImage(image1, forState: UIControlState.Normal) 

// in case you don't want image to change when "clicked", you can leave code below
// case of when button is clicked
let image2 = UIImage(named: "image_clicked")!
button1.setImage(image2, forState: UIControlState.Highlight) 

SVN how to resolve new tree conflicts when file is added on two branches

I found a post suggesting a solution for that. It's about to run:

svn resolve --accept working <YourPath>

which will claim the local version files as OK.
You can run it for single file or entire project catalogues.

Convert dd-mm-yyyy string to date

You can also write a date inside the parentheses of the Date() object, like these:

new Date("Month dd, yyyy hh:mm:ss")
new Date("Month dd, yyyy")
new Date(yyyy,mm,dd,hh,mm,ss)
new Date(yyyy,mm,dd)
new Date(milliseconds)

space between divs - display table-cell

Use transparent borders if possible.

JSFiddle Demo

https://jsfiddle.net/74q3na62/

HTML

<div class="table">
    <div class="row">
        <div class="cell">Cell 1</div>
        <div class="cell">Cell 2</div>
        <div class="cell">Cell 3</div>
    </div>
</div>

CSS

.table {
  display: table;
  border: 1px solid black;
}

.row { display:table-row; }

.cell {
  display: table-cell;
  background-clip: padding-box;
  background-color: gold;
  border-right: 10px solid transparent;
}

.cell:last-child {
  border-right: 0 none;
}

Explanation

You could use the border-spacing property, as the accepted answer suggests, but this not only generates space between the table cells but also between the table cells and the table container. This may be unwanted.

If you don't need visible borders on your table cells you should therefore use transparent borders to generate cell margins. Transparent borders require setting background-clip: padding-box; because otherwise the background color of the table cells is displayed on the border.

Transparent borders and background-clip are supported in IE9 upwards (and all other modern browsers). If you need IE8 compatibility or don't need actual transparent space you can simply set a white border color and leave the background-clip out.

Make git automatically remove trailing whitespace before committing

Those settings (core.whitespace and apply.whitespace) are not there to remove trailing whitespace but to:

  • core.whitespace: detect them, and raise errors
  • apply.whitespace: and strip them, but only during patch, not "always automatically"

I believe the git hook pre-commit would do a better job for that (includes removing trailing whitespace)


Note that at any given time you can choose to not run the pre-commit hook:

  • temporarily: git commit --no-verify .
  • permanently: cd .git/hooks/ ; chmod -x pre-commit

Warning: by default, a pre-commit script (like this one), has not a "remove trailing" feature", but a "warning" feature like:

if (/\s$/) {
    bad_line("trailing whitespace", $_);
}

You could however build a better pre-commit hook, especially when you consider that:

Committing in Git with only some changes added to the staging area still results in an “atomic” revision that may never have existed as a working copy and may not work.


For instance, oldman proposes in another answer a pre-commit hook which detects and remove whitespace.
Since that hook get the file name of each file, I would recommend to be careful for certain type of files: you don't want to remove trailing whitespace in .md (markdown) files!

How to select all elements with a particular ID in jQuery?

Can you assign a unique CSS class to each distinct timer? That way you could use the selector for the CSS class, which would work fine with multiple div elements.

Differences between SP initiated SSO and IDP initiated SSO

SP Initiated SSO

Bill the user: "Hey Jimmy, show me that report"

Jimmy the SP: "Hey, I'm not sure who you are yet. We have a process here so you go get yourself verified with Bob the IdP first. I trust him."

Bob the IdP: "I see Jimmy sent you here. Please give me your credentials."

Bill the user: "Hi I'm Bill. Here are my credentials."

Bob the IdP: "Hi Bill. Looks like you check out."

Bob the IdP: "Hey Jimmy. This guy Bill checks out and here's some additional information about him. You do whatever you want from here."

Jimmy the SP: "Ok cool. Looks like Bill is also in our list of known guests. I'll let Bill in."

IdP Initiated SSO

Bill the user: "Hey Bob. I want to go to Jimmy's place. Security is tight over there."

Bob the IdP: "Hey Jimmy. I trust Bill. He checks out and here's some additional information about him. You do whatever you want from here."

Jimmy the SP: "Ok cool. Looks like Bill is also in our list of known guests. I'll let Bill in."


I go into more detail here, but still keeping things simple: https://jorgecolonconsulting.com/saml-sso-in-simple-terms/.

Stop node.js program from command line

If you are running Node.js interactively (the REPL):

Ctrl + C will take back you to > prompt then type:

process.exit()

or just use Ctrl + D.

How to check the extension of a filename in a bash script?

I wrote a bash script that looks at the type of a file then copies it to a location, I use it to look through the videos I've watched online from my firefox cache:

#!/bin/bash
# flvcache script

CACHE=~/.mozilla/firefox/xxxxxxxx.default/Cache
OUTPUTDIR=~/Videos/flvs
MINFILESIZE=2M

for f in `find $CACHE -size +$MINFILESIZE`
do
    a=$(file $f | cut -f2 -d ' ')
    o=$(basename $f)
    if [ "$a" = "Macromedia" ]
        then
            cp "$f" "$OUTPUTDIR/$o"
    fi
done

nautilus  "$OUTPUTDIR"&

It uses similar ideas to those presented here, hope this is helpful to someone.

Where to change default pdf page width and font size in jspdf.debug.js?

For anyone trying to this in react. There is a slight difference.

// Document of 8.5 inch width and 11 inch high
new jsPDF('p', 'in', [612, 792]);

or

// Document of 8.5 inch width and 11 inch high
new jsPDF({
        orientation: 'p', 
        unit: 'in', 
        format: [612, 792]
});

When i tried the @Aidiakapi solution the pages were tiny. For a difference size take size in inches * 72 to get the dimensions you need. For example, i wanted 8.5 so 8.5 * 72 = 612. This is for [email protected].

List of All Locales and Their Short Codes?

While accepted answer is pretty complete (I used myself in similar question that arised to me), I think it is worth to put the whole supported language codes and variations, as well as encodings, and point user to a file which is present in almost any linux distributions, in case he simply wants a quicker answer and no internet for example.

This is the file /usr/share/i18n/SUPPORTED and its contents:

aa_DJ.UTF-8 UTF-8
aa_DJ ISO-8859-1
aa_ER UTF-8
aa_ER@saaho UTF-8
aa_ET UTF-8
af_ZA.UTF-8 UTF-8
af_ZA ISO-8859-1
am_ET UTF-8
an_ES.UTF-8 UTF-8
an_ES ISO-8859-15
ar_AE.UTF-8 UTF-8
ar_AE ISO-8859-6
ar_BH.UTF-8 UTF-8
ar_BH ISO-8859-6
ar_DZ.UTF-8 UTF-8
ar_DZ ISO-8859-6
ar_EG.UTF-8 UTF-8
ar_EG ISO-8859-6
ar_IN UTF-8
ar_IQ.UTF-8 UTF-8
ar_IQ ISO-8859-6
ar_JO.UTF-8 UTF-8
ar_JO ISO-8859-6
ar_KW.UTF-8 UTF-8
ar_KW ISO-8859-6
ar_LB.UTF-8 UTF-8
ar_LB ISO-8859-6
ar_LY.UTF-8 UTF-8
ar_LY ISO-8859-6
ar_MA.UTF-8 UTF-8
ar_MA ISO-8859-6
ar_OM.UTF-8 UTF-8
ar_OM ISO-8859-6
ar_QA.UTF-8 UTF-8
ar_QA ISO-8859-6
ar_SA.UTF-8 UTF-8
ar_SA ISO-8859-6
ar_SD.UTF-8 UTF-8
ar_SD ISO-8859-6
ar_SY.UTF-8 UTF-8
ar_SY ISO-8859-6
ar_TN.UTF-8 UTF-8
ar_TN ISO-8859-6
ar_YE.UTF-8 UTF-8
ar_YE ISO-8859-6
az_AZ UTF-8
as_IN UTF-8
ast_ES.UTF-8 UTF-8
ast_ES ISO-8859-15
be_BY.UTF-8 UTF-8
be_BY CP1251
be_BY@latin UTF-8
bem_ZM UTF-8
ber_DZ UTF-8
ber_MA UTF-8
bg_BG.UTF-8 UTF-8
bg_BG CP1251
bho_IN UTF-8
bn_BD UTF-8
bn_IN UTF-8
bo_CN UTF-8
bo_IN UTF-8
br_FR.UTF-8 UTF-8
br_FR ISO-8859-1
br_FR@euro ISO-8859-15
brx_IN UTF-8
bs_BA.UTF-8 UTF-8
bs_BA ISO-8859-2
byn_ER UTF-8
ca_AD.UTF-8 UTF-8
ca_AD ISO-8859-15
ca_ES.UTF-8 UTF-8
ca_ES ISO-8859-1
ca_ES@euro ISO-8859-15
ca_FR.UTF-8 UTF-8
ca_FR ISO-8859-15
ca_IT.UTF-8 UTF-8
ca_IT ISO-8859-15
crh_UA UTF-8
cs_CZ.UTF-8 UTF-8
cs_CZ ISO-8859-2
csb_PL UTF-8
cv_RU UTF-8
cy_GB.UTF-8 UTF-8
cy_GB ISO-8859-14
da_DK.UTF-8 UTF-8
da_DK ISO-8859-1
de_AT.UTF-8 UTF-8
de_AT ISO-8859-1
de_AT@euro ISO-8859-15
de_BE.UTF-8 UTF-8
de_BE ISO-8859-1
de_BE@euro ISO-8859-15
de_CH.UTF-8 UTF-8
de_CH ISO-8859-1
de_DE.UTF-8 UTF-8
de_DE ISO-8859-1
de_DE@euro ISO-8859-15
de_LU.UTF-8 UTF-8
de_LU ISO-8859-1
de_LU@euro ISO-8859-15
dv_MV UTF-8
dz_BT UTF-8
el_GR.UTF-8 UTF-8
el_GR ISO-8859-7
el_CY.UTF-8 UTF-8
el_CY ISO-8859-7
en_AG UTF-8
en_AU.UTF-8 UTF-8
en_AU ISO-8859-1
en_BW.UTF-8 UTF-8
en_BW ISO-8859-1
en_CA.UTF-8 UTF-8
en_CA ISO-8859-1
en_DK.UTF-8 UTF-8
en_DK ISO-8859-1
en_GB.UTF-8 UTF-8
en_GB ISO-8859-1
en_HK.UTF-8 UTF-8
en_HK ISO-8859-1
en_IE.UTF-8 UTF-8
en_IE ISO-8859-1
en_IE@euro ISO-8859-15
en_IN UTF-8
en_NG UTF-8
en_NZ.UTF-8 UTF-8
en_NZ ISO-8859-1
en_PH.UTF-8 UTF-8
en_PH ISO-8859-1
en_SG.UTF-8 UTF-8
en_SG ISO-8859-1
en_US.UTF-8 UTF-8
en_US ISO-8859-1
en_ZA.UTF-8 UTF-8
en_ZA ISO-8859-1
en_ZM UTF-8
en_ZW.UTF-8 UTF-8
en_ZW ISO-8859-1
es_AR.UTF-8 UTF-8
es_AR ISO-8859-1
es_BO.UTF-8 UTF-8
es_BO ISO-8859-1
es_CL.UTF-8 UTF-8
es_CL ISO-8859-1
es_CO.UTF-8 UTF-8
es_CO ISO-8859-1
es_CR.UTF-8 UTF-8
es_CR ISO-8859-1
es_CU UTF-8
es_DO.UTF-8 UTF-8
es_DO ISO-8859-1
es_EC.UTF-8 UTF-8
es_EC ISO-8859-1
es_ES.UTF-8 UTF-8
es_ES ISO-8859-1
es_ES@euro ISO-8859-15
es_GT.UTF-8 UTF-8
es_GT ISO-8859-1
es_HN.UTF-8 UTF-8
es_HN ISO-8859-1
es_MX.UTF-8 UTF-8
es_MX ISO-8859-1
es_NI.UTF-8 UTF-8
es_NI ISO-8859-1
es_PA.UTF-8 UTF-8
es_PA ISO-8859-1
es_PE.UTF-8 UTF-8
es_PE ISO-8859-1
es_PR.UTF-8 UTF-8
es_PR ISO-8859-1
es_PY.UTF-8 UTF-8
es_PY ISO-8859-1
es_SV.UTF-8 UTF-8
es_SV ISO-8859-1
es_US.UTF-8 UTF-8
es_US ISO-8859-1
es_UY.UTF-8 UTF-8
es_UY ISO-8859-1
es_VE.UTF-8 UTF-8
es_VE ISO-8859-1
et_EE.UTF-8 UTF-8
et_EE ISO-8859-1
et_EE.ISO-8859-15 ISO-8859-15
eu_ES.UTF-8 UTF-8
eu_ES ISO-8859-1
eu_ES@euro ISO-8859-15
fa_IR UTF-8
ff_SN UTF-8
fi_FI.UTF-8 UTF-8
fi_FI ISO-8859-1
fi_FI@euro ISO-8859-15
fil_PH UTF-8
fo_FO.UTF-8 UTF-8
fo_FO ISO-8859-1
fr_BE.UTF-8 UTF-8
fr_BE ISO-8859-1
fr_BE@euro ISO-8859-15
fr_CA.UTF-8 UTF-8
fr_CA ISO-8859-1
fr_CH.UTF-8 UTF-8
fr_CH ISO-8859-1
fr_FR.UTF-8 UTF-8
fr_FR ISO-8859-1
fr_FR@euro ISO-8859-15
fr_LU.UTF-8 UTF-8
fr_LU ISO-8859-1
fr_LU@euro ISO-8859-15
fur_IT UTF-8
fy_NL UTF-8
fy_DE UTF-8
ga_IE.UTF-8 UTF-8
ga_IE ISO-8859-1
ga_IE@euro ISO-8859-15
gd_GB.UTF-8 UTF-8
gd_GB ISO-8859-15
gez_ER UTF-8
gez_ER@abegede UTF-8
gez_ET UTF-8
gez_ET@abegede UTF-8
gl_ES.UTF-8 UTF-8
gl_ES ISO-8859-1
gl_ES@euro ISO-8859-15
gu_IN UTF-8
gv_GB.UTF-8 UTF-8
gv_GB ISO-8859-1
ha_NG UTF-8
he_IL.UTF-8 UTF-8
he_IL ISO-8859-8
hi_IN UTF-8
hne_IN UTF-8
hr_HR.UTF-8 UTF-8
hr_HR ISO-8859-2
hsb_DE ISO-8859-2
hsb_DE.UTF-8 UTF-8
ht_HT UTF-8
hu_HU.UTF-8 UTF-8
hu_HU ISO-8859-2
hy_AM UTF-8
hy_AM.ARMSCII-8 ARMSCII-8
id_ID.UTF-8 UTF-8
id_ID ISO-8859-1
ig_NG UTF-8
ik_CA UTF-8
is_IS.UTF-8 UTF-8
is_IS ISO-8859-1
it_CH.UTF-8 UTF-8
it_CH ISO-8859-1
it_IT.UTF-8 UTF-8
it_IT ISO-8859-1
it_IT@euro ISO-8859-15
iu_CA UTF-8
iw_IL.UTF-8 UTF-8
iw_IL ISO-8859-8
ja_JP.EUC-JP EUC-JP
ja_JP.UTF-8 UTF-8
ka_GE.UTF-8 UTF-8
ka_GE GEORGIAN-PS
kk_KZ.UTF-8 UTF-8
kk_KZ PT154
kl_GL.UTF-8 UTF-8
kl_GL ISO-8859-1
km_KH UTF-8
kn_IN UTF-8
ko_KR.EUC-KR EUC-KR
ko_KR.UTF-8 UTF-8
kok_IN UTF-8
ks_IN UTF-8
ks_IN@devanagari UTF-8
ku_TR.UTF-8 UTF-8
ku_TR ISO-8859-9
kw_GB.UTF-8 UTF-8
kw_GB ISO-8859-1
ky_KG UTF-8
lb_LU UTF-8
lg_UG.UTF-8 UTF-8
lg_UG ISO-8859-10
li_BE UTF-8
li_NL UTF-8
lij_IT UTF-8
lo_LA UTF-8
lt_LT.UTF-8 UTF-8
lt_LT ISO-8859-13
lv_LV.UTF-8 UTF-8
lv_LV ISO-8859-13
mag_IN UTF-8
mai_IN UTF-8
mg_MG.UTF-8 UTF-8
mg_MG ISO-8859-15
mhr_RU UTF-8
mi_NZ.UTF-8 UTF-8
mi_NZ ISO-8859-13
mk_MK.UTF-8 UTF-8
mk_MK ISO-8859-5
ml_IN UTF-8
mn_MN UTF-8
mr_IN UTF-8
ms_MY.UTF-8 UTF-8
ms_MY ISO-8859-1
mt_MT.UTF-8 UTF-8
mt_MT ISO-8859-3
my_MM UTF-8
nan_TW@latin UTF-8
nb_NO.UTF-8 UTF-8
nb_NO ISO-8859-1
nds_DE UTF-8
nds_NL UTF-8
ne_NP UTF-8
nl_AW UTF-8
nl_BE.UTF-8 UTF-8
nl_BE ISO-8859-1
nl_BE@euro ISO-8859-15
nl_NL.UTF-8 UTF-8
nl_NL ISO-8859-1
nl_NL@euro ISO-8859-15
nn_NO.UTF-8 UTF-8
nn_NO ISO-8859-1
nr_ZA UTF-8
nso_ZA UTF-8
oc_FR.UTF-8 UTF-8
oc_FR ISO-8859-1
om_ET UTF-8
om_KE.UTF-8 UTF-8
om_KE ISO-8859-1
or_IN UTF-8
os_RU UTF-8
pa_IN UTF-8
pa_PK UTF-8
pap_AN UTF-8
pl_PL.UTF-8 UTF-8
pl_PL ISO-8859-2
ps_AF UTF-8
pt_BR.UTF-8 UTF-8
pt_BR ISO-8859-1
pt_PT.UTF-8 UTF-8
pt_PT ISO-8859-1
pt_PT@euro ISO-8859-15
ro_RO.UTF-8 UTF-8
ro_RO ISO-8859-2
ru_RU.KOI8-R KOI8-R
ru_RU.UTF-8 UTF-8
ru_RU ISO-8859-5
ru_UA.UTF-8 UTF-8
ru_UA KOI8-U
rw_RW UTF-8
sa_IN UTF-8
sc_IT UTF-8
sd_IN UTF-8
sd_IN@devanagari UTF-8
se_NO UTF-8
shs_CA UTF-8
si_LK UTF-8
sid_ET UTF-8
sk_SK.UTF-8 UTF-8
sk_SK ISO-8859-2
sl_SI.UTF-8 UTF-8
sl_SI ISO-8859-2
so_DJ.UTF-8 UTF-8
so_DJ ISO-8859-1
so_ET UTF-8
so_KE.UTF-8 UTF-8
so_KE ISO-8859-1
so_SO.UTF-8 UTF-8
so_SO ISO-8859-1
sq_AL.UTF-8 UTF-8
sq_AL ISO-8859-1
sq_MK UTF-8
sr_ME UTF-8
sr_RS UTF-8
sr_RS@latin UTF-8
ss_ZA UTF-8
st_ZA.UTF-8 UTF-8
st_ZA ISO-8859-1
sv_FI.UTF-8 UTF-8
sv_FI ISO-8859-1
sv_FI@euro ISO-8859-15
sv_SE.UTF-8 UTF-8
sv_SE ISO-8859-1
sw_KE UTF-8
sw_TZ UTF-8
ta_IN UTF-8
ta_LK UTF-8
te_IN UTF-8
tg_TJ.UTF-8 UTF-8
tg_TJ KOI8-T
th_TH.UTF-8 UTF-8
th_TH TIS-620
ti_ER UTF-8
ti_ET UTF-8
tig_ER UTF-8
tk_TM UTF-8
tl_PH.UTF-8 UTF-8
tl_PH ISO-8859-1
tn_ZA UTF-8
tr_CY.UTF-8 UTF-8
tr_CY ISO-8859-9
tr_TR.UTF-8 UTF-8
tr_TR ISO-8859-9
ts_ZA UTF-8
tt_RU UTF-8
tt_RU@iqtelif UTF-8
ug_CN UTF-8
uk_UA.UTF-8 UTF-8
uk_UA KOI8-U
unm_US UTF-8
ur_IN UTF-8
ur_PK UTF-8
uz_UZ ISO-8859-1
uz_UZ@cyrillic UTF-8
ve_ZA UTF-8
vi_VN UTF-8
wa_BE ISO-8859-1
wa_BE@euro ISO-8859-15
wa_BE.UTF-8 UTF-8
wae_CH UTF-8
wal_ET UTF-8
wo_SN UTF-8
xh_ZA.UTF-8 UTF-8
xh_ZA ISO-8859-1
yi_US.UTF-8 UTF-8
yi_US CP1255
yo_NG UTF-8
yue_HK UTF-8
zh_CN.GB18030 GB18030
zh_CN.GBK GBK
zh_CN.UTF-8 UTF-8
zh_CN GB2312
zh_HK.UTF-8 UTF-8
zh_HK BIG5-HKSCS
zh_SG.UTF-8 UTF-8
zh_SG.GBK GBK
zh_SG GB2312
zh_TW.EUC-TW EUC-TW
zh_TW.UTF-8 UTF-8
zh_TW BIG5
zu_ZA.UTF-8 UTF-8
zu_ZA ISO-8859-1

Unable to login to SQL Server + SQL Server Authentication + Error: 18456

You need to enable SQL Server Authentication:

  1. In the Object Explorer, right click on the server and click on "Properties"

DBMS Properties dialog

  1. In the "Server Properties" window click on "Security" in the list of pages on the left. Under "Server Authentication" choose the "SQL Server and Windows Authentication mode" radio option.

SQL Server Authentication dialog

  1. Restart the SQLEXPRESS service.

Graphical user interface Tutorial in C

You can also have a look at FLTK (C++ and not plain C though)

FLTK (pronounced "fulltick") is a cross-platform C++ GUI toolkit for UNIX®/Linux® (X11), Microsoft® Windows®, and MacOS® X. FLTK provides modern GUI functionality without the bloat and supports 3D graphics via OpenGL® and its built-in GLUT emulation.

FLTK is designed to be small and modular enough to be statically linked, but works fine as a shared library. FLTK also includes an excellent UI builder called FLUID that can be used to create applications in minutes.

Here are some quickstart screencasts

[Happy New Year!]

Git Clone from GitHub over https with two-factor authentication

1st: Get personal access token. https://github.com/settings/tokens
2nd: Put account & the token. Example is here:

$ git push
Username for 'https://github.com':            # Put your GitHub account name
Password for 'https://{USERNAME}@github.com': # Put your Personal access token

Link on how to create a personal access token: https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line

convert month from name to number

Maybe use a combination with strtotime() and date()?

MySQL - Get row number on select

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

Running EXE with parameters

System.Diagnostics.Process.Start("PATH to exe", "Command Line Arguments");

UIWebView open links in Safari

The other answers have one problem: they rely on the action you do and not on the link itself to decide whether to load it in Safari or in webview.

Now sometimes this is exactly what you want, which is fine; but some other times, especially if you have anchor links in your page, you want really to open only external links in Safari, and not internal ones. In that case you should check the URL.host property of your request.

I use that piece of code to check whether I have a hostname in the URL that is being parsed, or if it is embedded html:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    static NSString *regexp = @"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9-]*[a-zA-Z0-9])[.])+([A-Za-z]|[A-Za-z][A-Za-z0-9-]*[A-Za-z0-9])$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexp];

    if ([predicate evaluateWithObject:request.URL.host]) {
        [[UIApplication sharedApplication] openURL:request.URL];
        return NO; 
    } else {
        return YES; 
    }
}

You can of course adapt the regular expression to fit your needs.

Enable the display of line numbers in Visual Studio

Visual studio 2015 enterprice

Tools -> Options -> Text Editor -> All Languages -> check Line Numbers

https://msdn.microsoft.com/en-us/library/ms165340.aspxenter image description here

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

you can download and install db2client and looking for - db2jcc.jar - db2jcc_license_cisuz.jar - db2jcc_license_cu.jar - and etc. at C:\Program Files (x86)\IBM\SQLLIB\java

How to write to an existing excel file without overwriting data (using pandas)?

book = load_workbook(xlsFilename)
writer = pd.ExcelWriter(self.xlsFilename)
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df.to_excel(writer, sheet_name=sheetName, index=False)
writer.save()

Get Return Value from Stored procedure in asp.net

Procedure never returns a value.You have to use a output parameter in store procedure.

ALTER PROC TESTLOGIN
@UserName   varchar(50),
@password   varchar(50)
@retvalue int output
 as
 Begin
    declare @return     int 
    set @return  = (Select COUNT(*) 
    FROM    CPUser  
    WHERE   UserName = @UserName AND Password = @password)

   set @retvalue=@return
  End

Then you have to add a sqlparameter from c# whose parameter direction is out. Hope this make sense.

How to check whether dynamically attached event listener exists or not?

I usually attach a class to the element then check if the class exist like this:

let element = document.getElementsById("someElement");

if(!element.classList.contains('attached-listener'))
   element.addEventListener("click", this.itemClicked);

element.classList.add('attached-listener');

Automatically open default email client and pre-populate content

Implemented this way without using Jquery:

<button class="emailReplyButton" onClick="sendEmail(message)">Reply</button>

sendEmail(message) {
    var email = message.emailId;
    var subject = message.subject;
    var emailBody = 'Hi '+message.from;
    document.location = "mailto:"+email+"?subject="+subject+"&body="+emailBody;
}

How to make a input field readonly with JavaScript?

document.getElementById("").readOnly = true

How to write an XPath query to match two attributes?

//div[@id='..' and @class='...]

should do the trick. That's selecting the div operators that have both attributes of the required value.

It's worth using one of the online XPath testbeds to try stuff out.

if else in a list comprehension

One way:

def change(f):
    if f is None:
        return unicode(f.strip())
    else:
        return ''

row = [change(x) for x in row]

Although then you have:

row = map(change, row)

Or you can use a lambda inline.

Trigger change event <select> using jquery

$('#edit_user_details').find('select').trigger('change');

It would change the select html tag drop-down item with id="edit_user_details".

Like Operator in Entity Framework?

I don't know anything about EF really, but in LINQ to SQL you usually express a LIKE clause using String.Contains:

where entity.Name.Contains("xyz")

translates to

WHERE Name LIKE '%xyz%'

(Use StartsWith and EndsWith for other behaviour.)

I'm not entirely sure whether that's helpful, because I don't understand what you mean when you say you're trying to implement LIKE. If I've misunderstood completely, let me know and I'll delete this answer :)

How do I add PHP code/file to HTML(.html) files?

You can modify .htaccess like others said, but the fastest solution is to rename the file extension to .php

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

A slightly more concise example that builds on top of the other answers here. I leveraged the code generation that is shipped with Visual Studio to remove most of the extra invocation code and replaced it with typed objects instead.

    using System;
    using System.Management;

    namespace Utils
    {
        class NetworkManagement
        {
            /// <summary>
            /// Returns a list of all the network interface class names that are currently enabled in the system
            /// </summary>
            /// <returns>list of nic names</returns>
            public static string[] GetAllNicDescriptions()
            {
                List<string> nics = new List<string>();

                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (var networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (var config in networkConfigs.Cast<ManagementObject>()
                                                                           .Where(mo => (bool)mo["IPEnabled"])
                                                                           .Select(x=> new NetworkAdapterConfiguration(x)))
                        {
                            nics.Add(config.Description);
                        }
                    }
                }

                return nics.ToArray();
            }

            /// <summary>
            /// Set's the DNS Server of the local machine
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            /// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
            /// <remarks>Requires a reference to the System.Management namespace</remarks>
            public static bool SetNameservers(string nicDescription, string[] dnsServers, bool restart = false)
            {
                using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription))
                        {
                            // NAC class was generated by opening a developer console and entering:
                            // mgmtclassgen Win32_NetworkAdapterConfiguration -p NetworkAdapterConfiguration.cs
                            // See: http://blog.opennetcf.com/2008/06/24/disableenable-network-connections-under-vista/

                            using (NetworkAdapterConfiguration config = new NetworkAdapterConfiguration(mboDNS))
                            {
                                if (config.SetDNSServerSearchOrder(dnsServers) == 0)
                                {
                                    RestartNetworkAdapter(nicDescription);
                                }
                            }
                        }
                    }
                }

                return false;
            }

            /// <summary>
            /// Restarts a given Network adapter
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            public static void RestartNetworkAdapter(string nicDescription)
            {
                using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapter"))
                {
                    using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo=> (string)mo["Description"] == nicDescription))
                        {
                            // NA class was generated by opening dev console and entering
                            // mgmtclassgen Win32_NetworkAdapter -p NetworkAdapter.cs
                            using (NetworkAdapter adapter = new NetworkAdapter(mboDNS))
                            {
                                adapter.Disable();
                                adapter.Enable();
                                Thread.Sleep(4000); // Wait a few secs until exiting, this will give the NIC enough time to re-connect
                                return;
                            }
                        }
                    }
                }
            }

            /// <summary>
            /// Get's the DNS Server of the local machine
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            public static string[] GetNameservers(string nicDescription)
            {
                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (var networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (var config  in networkConfigs.Cast<ManagementObject>()
                                                              .Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)
                                                              .Select( x => new NetworkAdapterConfiguration(x)))
                        {
                            return config.DNSServerSearchOrder;
                        }
                    }
                }

                return null;
            }

            /// <summary>
            /// Set's a new IP Address and it's Submask of the local machine
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            /// <param name="ipAddresses">The IP Address</param>
            /// <param name="subnetMask">The Submask IP Address</param>
            /// <param name="gateway">The gateway.</param>
            /// <remarks>Requires a reference to the System.Management namespace</remarks>
            public static void SetIP(string nicDescription, string[] ipAddresses, string subnetMask, string gateway)
            {
                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (var networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (var config in networkConfigs.Cast<ManagementObject>()
                                                                       .Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)
                                                                       .Select( x=> new NetworkAdapterConfiguration(x)))
                        {
                            // Set the new IP and subnet masks if needed
                            config.EnableStatic(ipAddresses, Array.ConvertAll(ipAddresses, _ => subnetMask));

                            // Set mew gateway if needed
                            if (!String.IsNullOrEmpty(gateway))
                            {
                                config.SetGateways(new[] {gateway}, new ushort[] {1});
                            }
                        }
                    }
                }
            }

        }
    }

Full source: https://github.com/sverrirs/DnsHelper/blob/master/src/DnsHelperUI/NetworkManagement.cs