Programs & Examples On #Python interactive

Marker in leaflet, click event

The accepted answer is correct. However, I needed a little bit more clarity, so in case someone else does too:

Leaflet allows events to fire on virtually anything you do on its map, in this case a marker.

So you could create a marker as suggested by the question above:

L.marker([10.496093,-66.881935]).addTo(map).on('mouseover', onClick);

Then create the onClick function:

function onClick(e) {
    alert(this.getLatLng());
}

Now anytime you mouseover that marker it will fire an alert of the current lat/long.

However, you could use 'click', 'dblclick', etc. instead of 'mouseover' and instead of alerting lat/long you can use the body of onClick to do anything else you want:

L.marker([10.496093,-66.881935]).addTo(map).on('click', function(e) {
    console.log(e.latlng);
});

Here is the documentation: http://leafletjs.com/reference.html#events

React Native android build failed. SDK location not found

Check out in your local.properties file:

sdk.dir=C\:\\Users\\USERNAME\\AppData\\Local\\Android\\sdk

if the format is proper or not

Certificate has either expired or has been revoked

If you have a host test target that you run on the device, make sure that it uses the same code signing identity that the app target uses. Otherwise you will have to clean when you switch between testing and debugging the app.

I had this issue in Xcode 11.4.1 when we turned off code signing in our host test target as a build-time enhancement. Once I turned code signing back on for the host test, I no longer experienced this issue when switching between running the host test target and the app!

converting epoch time with milliseconds to datetime

Use datetime.datetime.fromtimestamp:

>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time
>>> s, ms = divmod(1236472051807, 1000)  # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

To add more information to the correct answer above, after reading an example from Android-er I found you can easily convert your preference activity into a preference fragment. If you have the following activity:

public class MyPreferenceActivity extends PreferenceActivity
{
    @Override
    protected void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.my_preference_screen);
    }
}

The only changes you have to make is to create an internal fragment class, move the addPreferencesFromResources() into the fragment, and invoke the fragment from the activity, like this:

public class MyPreferenceActivity extends PreferenceActivity
{
    @Override
    protected void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
    }

    public static class MyPreferenceFragment extends PreferenceFragment
    {
        @Override
        public void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.my_preference_screen);
        }
    }
}

There may be other subtleties to making more complex preferences from fragments; if so, I hope someone notes them here.

Cannot execute RUN mkdir in a Dockerfile

When creating subdirectories hanging off from a non-existing parent directory(s) you must pass the -p flag to mkdir ... Please update your Dockerfile with

RUN mkdir -p ... 

I tested this and it's correct.

Get local IP address

I think using LINQ is easier:

Dns.GetHostEntry(Dns.GetHostName())
   .AddressList
   .First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
   .ToString()

Opening a remote machine's Windows C drive

If you need a drive letter (some applications don't like UNC style paths that start with a machine-name) you can "map a drive" to a UNC path. Right-click on "My Computer" and select Map Network Drive... or use this command line:

NET USE z: \server\c$\folder1\folder2

NET USE y: \server\d$

Note that you can map drive-to-drive or drill down and map to sub-folder.

What throws an IOException in Java?

Assume you were:

  1. Reading a network file and got disconnected.
  2. Reading a local file that was no longer available.
  3. Using some stream to read data and some other process closed the stream.
  4. Trying to read/write a file, but don't have permission.
  5. Trying to write to a file, but disk space was no longer available.

There are many more examples, but these are the most common, in my experience.

How do I get Maven to use the correct repositories?

I think what you have missed here is this:

https://maven.apache.org/settings.html#Servers

The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.

This is the prefered way of using custom repos. So probably what is happening is that the url of this repo is in settings.xml of the build server.

Once you get hold of the url and credentials, you can put them in your machine here: ~/.m2/settings.xml like this:

<settings ...> 

        .
        .
        .
        <servers>
            <server>
              <id>internal-repository-group</id>
              <username>YOUR-USERNAME-HERE</username>
              <password>YOUR-PASSWORD-HERE</password>
            </server>
        </servers>
</settings>

EDIT:

You then need to refer this repository into project POM. The id internal-repository-group can be used in every project. You can setup multiple repos and credentials setting using different IDs in settings xml.

The advantage of this approach is that project can be shared without worrying about the credentials and don't have to mention the credentials in every project.

Following is a sample pom of a project using "internal-repository-group"

<repositories>
    <repository>
        <id>internal-repository-group</id>
        <name>repo-name</name>
        <url>http://project.com/yourrepourl/</url>
        <layout>default</layout>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </releases>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </snapshots>
    </repository>
</repositories>

No resource found - Theme.AppCompat.Light.DarkActionBar

If you are using Eclipse just copying android-support-v7-appcompat.jar to libs folder will not work if you are going to use resources.

Follow steps from here for "Adding libraries with resources".

Get Value From Select Option in Angular 4

HTML code

    <form class="form-inline" (ngSubmit)="HelloCorp(modelName)">
        <div class="select">
            <select class="form-control col-lg-8" [(ngModel)]="modelName" required>
                <option *ngFor="let corporation of corporations" [ngValue]="corporation">
                    {{corporation.corp_name}}
                </option>    
            </select>
            <button type="submit" class="btn btn-primary manage">Submit</button>
        </div> 
    </form>

Component code

HelloCorp(corporation) {
    var corporationObj = corporation.value;
}

Efficient way to remove ALL whitespace from String?

Here is a simple linear alternative to the RegEx solution. I am not sure which is faster; you'd have to benchmark it.

static string RemoveWhitespace(string input)
{
    StringBuilder output = new StringBuilder(input.Length);

    for (int index = 0; index < input.Length; index++)
    {
        if (!Char.IsWhiteSpace(input, index))
        {
            output.Append(input[index]);
        }
    }
    return output.ToString();
}

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

$("div[id^=" + controlid + "]") will return all the controls with the same name but you need to ensure that the text should not present in any of the controls

JTable won't show column headers

The main difference between this answer and the accepted answer is the use of setViewportView() instead of add().

How to put JTable in JScrollPane using Eclipse IDE:

  1. Create JScrollPane container via Design tab.
  2. Stretch JScrollPane to desired size (applies to Absolute Layout).
  3. Drag and drop JTable component on top of JScrollPane (Viewport area).

In Structure > Components, table should be a child of scrollPane. enter image description here

The generated code would be something like this:

JScrollPane scrollPane = new JScrollPane();
...

JTable table = new JTable();
scrollPane.setViewportView(table);

How to make sql-mode="NO_ENGINE_SUBSTITUTION" permanent in MySQL my.cnf

If you're using mariadb, you have to modify the mariadb.cnf file located in /etc/mysql/conf.d/.

I supposed the stuff is the same for any other my-sql based solutions.

Rmi connection refused with localhost

You need to have a rmiregistry running before attempting to connect (register) a RMI service with it.

The LocateRegistry.createRegistry(2020) method call creates and exports a registry on the specified port number.

See the documentation for LocateRegistry

Just what is an IntPtr exactly?

Here's an example:

I'm writing a C# program that interfaces with a high-speed camera. The camera has its own driver that acquires images and loads them into the computer's memory for me automatically.

So when I'm ready to bring the latest image into my program to work with, the camera driver provides me with an IntPtr to where the image is ALREADY stored in physical memory, so I don't have to waste time/resources creating another block of memory to store an image that's in memory already. The IntPtr just shows me where the image already is.

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

Try this

import components
from components import *

Method to get all files within folder and subfolders that will return a list

Simply use this:

public static List<String> GetAllFiles(String directory)
{
    return Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories).ToList();
}

And if you want every file, even extensionless ones:

public static List<String> GetAllFiles(String directory)
{
    return Directory.GetFiles(directory, "*", SearchOption.AllDirectories).ToList();
}

SyntaxError: Use of const in strict mode?

Since the time the question was asked, the draft for the const keyword is already a living standard as part of ECMAScript 2015. Also the current version of Node.js supports const declarations without the --harmony flag.

With the above said you can now run node app.js, with app.js:

'use strict';
const MB = 1024 * 1024;
...

getting both the syntax sugar and the benefits of strict mode.

change directory in batch file using variable

The set statement doesn't treat spaces the way you expect; your variable is really named Pathname[space] and is equal to [space]C:\Program Files.

Remove the spaces from both sides of the = sign, and put the value in double quotes:

set Pathname="C:\Program Files"

Also, if your command prompt is not open to C:\, then using cd alone can't change drives.

Use

cd /d %Pathname%

or

pushd %Pathname%

instead.

Multiple radio button groups in one form

To create a group of inputs you can create a custom html element

window.customElements.define('radio-group', RadioGroup);

https://gist.github.com/robdodson/85deb2f821f9beb2ed1ce049f6a6ed47

to keep selected option in each group, you need to add name attribute to inputs in group, if you not add it then all is one group.

MySQL error: key specification without a key length

Go to mysql edit table-> change column type to varchar(45).

JavaScript check if variable exists (is defined/initialized)

you can use the typeof operator.

For example,

var dataSet;

alert("Variable dataSet is : " + typeof dataSet);

Above code snippet will return the output like

variable dataSet is : undefined.

Changing permissions via chmod at runtime errors with "Operation not permitted"

You, or most likely your sysadmin, will need to login as root and run the chown command: http://www.computerhope.com/unix/uchown.htm

Through this command you will become the owner of the file.

Or, you can be a member of a group that owns this file and then you can use chmod.

But, talk with your sysadmin.

Android Intent Cannot resolve constructor

Or you can simply start the activity as shown below;

startActivity( new Intent(currentactivity.this, Tostartactivity.class));

How do I convert from int to String?

String strI = String.valueOf(i);

String string = Integer.toString(i);

Both of the ways are correct.

How to skip "are you sure Y/N" when deleting files in batch files

You have the following options on Windows command line:

net use [DeviceName [/home[{Password | *}] [/delete:{yes | no}]]

Try like:

net use H: /delete /y

How to get just numeric part of CSS property with jQuery?

If it's just for "px" you can also use:

$(this).css('marginBottom').slice(0, -2);

How to do multiple conditions for single If statement

Use the 'And' keyword for a logical and. Like this:

If Not ((filename = testFileName) And (fileName <> "")) Then

Solving "adb server version doesn't match this client" error

This issue for me was caused by having apowermirror running at the same time, from what I can tell any software that could use a different version of adb could cause these issues as others mention in this thread this can include Genymotion or from other threads unreal studio was the problem.

MySQL : transaction within a stored procedure

This is just an explanation not addressed in other answers

At least in recent versions of Mysql, your first query is not committed.

If you query it under the same session you will see the changes, but if you query it from a different session, the changes are not there, they are not committed.

What's going on?

When you open a transaction, and a query inside it fails, the transaction keeps open, it does not commit nor rollback the changes.

So BE CAREFUL, any table/row that was locked with a previous query likeSELECT ... FOR SHARE/UPDATE, UPDATE, INSERT or any other locking-query, keeps locked until that session is killed (and executes a rollback), or until a subsequent query commits it explicitly (COMMIT) or implicitly, thus making the partial changes permanent (which might happen hours later, while the transaction was in a waiting state).

That's why the solution involves declaring handlers to immediately ROLLBACK when an error happens.

Extra

Inside the handler you can also re-raise the error using RESIGNAL, otherwise the stored procedure executes "Successfully"

BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION 
        BEGIN
            ROLLBACK;
            RESIGNAL;
        END;

    START TRANSACTION;
        #.. Query 1 ..
        #.. Query 2 ..
        #.. Query 3 ..
    COMMIT;
END

php Replacing multiple spaces with a single space

preg_replace("/[[:blank:]]+/"," ",$input)

How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)

To disable resizing completely:

textarea {
    resize: none;
}

To allow only vertical resizing:

textarea {
    resize: vertical;
}

To allow only horizontal resizing:

textarea {
    resize: horizontal;
}

Or you can limit size:

textarea {
    max-width: 100px; 
    max-height: 100px;
}

To limit size to parents width and/or height:

textarea {
    max-width: 100%; 
    max-height: 100%;
}

Is it possible only to declare a variable without assigning any value in Python?

Is it possible to declare a variable in Python (var=None):

def decl_var(var=None):
if var is None:
    var = []
var.append(1)
return var

Java - Check Not Null/Empty else assign default value

With guava you can use

MoreObjects.firstNonNull(possiblyNullString, defaultValue);

How can I enable MySQL's slow query log without restarting MySQL?

MySQL Manual - slow-query-log-file

This claims that you can run the following to set the slow-log file (5.1.6 onwards):

set global slow_query_log_file = 'path';

The variable slow_query_log just controls whether it is enabled or not.

How to embed PDF file with responsive width

Simply do this:

<object data="resume.pdf" type="application/pdf" width="100%" height="800px"> 
  <p>It appears you don't have a PDF plugin for this browser.
   No biggie... you can <a href="resume.pdf">click here to
  download the PDF file.</a></p>  
</object>

R apply function with multiple parameters

Just pass var2 as an extra argument to one of the apply functions.

mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
  var1*var2
}
var2 <- 2

sapply(mylist,myfxn,var2=var2)

This passes the same var2 to every call of myfxn. If instead you want each call of myfxn to get the 1st/2nd/3rd/etc. element of both mylist and var2, then you're in mapply's domain.

How to autosize and right-align GridViewColumn data in WPF?

I had trouble with the accepted answer (because I missed the HorizontalAlignment=Stretch portion and have adjusted the original answer).

This is another technique. It uses a Grid with a SharedSizeGroup.

Note: the Grid.IsSharedScope=true on the ListView.

<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
    <ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}" Grid.IsSharedSizeScope="True">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="ID" Width="40">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                             <Grid>
                                  <Grid.ColumnDefinitions>
                                       <ColumnDefinition Width="Auto" SharedSizeGroup="IdColumn"/>
                                  </Grid.ColumnDefinitions>
                                  <TextBlock HorizontalAlignment="Right" Text={Binding Path=Id}"/>
                             </Grid>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="Auto" />
                <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="Auto"/>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>
</Window>

How to use multiple @RequestMapping annotations in spring?

Doesn't need to. RequestMapping annotation supports wildcards and ant-style paths. Also looks like you just want a default view, so you can put

<mvc:view-controller path="/" view-name="welcome"/>

in your config file. That will forward all requests to the Root to the welcome view.

Spark - load CSV file as DataFrame?

With Spark 2.0, following is how you can read CSV

val conf = new SparkConf().setMaster("local[2]").setAppName("my app")
val sc = new SparkContext(conf)
val sparkSession = SparkSession.builder
  .config(conf = conf)
  .appName("spark session example")
  .getOrCreate()

val path = "/Users/xxx/Downloads/usermsg.csv"
val base_df = sparkSession.read.option("header","true").
  csv(path)

How to verify a Text present in the loaded page through WebDriver

If you are not bothered about the location of the text present, then you could use Driver.PageSource property as below:

Driver.PageSource.Contains("expected message");

Replacing column values in a pandas DataFrame

w.female.replace(to_replace=dict(female=1, male=0), inplace=True)

See pandas.DataFrame.replace() docs.

Split pandas dataframe in two if it has more than 10 rows

I used a List Comprehension to cut a huge DataFrame into blocks of 100'000:

size = 100000
list_of_dfs = [df.loc[i:i+size-1,:] for i in range(0, len(df),size)]

or as generator:

list_of_dfs = (df.loc[i:i+size-1,:] for i in range(0, len(df),size))

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?

keytool -list -v -keystore "keyStoreName"

Run this command from the directory where the keystore of your app exists.

How can I commit files with git?

The command for commiting all changed files:

git commit -a -m 'My commit comments'

-a = all edited files

-m = following string is a comment.

This will commit to your local drives / folders repo. If you want to push your changes to a git server / remotely hosted server, after the above command type:

git push

GitHub's cheat sheet is quite handy.

EditText, clear focus on touch outside

I really think it's a more robust way to use getLocationOnScreen than getGlobalVisibleRect. Because I meet a problem. There is a Listview which contain some Edittext and and set ajustpan in the activity. I find getGlobalVisibleRect return a value that looks like including the scrollY in it, but the event.getRawY is always by the screen. The below code works well.

public boolean dispatchTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        View v = getCurrentFocus();
        if ( v instanceof EditText) {
            if (!isPointInsideView(event.getRawX(), event.getRawY(), v)) {
                Log.i(TAG, "!isPointInsideView");

                Log.i(TAG, "dispatchTouchEvent clearFocus");
                v.clearFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    }
    return super.dispatchTouchEvent( event );
}

/**
 * Determines if given points are inside view
 * @param x - x coordinate of point
 * @param y - y coordinate of point
 * @param view - view object to compare
 * @return true if the points are within view bounds, false otherwise
 */
private boolean isPointInsideView(float x, float y, View view) {
    int location[] = new int[2];
    view.getLocationOnScreen(location);
    int viewX = location[0];
    int viewY = location[1];

    Log.i(TAG, "location x: " + location[0] + ", y: " + location[1]);

    Log.i(TAG, "location xWidth: " + (viewX + view.getWidth()) + ", yHeight: " + (viewY + view.getHeight()));

    // point is inside view bounds
    return ((x > viewX && x < (viewX + view.getWidth())) &&
            (y > viewY && y < (viewY + view.getHeight())));
}

How can I get a process handle by its name in C++?

OpenProcess Function

From MSDN:

To open a handle to another local process and obtain full access rights, you must enable the SeDebugPrivilege privilege.

How to get mouse position in jQuery without mouse-events?

You can't read mouse position in jQuery without using an event. Note firstly that the event.pageX and event.pageY properties exists on any event, so you could do:

$('#myEl').click(function(e) {
    console.log(e.pageX);
});

Your other option is to use a closure to give your whole code access to a variable that is updated by a mousemove handler:

var mouseX, mouseY;
$(document).mousemove(function(e) {
    mouseX = e.pageX;
    mouseY = e.pageY;
}).mouseover(); // call the handler immediately

// do something with mouseX and mouseY

HSL to RGB color conversion

With H, S,and L in [0,1] range:

ConvertHslToRgb: function (iHsl)
{
    var min, sv, sextant, fract, vsf;

    var v = (iHsl.l <= 0.5) ? (iHsl.l * (1 + iHsl.s)) : (iHsl.l + iHsl.s - iHsl.l * iHsl.s);
    if (v === 0)
        return { Red: 0, Green: 0, Blue: 0 };

    min = 2 * iHsl.l - v;
    sv = (v - min) / v;
    var h = (6 * iHsl.h) % 6;
    sextant = Math.floor(h);
    fract = h - sextant;
    vsf = v * sv * fract;

    switch (sextant)
    {
        case 0: return { r: v, g: min + vsf, b: min };
        case 1: return { r: v - vsf, g: v, b: min };
        case 2: return { r: min, g: v, b: min + vsf };
        case 3: return { r: min, g: v - vsf, b: v };
        case 4: return { r: min + vsf, g: min, b: v };
        case 5: return { r: v, g: min, b: v - vsf };
    }
}

ProgressDialog in AsyncTask

/**
 * this class performs all the work, shows dialog before the work and dismiss it after
 */
public class ProgressTask extends AsyncTask<String, Void, Boolean> {

    public ProgressTask(ListActivity activity) {
        this.activity = activity;
        dialog = new ProgressDialog(activity);
    }

    /** progress dialog to show user that the backup is processing. */
    private ProgressDialog dialog;
    /** application context. */
    private ListActivity activity;

    protected void onPreExecute() {
        this.dialog.setMessage("Progress start");
        this.dialog.show();
    }

        @Override
    protected void onPostExecute(final Boolean success) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }


        MessageListAdapter adapter = new MessageListAdapter(activity, titles);
        setListAdapter(adapter);
        adapter.notifyDataSetChanged();


        if (success) {
            Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
        }
    }

    protected Boolean doInBackground(final String... args) {
       try{    
          BaseFeedParser parser = new BaseFeedParser();
          messages = parser.parse();
          List<Message> titles = new ArrayList<Message>(messages.size());
          for (Message msg : messages){
              titles.add(msg);
          }
          activity.setMessages(titles);
          return true;
       } catch (Exception e)
          Log.e("tag", "error", e);
          return false;
       }
    }
}

public class Soirees extends ListActivity {
    private List<Message> messages;
    private TextView tvSorties;
    private MyProgressDialog dialog;
    @Override
    public void onCreate(Bundle icicle) {

        super.onCreate(icicle);

        setContentView(R.layout.sorties);

        tvSorties=(TextView)findViewById(R.id.TVTitle);
        tvSorties.setText("Programme des soirées");

        // just call here the task
        AsyncTask task = new ProgressTask(this).execute();
   }

   public void setMessages(List<Message> msgs) {
      messages = msgs;
   }

}

Getting the size of an array in an object

Javascript arrays have a length property. Use it like this:

st.itemb.length

Convert columns to string in Pandas

I usually use this one:

pd['Column'].map(str)

Where to place the 'assets' folder in Android Studio?

Two ways:

  1. Select app/main folder, Right click and select New => Folder => Asset Folder. It will create 'assets' directory in main.

  2. Select main folder, Right click and select New => Directory Enter name as 'assets' = > Ok.

enter image description here

Reading a huge .csv file

here's another solution for Python3:

import csv
with open(filename, "r") as csvfile:
    datareader = csv.reader(csvfile)
    count = 0
    for row in datareader:
        if row[3] in ("column header", criterion):
            doSomething(row)
            count += 1
        elif count > 2:
            break

here datareader is a generator function.

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

The R-squared is not dependent on the number of variables in the model. The adjusted R-squared is.

The adjusted R-squared adds a penalty for adding variables to the model that are uncorrelated with the variable your trying to explain. You can use it to test if a variable is relevant to the thing your trying to explain.

Adjusted R-squared is R-squared with some divisions added to make it dependent on the number of variables in the model.

Trim a string in C

static inline void ut_trim(char * str) {
   char * start = str;
   char * end = start + strlen(str);

   while (--end >= start) {   /* trim right */
      if (!isspace(*end))
         break;
   }
   *(++end) = '\0';

   while (isspace(*start))    /* trim left */
      start++;

   if (start != str)          /* there is a string */
      memmove(str, start, end - start + 1);
}

How to set menu to Toolbar in Android

Simple fix to this was setting showAsAction to always in menu.xml in res/menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/add_alarm"
        android:icon="@drawable/ic_action_name"
        android:orderInCategory="100"
        android:title="Add"
        app:showAsAction="always"
        android:visible="true"/>

</menu>

Deep copy an array in Angular 2 + TypeScript

you can use use JQuery for deep copying :

var arr =[['abc'],['xyz']];
var newArr = $.extend(true, [], arr);
newArr.shift().shift();

console.log(arr); //arr still has [['abc'],['xyz']]

How to load external webpage in WebView

public class WebViewController extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}
webView.setWebViewClient(new WebViewController());

Get program execution time in the shell

The way is

$ > g++ -lpthread perform.c -o per
$ > time ./per

output is >>

real    0m0.014s
user    0m0.010s
sys     0m0.002s

Optional query string parameters in ASP.NET Web API

Default values cannot be supplied for parameters that are not declared 'optional'

 Function GetFindBooks(id As Integer, ByVal pid As Integer, Optional sort As String = "DESC", Optional limit As Integer = 99)

In your WebApiConfig

 config.Routes.MapHttpRoute( _
          name:="books", _
          routeTemplate:="api/{controller}/{action}/{id}/{pid}/{sort}/{limit}", _
          defaults:=New With {.id = RouteParameter.Optional, .pid = RouteParameter.Optional, .sort = UrlParameter.Optional, .limit = UrlParameter.Optional} _
      )

Can an Option in a Select tag carry multiple values?

Use a delimiter to separate the values.

<select name="myValues">
<option value="one|two">
</select>

<?php>
$value = filter_input(INPUT_POST, 'myValues');
$exploded_value = explode('|', $value);
$value_one = $exploded_value[0];
$value_two = $exploded_value[1];
?>

Method to find string inside of the text file. Then getting the following lines up to a certain limit

I am doing something similar but in C++. What you need to do is read the lines in one at a time and parse them (go over the words one by one). I have an outter loop that goes over all the lines and inside that is another loop that goes over all the words. Once the word you need is found, just exit the loop and return a counter or whatever you want.

This is my code. It basically parses out all the words and adds them to the "index". The line that word was in is then added to a vector and used to reference the line (contains the name of the file, the entire line and the line number) from the indexed words.

ifstream txtFile;
txtFile.open(path, ifstream::in);
char line[200];
//if path is valid AND is not already in the list then add it
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid
{
    //Add the path to the list of file paths
    textFilePaths.push_back(path);
    int lineNumber = 1;
    while(!txtFile.eof())
    {
        txtFile.getline(line, 200);
        Line * ln = new Line(line, path, lineNumber);
        lineNumber++;
        myList.push_back(ln);
        vector<string> words = lineParser(ln);
        for(unsigned int i = 0; i < words.size(); i++)
        {
            index->addWord(words[i], ln);
        }
    }
    result = true;
}

Autoreload of modules in IPython

As mentioned above, you need the autoreload extension. If you want it to automatically start every time you launch ipython, you need to add it to the ipython_config.py startup file:

It may be necessary to generate one first:

ipython profile create

Then include these lines in ~/.ipython/profile_default/ipython_config.py:

c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')

As well as an optional warning in case you need to take advantage of compiled Python code in .pyc files:

c.InteractiveShellApp.exec_lines.append('print "Warning: disable autoreload in ipython_config.py to improve performance." ')

edit: the above works with version 0.12.1 and 0.13

Using ConfigurationManager to load config from an arbitrary location

I provided the configuration values to word hosted .nET Compoent as follows.

A .NET Class Library component being called/hosted in MS Word. To provide configuration values to my component, I created winword.exe.config in C:\Program Files\Microsoft Office\OFFICE11 folder. You should be able to read configurations values like You do in Traditional .NET.

string sMsg = System.Configuration.ConfigurationManager.AppSettings["WSURL"];

Table overflowing outside of div

I tried almost all of above but did not work for me ... The following did

word-break: break-all;

This to be added on the parent div (container of the table .)

Getting data from selected datagridview row and which event?

You can use SelectionChanged event since you are using FullRowSelect selection mode. Than inside the handler you can access SelectedRows property and get data from it. Example:

private void dataGridView_SelectionChanged(object sender, EventArgs e) 
{
    foreach (DataGridViewRow row in dataGridView.SelectedRows) 
    {
        string value1 = row.Cells[0].Value.ToString();
        string value2 = row.Cells[1].Value.ToString();
        //...
    }
}

You can also walk through the column collection instead of typing indexes...

Setting the classpath in java using Eclipse IDE

Just had the same issue, for those having the same one it may be that you put the library on the modulepath rather than the classpath while adding it to your project

Error during SSL Handshake with remote server

Faced the same problem as OP:

  • Tomcat returned response when accessing directly via SOAP UI
  • Didn't load html files
  • When used Apache properties mentioned by the previous answer, web-page appeared but AngularJS couldn't get HTTP response

Tomcat SSL certificate was expired while a browser showed it as secure - Apache certificate was far from expiration. Updating Tomcat KeyStore file solved the problem.

Priority queue in .Net

here's one i just wrote, maybe it's not as optimized (just uses a sorted dictionary) but simple to understand. you can insert objects of different kinds, so no generic queues.

using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;

namespace PrioQueue
{
    public class PrioQueue
    {
        int total_size;
        SortedDictionary<int, Queue> storage;

        public PrioQueue ()
        {
            this.storage = new SortedDictionary<int, Queue> ();
            this.total_size = 0;
        }

        public bool IsEmpty ()
        {
            return (total_size == 0);
        }

        public object Dequeue ()
        {
            if (IsEmpty ()) {
                throw new Exception ("Please check that priorityQueue is not empty before dequeing");
            } else
                foreach (Queue q in storage.Values) {
                    // we use a sorted dictionary
                    if (q.Count > 0) {
                        total_size--;
                        return q.Dequeue ();
                    }
                }

                Debug.Assert(false,"not supposed to reach here. problem with changing total_size");

                return null; // not supposed to reach here.
        }

        // same as above, except for peek.

        public object Peek ()
        {
            if (IsEmpty ())
                throw new Exception ("Please check that priorityQueue is not empty before peeking");
            else
                foreach (Queue q in storage.Values) {
                    if (q.Count > 0)
                        return q.Peek ();
                }

                Debug.Assert(false,"not supposed to reach here. problem with changing total_size");

                return null; // not supposed to reach here.
        }

        public object Dequeue (int prio)
        {
            total_size--;
            return storage[prio].Dequeue ();
        }

        public void Enqueue (object item, int prio)
        {
            if (!storage.ContainsKey (prio)) {
                storage.Add (prio, new Queue ());
              }
            storage[prio].Enqueue (item);
            total_size++;

        }
    }
}

How to get just the date part of getdate()?

SELECT CAST(FLOOR(CAST(GETDATE() AS float)) as datetime)

or

SELECT CONVERT(datetime,FLOOR(CONVERT(float,GETDATE())))

How to make python Requests work via socks proxy

I could do this on Linux.

$ pip3 install --user 'requests[socks]'
$ https_proxy=socks5://<hostname or ip>:<port> python3 -c \
> 'import requests;print(requests.get("https://httpbin.org/ip").text)'

Git - how delete file from remote repository

If you have deleted lot of files and folders, just do this

git commit -a -m .
git push

Transparent ARGB hex value

Just came across this and the short code for transparency is simply #00000000.

How to break out of a loop in Bash?

while true ; do
    ...
    if [ something ]; then
        break
    fi
done

Remove first Item of the array (like popping from stack)

Just use arr.slice(startingIndex, endingIndex).

If you do not specify the endingIndex, it returns all the items starting from the index provided.

In your case arr=arr.slice(1).

Eclipse error "ADB server didn't ACK, failed to start daemon"

Killing Eclipse and then rebooting did not help me. I added the Android tool to the PATH variables, started Task Manager and killed adb.exe.

I restarted Eclipse, and then it worked.

How to get data from observable in angular2

You need to subscribe to the observable and pass a callback that processes emitted values

this.myService.getConfig().subscribe(val => console.log(val));

Failed to resolve: com.android.support:appcompat-v7:28.0

Ensure that your buildToolsVersion version tallies with your app compact version.

In order to find both installed compileSdkVersion and buildToolsVersion go to Tools > SDK Manager. This will pull up a window that will allow you to manage your compileSdkVersion and your buildToolsVersion.

To see the exact version breakdowns ensure you have the Show Package Details checkbox checked.

android {
    compileSdkVersion 28
    buildToolsVersion "28.0.3" (HERE)
    defaultConfig {
        applicationId "com.example.truecitizenquiz"
        minSdkVersion 14
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0' (HERE)
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Find and replace specific text characters across a document with JS

Vanilla JavaScript solution:

document.body.innerHTML = document.body.innerHTML.replace(/Original/g, "New")

Java: Replace all ' in a string with \'

Let's take a tour of String#repalceAll(String regex, String replacement)

You will see that:

An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression

Pattern.compile(regex).matcher(str).replaceAll(repl)

So lets take a look at Matcher.html#replaceAll(java.lang.String) documentation

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

You can see that in replacement we have special character $ which can be used as reference to captured group like

System.out.println("aHellob,aWorldb".replaceAll("a(\\w+?)b", "$1"));
// result Hello,World

But sometimes we don't want $ to be such special because we want to use it as simple dollar character, so we need a way to escape it.
And here comes \, because since it is used to escape metacharacters in regex, Strings and probably in other places it is good convention to use it here to escape $.

So now \ is also metacharacter in replacing part, so if you want to make it simple \ literal in replacement you need to escape it somehow. And guess what? You escape it the same way as you escape it in regex or String. You just need to place another \ before one you escaping.

So if you want to create \ in replacement part you need to add another \ before it. But remember that to write \ literal in String you need to write it as "\\" so to create two \\ in replacement you need to write it as "\\\\".


So try

s = s.replaceAll("'", "\\\\'");

Or even better

to reduce explicit escaping in replacement part (and also in regex part - forgot to mentioned that earlier) just use replace instead replaceAll which adds regex escaping for us

s = s.replace("'", "\\'");

Regex to check if valid URL that ends in .jpg, .png, or .gif

In general, you're better off validating URLs using built-in library or framework functions, rather than rolling your own regular expressions to do this - see What is the best regular expression to check if a string is a valid URL for details.

If you are keen on doing this, though, check out this question:

Getting parts of a URL (Regex)

Then, once you're satisfied with the URL (by whatever means you used to validate it), you could either use a simple "endswith" type string operator to check the extension, or a simple regex like

(?i)\.(jpg|png|gif)$

How can I add private key to the distribution certificate?

With Xcode 9 the interface has been updated and now the way I did to resolve the problem was this:

  1. Choose Xcode > Preferences.
  2. Click Accounts at the top of the window.
  3. Select the team you want to view
  4. Click the gear icon () in the lower-left.

enter image description here

  1. Export Apple Id and Code Signing Assets
  2. After entering a filename in the Save As field and a password in both the Password and Verify fields you'll see a Window like this

enter image description here

  1. Click the gear icon () -> Click Import -> Select the file you exported in step 6

mysqld: Can't change dir to data. Server doesn't start

If you are having this issue and can't find the MySQL service either, just launch "MySQL Installer" from the Start menu (or download it), then choose "Reconfigure" on MySQL Server. Follow the steps to set a root user password and then the service will be created and started automatically (and set to auto-start on boot).

extract month from date in python

import datetime

a = '2010-01-31'

datee = datetime.datetime.strptime(a, "%Y-%m-%d")


datee.month
Out[9]: 1

datee.year
Out[10]: 2010

datee.day
Out[11]: 31

Class Diagrams in VS 2017

A further note on Dmitry's 2017 answer. I opened up

C:\Program Files (x86)\Microsoft Visual 
Studio\2017\Community\MSBuild\Microsoft\VisualStudio\Managed\ 
Microsoft.CSharp.DesignTime.targets 

and went to the <ProjectCapability> element. I already had this:

<ProjectCapability Include="
                          CSharp;
                          Managed;
                          ClassDesigner**;**" />

with ClassDesigner already there, and yet I was still unable to drag items to my hack-made Diagram.cd using the XML editing method Dmitry mentioned (

Manually create text file, say MyClasses.cd with following content:

<?xml version="1.0" encoding="utf-8"?> <ClassDiagram MajorVersion="1"
> MinorVersion="1">
>     <Font Name="Segoe UI" Size="9" /> </ClassDiagram>

). But when I took off the semicolon off 'ClassDesigner' in that element then reopened Visual Studio, voila, I was able to drag classes from my Solution Explorer to my Diagram.cd window.

So in conclusion, this element in Microsoft.CSharp.DesignTime.targets worked:

<ProjectCapability Include="
                              CSharp;
                              Managed;
                              ClassDesigner" />

I am using VS 2019, version 16.1.5.

Oracle database: How to read a BLOB?

You can dump the value in hex using UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2()).

SELECT b FROM foo;
-- (BLOB)

SELECT UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2(b))
FROM foo;
-- 1F8B080087CDC1520003F348CDC9C9D75128CF2FCA49D1E30200D7BBCDFC0E000000

This is handy because you this is the same format used for inserting into BLOB columns:

CREATE GLOBAL TEMPORARY TABLE foo (
    b BLOB);
INSERT INTO foo VALUES ('1f8b080087cdc1520003f348cdc9c9d75128cf2fca49d1e30200d7bbcdfc0e000000');

DESC foo;
-- Name Null Type 
-- ---- ---- ---- 
-- B        BLOB 

However, at a certain point (2000 bytes?) the corresponding hex string exceeds Oracle’s maximum string length. If you need to handle that case, you’ll have to combine How do I get textual contents from BLOB in Oracle SQL with the documentation for DMBS_LOB.SUBSTR for a more complicated approach that will allow you to see substrings of the BLOB.

Git ignore file for Xcode projects

Most of the answers are from the Xcode 4-5 era. I recommend an ignore file in a modern style.

# Xcode Project
**/*.xcodeproj/xcuserdata/
**/*.xcworkspace/xcuserdata/
**/*.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
**/*.xcworkspace/xcshareddata/*.xccheckout
**/*.xcworkspace/xcshareddata/*.xcscmblueprint
**/*.playground/**/timeline.xctimeline
.idea/

# Build
build/
DerivedData/
*.ipa

# CocoaPods
Pods/

# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/sign&cert

# CSV
*.orig
.svn

# Other
*~
.DS_Store
*.swp
*.save
._*
*.bak

Keep it updated from: https://github.com/BB9z/iOS-Project-Template/blob/master/.gitignore

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

You are doing it right with ServerCertificateValidationCallback. This is not the problem you are facing. The problem you are facing is most likely the version of SSL/TLS protocol.

For example, if your server offers only SSLv3 and TLSv10 and your client needs TLSv12 then you will receive this error message. What you need to do is to make sure that both client and server have a common protocol version supported.

When I need a client that is able to connect to as many servers as possible (rather than to be as secure as possible) I use this (together with setting the validation callback):

  ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Why can't I find SQL Server Management Studio after installation?

It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

and the one for 64 bit WITH the management tools (management studio) is here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively.

SSRS expression to format two decimal places does not show zeros

Please try the following code snippet,

IIF(Round(Avg(Fields!Vision_Score.Value)) = Avg(Fields!Vision_Score.Value), 
Format(Avg(Fields!Vision_Score.Value)), 
FORMAT(Avg(Fields!Vision_Score.Value),"##.##"))

hope it will help, Thank-you.

Convert array to JSON string in swift

For Swift 3.0 you have to use this:

var postString = ""
    do {
        let data =  try JSONSerialization.data(withJSONObject: self.arrayNParcel, options: .prettyPrinted)
        let string1:String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String

        postString = "arrayData=\(string1)&user_id=\(userId)&markupSrcReport=\(markup)"
    } catch {
        print(error.localizedDescription)
    }
    request.httpBody = postString.data(using: .utf8)

100% working TESTED

WebDriver - wait for element using Java

You can use Explicit wait or Fluent Wait

Example of Explicit Wait -

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,20);
WebElement aboutMe;
aboutMe= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("about_me")));     

Example of Fluent Wait -

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)                            
.withTimeout(20, TimeUnit.SECONDS)          
.pollingEvery(5, TimeUnit.SECONDS)          
.ignoring(NoSuchElementException.class);    

  WebElement aboutMe= wait.until(new Function<WebDriver, WebElement>() {       
public WebElement apply(WebDriver driver) { 
return driver.findElement(By.id("about_me"));     
 }  
});  

Check this TUTORIAL for more details.

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

Also, if your service is sending an object instead of an array add isArray:false to its declaration.

'query': {method: 'GET', isArray: false }

Creating random numbers with no duplicates

There is algorithm of card batch: you create ordered array of numbers (the "card batch") and in every iteration you select a number at random position from it (removing the selected number from the "card batch" of course).

Calculate age based on date of birth

Got this script from net (thanks to coffeecupweb)

<?php
/**
 * Simple PHP age Calculator
 * 
 * Calculate and returns age based on the date provided by the user.
 * @param   date of birth('Format:yyyy-mm-dd').
 * @return  age based on date of birth
 */
function ageCalculator($dob){
    if(!empty($dob)){
        $birthdate = new DateTime($dob);
        $today   = new DateTime('today');
        $age = $birthdate->diff($today)->y;
        return $age;
    }else{
        return 0;
    }
}
$dob = '1992-03-18';
echo ageCalculator($dob);
?>

How to squash all git commits into one?

As of git 1.6.2, you can use git rebase --root -i.

For each commit except the first, change pick to squash.

WCF on IIS8; *.svc handler mapping doesn't work

This was a really silly one for me. Adding this here as it's one of the more popular threads on svc 404 issues.

I had in my Project Settings' \ Web \ Project URL, pasted:

http://blah.webservice.local.blahblah.com/Blah.svc

And for some unknown reason (having done this a thousand times) didn't spot straight away that the name of the .svc file was at the end.

DOH!

I had just pasted the address from my WCF test client and hadn't checked it sufficiently. What this did in the background was create an IIS application at the .svc address and I was getting nothing out of IIS. I couldn't work out how I couldn't even hit the .svc file.

Simple fix, obviously, just remove the application in IIS and change the project URL.

After almost 20 years at this, you can still make schoolboy errors / rookie mistakes. Hope this helps someone.

Invalid date in safari

Use the below format, it would work on all the browsers

var year = 2016;
var month = 02;           // month varies from 0-11 (Jan-Dec)
var day = 23;

month = month<10?"0"+month:month;        // to ensure YYYY-MM-DD format
day = day<10?"0"+day:day;

dateObj = new Date(year+"-"+month+"-"+day);

alert(dateObj); 

//Your output would look like this "Wed Mar 23 2016 00:00:00 GMT+0530 (IST)"

//Note this would be in the current timezone in this case denoted by IST, to convert to UTC timezone you can include

alert(dateObj.toUTCSting);

//Your output now would like this "Tue, 22 Mar 2016 18:30:00 GMT"

Note that now the dateObj shows the time in GMT format, also note that the date and time have been changed correspondingly.

The "toUTCSting" function retrieves the corresponding time at the Greenwich meridian. This it accomplishes by establishing the time difference between your current timezone to the Greenwich Meridian timezone.

In the above case the time before conversion was 00:00 hours and minutes on the 23rd of March in the year 2016. And after conversion from GMT+0530 (IST) hours to GMT (it basically subtracts 5.30 hours from the given timestamp in this case) the time reflects 18.30 hours on the 22nd of March in the year 2016 (exactly 5.30 hours behind the first time).

Further to convert any date object to timestamp you can use

alert(dateObj.getTime());

//output would look something similar to this "1458671400000"

This would give you the unique timestamp of the time

android.content.Context.getPackageName()' on a null object reference

Use can use in global

Context context;

and create a constructor and passing the context. LoginClass is name of the class

LoginClass(Context context)
{this.context=context;}

and also when we call the class then use getApplicationContext like LoginClass lclass = new LoginClass(getApplicationContext) thats it.

shared global variables in C

There is a cleaner way with just one header file so it is simpler to maintain. In the header with the global variables prefix each declaration with a keyword (I use common) then in just one source file include it like this

#define common
#include "globals.h"
#undef common

and any other source files like this

#define common extern
#include "globals.h"
#undef common

Just make sure you don't initialise any of the variables in the globals.h file or the linker will still complain as an initialised variable is not treated as external even with the extern keyword. The global.h file looks similar to this

#pragma once
common int globala;
common int globalb;
etc.

seems to work for any type of declaration. Don't use the common keyword on #define of course.

Compare two DataFrames and output their differences side-by-side

pandas >= 1.1: DataFrame.compare

With pandas 1.1, you could essentially replicate Ted Petrou's output with a single function call. Example taken from the docs:

pd.__version__
# '1.1.0'

df1.compare(df2)

  score       isEnrolled       Comment             
   self other       self other    self        other
1  1.11  1.21        NaN   NaN     NaN          NaN
2   NaN   NaN        1.0   0.0     NaN  On vacation

Here, "self" refers to the LHS dataFrame, while "other" is the RHS DataFrame. By default, equal values are replaced with NaNs so you can focus on just the diffs. If you want to show values that are equal as well, use

df1.compare(df2, keep_equal=True, keep_shape=True) 

  score       isEnrolled           Comment             
   self other       self  other       self        other
1  1.11  1.21      False  False  Graduated    Graduated
2  4.12  4.12       True  False        NaN  On vacation

You can also change the axis of comparison using align_axis:

df1.compare(df2, align_axis='index')

         score  isEnrolled      Comment
1 self    1.11         NaN          NaN
  other   1.21         NaN          NaN
2 self     NaN         1.0          NaN
  other    NaN         0.0  On vacation

This compares values row-wise, instead of column-wise.

Does "git fetch --tags" include "git fetch"?

In most situations, git fetch should do what you want, which is 'get anything new from the remote repository and put it in your local copy without merging to your local branches'. git fetch --tags does exactly that, except that it doesn't get anything except new tags.

In that sense, git fetch --tags is in no way a superset of git fetch. It is in fact exactly the opposite.

git pull, of course, is nothing but a wrapper for a git fetch <thisrefspec>; git merge. It's recommended that you get used to doing manual git fetching and git mergeing before you make the jump to git pull simply because it helps you understand what git pull is doing in the first place.

That being said, the relationship is exactly the same as with git fetch. git pull is the superset of git pull --tags.

How to write an async method with out parameter?

You cannot have ref or out parameters in async methods (as was already noted).

This screams for some modelling in the data moving around:

public class Data
{
    public int Op {get; set;}
    public int Result {get; set;}
}

public async void Method1()
{
    Data data = await GetDataTaskAsync();
    // use data.Op and data.Result from here on
}

public async Task<Data> GetDataTaskAsync()
{
    var returnValue = new Data();
    // Fill up returnValue
    return returnValue;
}

You gain the ability to reuse your code more easily, plus it's way more readable than variables or tuples.

add maven repository to build.gradle

After

apply plugin: 'com.android.application'

You should add this:

  repositories {
        mavenCentral()
        maven {
            url "https://repository-achartengine.forge.cloudbees.com/snapshot/"
        }
    }

@Benjamin explained the reason.

If you have a maven with authentication you can use:

repositories {
            mavenCentral()
            maven {
               credentials {
                   username xxx
                   password xxx
               }
               url    'http://mymaven/xxxx/repositories/releases/'
            }
}

It is important the order.

R: Comment out block of code

I use RStudio or Emacs and always use the editor shortcuts available to comment regions. If this is not a possibility then you could use Paul's answer but this only works if your code is syntactically correct.

Here is another dirty way I came up with, wrap it in scan() and remove the result. It does store the comment in memory for a short while so it will probably not work with very large comments. Best still is to just put # signs in front of every line (possibly with editor shortcuts).

foo <- scan(what="character")
These are comments
These are still comments
Can also be code:
x <- 1:10
One line must be blank

rm(foo)

How to initialize all the elements of an array to any specific value in java

For Lists you can use

Collections.fill(arrayList, "-")

How to set portrait and landscape media queries in css?

iPad Media Queries (All generations - including iPad mini)

Thanks to Apple's work in creating a consistent experience for users, and easy time for developers, all 5 different iPads (iPads 1-5 and iPad mini) can be targeted with just one CSS media query. The next few lines of code should work perfect for a responsive design.

iPad in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px)  { /* STYLES GO HERE */}

iPad in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) { /* STYLES GO HERE */}

iPad in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) { /* STYLES GO HERE */ }

iPad 3 & 4 Media Queries

If you're looking to target only 3rd and 4th generation Retina iPads (or tablets with similar resolution) to add @2x graphics, or other features for the tablet's Retina display, use the following media queries.

Retina iPad in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

Retina iPad in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

Retina iPad in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */ }

iPad 1 & 2 Media Queries

If you're looking to supply different graphics or choose different typography for the lower resolution iPad display, the media queries below will work like a charm in your responsive design!

iPad 1 & 2 in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (-webkit-min-device-pixel-ratio: 1){ /* STYLES GO HERE */}

iPad 1 & 2 in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 1)  { /* STYLES GO HERE */}

iPad 1 & 2 in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) 
and (-webkit-min-device-pixel-ratio: 1) { /* STYLES GO HERE */ }

Source: http://stephen.io/mediaqueries/

How do I pull from a Git repository through an HTTP proxy?

When your network team does ssl-inspection by rewriting certificates, then using a http url instead of a https one, combined with setting this var worked for me.

git config --global http.proxy http://proxy:8081

How can I make a UITextField move up when the keyboard is present - on starting to edit?

- SwiftUI

Show only the active TextField

This will move the view enough just to avoid hiding only the active TextField. When each TextField is clicked, the view is only moved up enough to make the clicked text field visible.

struct ContentView: View {
    @ObservedObject private var kGuardian = KeyboardGuardian(textFieldCount: 3)
    @State private var name = Array<String>.init(repeating: "", count: 3)

    var body: some View {

        VStack {
            Group {
                Text("Some filler text").font(.largeTitle)
                Text("Some filler text").font(.largeTitle)
            }

            TextField("text #1", text: $name[0], onEditingChanged: { if $0 { self.kGuardian.showField = 0 } })
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .background(GeometryGetter(rect: $kGuardian.rects[0]))

            TextField("text #2", text: $name[1], onEditingChanged: { if $0 { self.kGuardian.showField = 1 } })
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .background(GeometryGetter(rect: $kGuardian.rects[1]))

            TextField("text #3", text: $name[2], onEditingChanged: { if $0 { self.kGuardian.showField = 2 } })
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .background(GeometryGetter(rect: $kGuardian.rects[2]))

            }.offset(y: kGuardian.slide).animation(.easeInOut(duration: 0.25))
    }

}

Show all TextFields

This moves all textField up, if the keyboard appears for any of them. But only if needed. If the keyboard doesn't hide the textfields, they will not move. When the keyboard is opened, the 3 textfields are moved up enough to keep then all visible

struct ContentView: View {
    @ObservedObject private var kGuardian = KeyboardGuardian(textFieldCount: 1)
    @State private var name = Array<String>.init(repeating: "", count: 3)

    var body: some View {

        VStack {
            Group {
                Text("Some filler text").font(.largeTitle)
                Text("Some filler text").font(.largeTitle)
            }

            TextField("enter text #1", text: $name[0])
                .textFieldStyle(RoundedBorderTextFieldStyle())

            TextField("enter text #2", text: $name[1])
                .textFieldStyle(RoundedBorderTextFieldStyle())

            TextField("enter text #3", text: $name[2])
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .background(GeometryGetter(rect: $kGuardian.rects[0]))

        }.offset(y: kGuardian.slide).animation(.easeInOut(duration: 0.25))
    }

}

Both examples use the same common codes: GeometryGetter and KeyboardGuardian Inspired by @kontiki

GeometryGetter

This is a view that absorbs the size and position of its parent view. Encapsulate description here In order to achieve that, it is called inside the .background modifier. This is a very powerful modifier, not just a way to decorate the background of a view. When passing a view to .background(MyView()), MyView is getting the modified view as the parent. Using GeometryReader is what makes it possible for the view to know the geometry of the parent.

For example: Text("hello").background(GeometryGetter(rect: $bounds)) will fill variable bounds, with the size and position of the Text view, and using the global coordinate space.

struct GeometryGetter: View {
    @Binding var rect: CGRect

    var body: some View {
        GeometryReader { geometry in
            Group { () -> AnyView in
                DispatchQueue.main.async {
                    self.rect = geometry.frame(in: .global)
                }

                return AnyView(Color.clear)
            }
        }
    }
}

Note that the DispatchQueue.main.async is to avoid the possibility of modifying the state of the view while it is being rendered.

KeyboardGuardian

The purpose of KeyboardGuardian, is to keep track of keyboard show/hide events and calculate how much space the view needs to be shifted.

Note that it refreshes the slide, when the user tabs from one field to another*

import SwiftUI
import Combine

final class KeyboardGuardian: ObservableObject {
    public var rects: Array<CGRect>
    public var keyboardRect: CGRect = CGRect()

    // keyboardWillShow notification may be posted repeatedly,
    // this flag makes sure we only act once per keyboard appearance
    public var keyboardIsHidden = true

    @Published var slide: CGFloat = 0

    var showField: Int = 0 {
        didSet {
            updateSlide()
        }
    }

    init(textFieldCount: Int) {
        self.rects = Array<CGRect>(repeating: CGRect(), count: textFieldCount)

        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardDidHide(notification:)), name: UIResponder.keyboardDidHideNotification, object: nil)

    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    @objc func keyBoardWillShow(notification: Notification) {
        if keyboardIsHidden {
            keyboardIsHidden = false
            if let rect = notification.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? CGRect {
                keyboardRect = rect
                updateSlide()
            }
        }
    }

    @objc func keyBoardDidHide(notification: Notification) {
        keyboardIsHidden = true
        updateSlide()
    }

    func updateSlide() {
        if keyboardIsHidden {
            slide = 0
        } else {
            let tfRect = self.rects[self.showField]
            let diff = keyboardRect.minY - tfRect.maxY

            if diff > 0 {
                slide += diff
            } else {
                slide += min(diff, 0)
            }

        }
    }
}

Jquery change background color

The .css() function doesn't queue behind running animations, it's instantaneous.

To match the behaviour that you're after, you'd need to do the following:

$(document).ready(function() {
  $("button").mouseover(function() {
    var p = $("p#44.test").css("background-color", "yellow");
    p.hide(1500).show(1500);
    p.queue(function() {
      p.css("background-color", "red");
    });
  });
});

The .queue() function waits for running animations to run out and then fires whatever's in the supplied function.

How to download Xcode DMG or XIP file?

You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).

You must login to have a valid session before downloading anything below.

*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)

*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.

Xcode 12

  • 12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)

  • 12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)

  • 12.2

  • 12.1

  • 12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)

Xcode 11

Xcode 10 (unsupported for iTunes Connect)

  • 10.3 (Requires macOS 10.14.3 or later)
  • 10.2.1 (Requires macOS 10.14.3 or later)
  • 10.1 (Last version supporting macOS 10.13.6 High Sierra)
  • 10 (Subsequent versions were unsupported for iTunes Connect from March 2019)

Xcode 9

Xcode 8

Xcode 7

Xcode 6

Even Older Versions (unsupported for iTunes Connect)

How do I catch a PHP fatal (`E_ERROR`) error?

Not really. Fatal errors are called that, because they are fatal. You can't recover from them.

How do I add a submodule to a sub-directory?

Note that starting git1.8.4 (July 2013), you wouldn't have to go back to the root directory anymore.

 cd ~/.janus/snipmate-snippets
 git submodule add <git@github ...> snippets

(Bouke Versteegh comments that you don't have to use /., as in snippets/.: snippets is enough)

See commit 091a6eb0feed820a43663ca63dc2bc0bb247bbae:

submodule: drop the top-level requirement

Use the new rev-parse --prefix option to process all paths given to the submodule command, dropping the requirement that it be run from the top-level of the repository.

Since the interpretation of a relative submodule URL depends on whether or not "remote.origin.url" is configured, explicitly block relative URLs in "git submodule add" when not at the top level of the working tree.

Signed-off-by: John Keeping

Depends on commit 12b9d32790b40bf3ea49134095619700191abf1f

This makes 'git rev-parse' behave as if it were invoked from the specified subdirectory of a repository, with the difference that any file paths which it prints are prefixed with the full path from the top of the working tree.

This is useful for shell scripts where we may want to cd to the top of the working tree but need to handle relative paths given by the user on the command line.

How to do Select All(*) in linq to sql

You can use simple linq query as follow to select all records from sql table

var qry = ent.tableName.Select(x => x).ToList();

How to render a DateTime in a specific format in ASP.NET MVC 3?

Only View File Adjust like this. You may try this.

@Html.FormatValue( (object)Convert.ChangeType(item.transdate, typeof(object)), 
                            "{0: yyyy-MM-dd}")

item.transdate it is your DateTime type data.

Update and left outer join statements

Update t 
SET 
       t.Column1=100
FROM 
       myTableA t 
LEFT JOIN 
       myTableB t2 
ON 
       t2.ID=t.ID

Replace myTableA with your table name and replace Column1 with your column name.

After this simply LEFT JOIN to tableB. t in this case is just an alias for myTableA. t2 is an alias for your joined table, in my example that is myTableB. If you don't like using t or t2 use any alias name you prefer - it doesn't matter - I just happen to like using those.

How do I see if Wi-Fi is connected on Android?

This works for me:

    ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    // Mobile
    State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();

    // Wi-Fi
    State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();

    // And then use it like this:

    if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
    {
        Toast.makeText(Wifi_Gprs.this,"Mobile is Enabled :) ....",Toast.LENGTH_LONG).show();
    }
    else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
    {
        Toast.makeText(Wifi_Gprs.this,"Wifi is Enabled  :) ....",Toast.LENGTH_LONG).show();
    }
    else
    {
        Toast.makeText(Wifi_Gprs.this,"No Wifi or Gprs Enabled :( ....",Toast.LENGTH_LONG).show();
    }

And add this permission:

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

Decimal values in SQL for dividing results

Just another approach:

SELECT col1 * 1.0 / col2 FROM tbl1

Multiplying by 1.0 turns an integer into a float numeric(13,1) and so works like a typecast, but most probably it is slower than that.

A slightly shorter variation suggested by Aleksandr Fedorenko in a comment:

SELECT col1 * 1. / col2 FROM tbl1

The effect would be basically the same. The only difference is that the multiplication result in this case would be numeric(12,0).

Principal advantage: less wordy than other approaches.

Check if a file is executable

This might be not so obvious, but sometime is required to test the executable to appropriately call it without an external shell process:

function tkl_is_file_os_exec()
{
  [[ ! -x "$1" ]] && return 255

  local exec_header_bytes
  case "$OSTYPE" in
    cygwin* | msys* | mingw*)
      # CAUTION:
      #   The bash version 3.2+ might require a file path together with the extension,
      #   otherwise will throw the error: `bash: ...: No such file or directory`.
      #   So we make a guess to avoid the error.
      #
      {
        read -r -n 4 exec_header_bytes 2> /dev/null < "$1" ||
        {
          [[ -x "${1%.exe}.exe" ]] && read -r -n 4 exec_header_bytes 2> /dev/null < "${1%.exe}.exe"
        } ||
        {
          [[ -x "${1%.com}.com" ]] && read -r -n 4 exec_header_bytes 2> /dev/null < "${1%.com}.com"
        }
      } &&
      if [[ "${exec_header_bytes:0:3}" == $'MZ\x90' ]]; then
        # $'MZ\x90\00' for bash version 3.2.42+
        # $'MZ\x90\03' for bash version 4.0+
        [[ "${exec_header_bytes:3:1}" == $'\x00' || "${exec_header_bytes:3:1}" == $'\x03' ]] && return 0
      fi
    ;;
    *)
      read -r -n 4 exec_header_bytes < "$1"
      [[ "$exec_header_bytes" == $'\x7fELF' ]] && return 0
    ;;
  esac

  return 1
}

# executes script in the shell process in case of a shell script, otherwise executes as usual
function tkl_exec_inproc()
{
  if tkl_is_file_os_exec "$1"; then
    "$@"
  else
    . "$@"
  fi
  return $?
}

myscript.sh:

#!/bin/bash

echo 123

return 123

In Cygwin:

> tkl_exec_inproc /cygdrive/c/Windows/system32/cmd.exe /c 'echo 123'
123
> tkl_exec_inproc /cygdrive/c/Windows/system32/chcp.com 65001
Active code page: 65001
> tkl_exec_inproc ./myscript.sh
123
> echo $?
123

In Linux:

> tkl_exec_inproc /bin/bash -c 'echo 123'
123
> tkl_exec_inproc ./myscript.sh
123
> echo $?
123

SSL Error: unable to get local issuer certificate

jww is right — you're referencing the wrong intermediate certificate.

As you have been issued with a SHA256 certificate, you will need the SHA256 intermediate. You can grab it from here: http://secure2.alphassl.com/cacert/gsalphasha2g2r1.crt

Drop all tables command

Once you've dropped all the tables (and the indexes will disappear when the table goes) then there's nothing left in a SQLite database as far as I know, although the file doesn't seem to shrink (from a quick test I just did).

So deleting the file would seem to be fastest - it should just be recreated when your app tries to access the db file.

Android Studio cannot resolve R in imported project?

None of these answers helped me!

My problem was not a problem! The program could compile completely and run on the device but the IDE has given me an annoying syntax error. It has underlined the lines of codes that included "R.".

The way that I could solve this issue:

I just added these three classes in "myapp/gen/com.example.app/" folder:

BuildConfig

package com.example.app;
public final class BuildConfig {
    public final static boolean DEBUG = true;
}

Manifest

package com.example.app;
public final class Manifest {
}

R

package com.example.app;
public final class R {
}

Combine or merge JSON on node.js without jQuery

If using Node version >= 4, use Object.assign() (see Ricardo Nolde's answer).

If using Node 0.x, there is the built in util._extend:

var extend = require('util')._extend
var o = extend({}, {name: "John"});
extend(o,  {location: "San Jose"});

It doesn't do a deep copy and only allows two arguments at a time, but is built in. I saw this mentioned on a question about cloning objects in node: https://stackoverflow.com/a/15040626.

If you're concerned about using a "private" method, you could always proxy it:

// myutil.js
exports.extend = require('util')._extend;

and replace it with your own implementation if it ever disappears. This is (approximately) their implementation:

exports.extend = function(origin, add) {
    if (!add || (typeof add !== 'object' && add !== null)){
        return origin;
    }

    var keys = Object.keys(add);
    var i = keys.length;
    while(i--){
        origin[keys[i]] = add[keys[i]];
    }
    return origin;
};

Checking if a variable is an integer

A more "duck typing" way is to use respond_to? this way "integer-like" or "string-like" classes can also be used

if(s.respond_to?(:match) && s.match(".com")){
  puts "It's a .com"
else
  puts "It's not"
end

What are alternatives to document.write?

This is probably the most correct, direct replacement: insertAdjacentHTML.

How many files can I put in a directory?

It really depends on the filesystem used, and also some flags.

For example, ext3 can have many thousands of files; but after a couple of thousands, it used to be very slow. Mostly when listing a directory, but also when opening a single file. A few years ago, it gained the 'htree' option, that dramatically shortened the time needed to get an inode given a filename.

Personally, I use subdirectories to keep most levels under a thousand or so items. In your case, I'd create 256 directories, with the two last hex digits of the ID. Use the last and not the first digits, so you get the load balanced.

.substring error: "is not a function"

try this code below :

var currentLocation = document.location;
muzLoc = String(currentLocation).substring(0,45);
prodLoc = String(currentLocation).substring(0,48); 
techLoc = String(currentLocation).substring(0,47);

Convert from enum ordinal to enum type

Every enum has name(), which gives a string with the name of enum member.

Given enum Suit{Heart, Spade, Club, Diamond}, Suit.Heart.name() will give Heart.

Every enum has a valueOf() method, which takes an enum type and a string, to perform the reverse operation:

Enum.valueOf(Suit.class, "Heart") returns Suit.Heart.

Why anyone would use ordinals is beyond me. It may be nanoseconds faster, but it is not safe, if the enum members change, as another developer may not be aware some code is relying on ordinal values (especially in the JSP page cited in the question, network and database overhead completely dominates the time, not using an integer over a string).

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

I am able to use this feature on my machine using MS Access 2007.

  • On the Ribbon, select External Data
  • Select the "Text File" option
  • This displays the Get External Data Wizard
  • Specify the location of the file you wish to import
  • Click OK. This displays the "Import Text Wizard"
  • On the bottom of this dialog screen is the Advanced button you referenced
  • Clicking on this button should display the Import Specification screen and allow you to select and modify an existing import spec.

For what its worth, I'm using Access 2007 SP1

How can I prevent the backspace key from navigating back?

I had a hard time finding a non-JQUERY answer. Thanks to Stas for putting me on the track.

Chrome: If you don't need cross browser support, you can just use a blacklist, rather than whitelisting. This pure JS version works in Chrome, but not in IE. Not sure about FF.

In Chrome (ver. 36, mid 2014), keypresses not on an input or contenteditable element seem to be targeted to <BODY>. This makes it possible use a blacklist, which I prefer to whitelisting. IE uses the last click target - so it might be a div or anything else. That makes this useless in IE.

window.onkeydown = function(event) {
    if (event.keyCode == 8) {
    //alert(event.target.tagName); //if you want to see how chrome handles keypresses not on an editable element
        if (event.target.tagName == 'BODY') {
            //alert("Prevented Navigation");
            event.preventDefault();
        }
    }
}  

Cross Browser: For pure javascript, I found Stas' answer to be the best. Adding one more condition check for contenteditable made it work for me*:

document.onkeydown = function(e) {stopDefaultBackspaceBehaviour(e);}
document.onkeypress = function(e) {stopDefaultBackspaceBehaviour(e);}

function stopDefaultBackspaceBehaviour(event) {
    var event = event || window.event;
    if (event.keyCode == 8) {
        var elements = "HTML, BODY, TABLE, TBODY, TR, TD, DIV";
        var d = event.srcElement || event.target;
        var regex = new RegExp(d.tagName.toUpperCase());
        if (d.contentEditable != 'true') { //it's not REALLY true, checking the boolean value (!== true) always passes, so we can use != 'true' rather than !== true/
            if (regex.test(elements)) {
                event.preventDefault ? event.preventDefault() : event.returnValue = false;
            }
        }
    }
}

*Note that IEs [edit: and Spartan/TechPreview] have a "feature" that makes table-related elements uneditable. If you click one of those and THEN press backspace, it WILL navigate back. If you don't have editable <td>s, this is not an issue.

Is there any standard for JSON API response format?

Their is no agreement on the rest api response formats of big software giants - Google, Facebook, Twitter, Amazon and others, though many links have been provided in the answers above, where some people have tried to standardize the response format.

As needs of the API's can differ it is very difficult to get everyone on board and agree to some format. If you have millions of users using your API, why would you change your response format?

Following is my take on the response format inspired by Google, Twitter, Amazon and some posts on internet:

https://github.com/adnan-kamili/rest-api-response-format

Swagger file:

https://github.com/adnan-kamili/swagger-sample-template

Not able to launch IE browser using Selenium2 (Webdriver) with Java

Well as the stack trace says, you would need to set the protected mode settings to same for all zones in IE. Read the why here : http://jimevansmusic.blogspot.in/2012/08/youre-doing-it-wrong-protected-mode-and.html

and a quick how to from the same link : "In IE, from the Tools menu (or the gear icon in the toolbar in later versions), select "Internet options." Go to the Security tab. At the bottom of the dialog for each zone, you should see a check box labeled "Enable Protected Mode." Set the value of the check box to the same value, either checked or unchecked, for each zone"

Creating a thumbnail from an uploaded image

UPDATE:

If you want to take advantage of Imagick (if it is installed on your server). Note: I didn't use Imagick's nature writeFile because I was having issues with it on my server. File put contents works just as well.

<?php
/**
 * 
 * Generate Thumbnail using Imagick class
 *  
 * @param string $img
 * @param string $width
 * @param string $height
 * @param int $quality
 * @return boolean on true
 * @throws Exception
 * @throws ImagickException
 */
function generateThumbnail($img, $width, $height, $quality = 90)
{
    if (is_file($img)) {
        $imagick = new Imagick(realpath($img));
        $imagick->setImageFormat('jpeg');
        $imagick->setImageCompression(Imagick::COMPRESSION_JPEG);
        $imagick->setImageCompressionQuality($quality);
        $imagick->thumbnailImage($width, $height, false, false);
        $filename_no_ext = reset(explode('.', $img));
        if (file_put_contents($filename_no_ext . '_thumb' . '.jpg', $imagick) === false) {
            throw new Exception("Could not put contents.");
        }
        return true;
    }
    else {
        throw new Exception("No valid image provided with {$img}.");
    }
}

// example usage
try {
    generateThumbnail('test.jpg', 100, 50, 65);
}
catch (ImagickException $e) {
    echo $e->getMessage();
}
catch (Exception $e) {
    echo $e->getMessage();
}
?>

I have been using this, just execute the function after you store the original image and use that location to create the thumbnail. Edit it to your liking...

function makeThumbnails($updir, $img, $id)
{
    $thumbnail_width = 134;
    $thumbnail_height = 189;
    $thumb_beforeword = "thumb";
    $arr_image_details = getimagesize("$updir" . $id . '_' . "$img"); // pass id to thumb name
    $original_width = $arr_image_details[0];
    $original_height = $arr_image_details[1];
    if ($original_width > $original_height) {
        $new_width = $thumbnail_width;
        $new_height = intval($original_height * $new_width / $original_width);
    } else {
        $new_height = $thumbnail_height;
        $new_width = intval($original_width * $new_height / $original_height);
    }
    $dest_x = intval(($thumbnail_width - $new_width) / 2);
    $dest_y = intval(($thumbnail_height - $new_height) / 2);
    if ($arr_image_details[2] == IMAGETYPE_GIF) {
        $imgt = "ImageGIF";
        $imgcreatefrom = "ImageCreateFromGIF";
    }
    if ($arr_image_details[2] == IMAGETYPE_JPEG) {
        $imgt = "ImageJPEG";
        $imgcreatefrom = "ImageCreateFromJPEG";
    }
    if ($arr_image_details[2] == IMAGETYPE_PNG) {
        $imgt = "ImagePNG";
        $imgcreatefrom = "ImageCreateFromPNG";
    }
    if ($imgt) {
        $old_image = $imgcreatefrom("$updir" . $id . '_' . "$img");
        $new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
        imagecopyresized($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
        $imgt($new_image, "$updir" . $id . '_' . "$thumb_beforeword" . "$img");
    }
}

The above function creates images with a uniform thumbnail size. If the image doesn't have the same dimensions as the specified thumbnail size (proportionally), it just has blackspace on the top and bottom.

How to check if the key pressed was an arrow key in Java KeyListener?

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_RIGHT ) {
            //Right arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_LEFT ) {
            //Left arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_UP ) {
            //Up arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN ) {
            //Down arrow key code
    }

    repaint();
}

The KeyEvent codes are all a part of the API: http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html

Message Queue vs. Web Services?

When you use a web service you have a client and a server:

  1. If the server fails the client must take responsibility to handle the error.
  2. When the server is working again the client is responsible of resending it.
  3. If the server gives a response to the call and the client fails the operation is lost.
  4. You don't have contention, that is: if million of clients call a web service on one server in a second, most probably your server will go down.
  5. You can expect an immediate response from the server, but you can handle asynchronous calls too.

When you use a message queue like RabbitMQ, Beanstalkd, ActiveMQ, IBM MQ Series, Tuxedo you expect different and more fault tolerant results:

  1. If the server fails, the queue persist the message (optionally, even if the machine shutdown).
  2. When the server is working again, it receives the pending message.
  3. If the server gives a response to the call and the client fails, if the client didn't acknowledge the response the message is persisted.
  4. You have contention, you can decide how many requests are handled by the server (call it worker instead).
  5. You don't expect an immediate synchronous response, but you can implement/simulate synchronous calls.

Message Queues has a lot more features but this is some rule of thumb to decide if you want to handle error conditions yourself or leave them to the message queue.

Node.js Generate html

If you want to create static files, you can use Node.js File System Library to do that. But if you are looking for a way to create dynamic files as a result of your database or similar queries then you will need a template engine like SWIG. Besides these options you can always create HTML files as you would normally do and serve them over Node.js. To do that, you can read data from HTML files with Node.js File System and write it into response. A simple example would be:

var http = require('http');
var fs   = require('fs');

http.createServer(function (req, res) {
  fs.readFile(req.params.filepath, function (err, content) {
    if(!err) {
      res.end(content);
    } else {
      res.end('404');
    }
  }
}).listen(3000);

But I suggest you to look into some frameworks like Express for more useful solutions.

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

MySQL selecting yesterday's date

Query for the last weeks:

SELECT *
FROM dual
WHERE search_date BETWEEN SUBDATE(CURDATE(), 7) AND CURDATE()

Node.js check if file exists

You can use fs.stat to check if target is a file or directory and you can use fs.access to check if you can write/read/execute the file. (remember to use path.resolve to get full path for the target)

Documentation:

Full example (TypeScript)

import * as fs from 'fs';
import * as path from 'path';

const targetPath = path.resolve(process.argv[2]);

function statExists(checkPath): Promise<fs.Stats> {
  return new Promise((resolve) => {
    fs.stat(checkPath, (err, result) => {
      if (err) {
        return resolve(undefined);
      }

      return resolve(result);
    });
  });
}

function checkAccess(checkPath: string, mode: number = fs.constants.F_OK): Promise<boolean> {
  return new Promise((resolve) => {
    fs.access(checkPath, mode, (err) => {
      resolve(!err);
    });
  });
}

(async function () {
  const result = await statExists(targetPath);
  const accessResult = await checkAccess(targetPath, fs.constants.F_OK);
  const readResult = await checkAccess(targetPath, fs.constants.R_OK);
  const writeResult = await checkAccess(targetPath, fs.constants.W_OK);
  const executeResult = await checkAccess(targetPath, fs.constants.X_OK);
  const allAccessResult = await checkAccess(targetPath, fs.constants.F_OK | fs.constants.R_OK | fs.constants.W_OK | fs.constants.X_OK);

  if (result) {
    console.group('stat');
    console.log('isFile: ', result.isFile());
    console.log('isDir: ', result.isDirectory());
    console.groupEnd();
  }
  else {
    console.log('file/dir does not exist');
  }

  console.group('access');
  console.log('access:', accessResult);
  console.log('read access:', readResult);
  console.log('write access:', writeResult);
  console.log('execute access:', executeResult);
  console.log('all (combined) access:', allAccessResult);
  console.groupEnd();

  process.exit(0);
}());

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

Please make sure that you are not consuming your inputstream anywhere before parsing. Sample code is following: the respose below is httpresponse(i.e. response) and main content is contain inside StringEntity (i.e. getEntity())in form of inputStream(i.e. getContent()).

InputStream rescontent = response.getEntity().getContent();
tsResponse=(TsResponse) transformer.convertFromXMLToObject(rescontent );

How can I connect to MySQL in Python 3 on Windows?

PyMySQL gives MySQLDb like interface as well. You could try in your initialization:

import pymysql
pymysql.install_as_MySQLdb()

Also there is a port of mysql-python on github for python3.

https://github.com/davispuh/MySQL-for-Python-3

How to initialise a string from NSData in Swift

This is the implemented code needed:

in Swift 3.0:

var dataString = String(data: fooData, encoding: String.Encoding.utf8)

or just

var dataString = String(data: fooData, encoding: .utf8)

Older swift version:

in Swift 2.0:

import Foundation

var dataString = String(data: fooData, encoding: NSUTF8StringEncoding)

in Swift 1.0:

var dataString = NSString(data: fooData, encoding:NSUTF8StringEncoding)

Exclude property from type

Typescript 3.5

As of Typescript 3.5, the Omit helper will be included: TypeScript 3.5 RC - The Omit Helper Type

You can use it directly, and you should remove your own definition of the Omit helper when updating.

C#: How do you edit items and subitems in a listview?

I use a hidden textbox to edit all the listview items/subitems. The only problem is that the textbox needs to disappear as soon as any event takes place outside the textbox and the listview doesn't trigger the scroll event so if you scroll the listview the textbox will still be visible. To bypass this problem I created the Scroll event with this overrided listview.

Here is my code, I constantly reuse it so it might be help for someone:

ListViewItem.ListViewSubItem SelectedLSI;
private void listView2_MouseUp(object sender, MouseEventArgs e)
{
    ListViewHitTestInfo i = listView2.HitTest(e.X, e.Y);
    SelectedLSI = i.SubItem;
    if (SelectedLSI == null)
        return;

    int border = 0;
    switch (listView2.BorderStyle)
    {
        case BorderStyle.FixedSingle:
            border = 1;
            break;
        case BorderStyle.Fixed3D:
            border = 2;
            break;
    }

    int CellWidth = SelectedLSI.Bounds.Width;
    int CellHeight = SelectedLSI.Bounds.Height;
    int CellLeft = border + listView2.Left + i.SubItem.Bounds.Left;
    int CellTop =listView2.Top + i.SubItem.Bounds.Top;
    // First Column
    if (i.SubItem == i.Item.SubItems[0])
        CellWidth = listView2.Columns[0].Width;

    TxtEdit.Location = new Point(CellLeft, CellTop);
    TxtEdit.Size = new Size(CellWidth, CellHeight);
    TxtEdit.Visible = true;
    TxtEdit.BringToFront();
    TxtEdit.Text = i.SubItem.Text;
    TxtEdit.Select();
    TxtEdit.SelectAll();
}
private void listView2_MouseDown(object sender, MouseEventArgs e)
{
    HideTextEditor();
}
private void listView2_Scroll(object sender, EventArgs e)
{
    HideTextEditor();
}
private void TxtEdit_Leave(object sender, EventArgs e)
{
    HideTextEditor();
}
private void TxtEdit_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
        HideTextEditor();
}
private void HideTextEditor()
{
    TxtEdit.Visible = false;
    if (SelectedLSI != null)
        SelectedLSI.Text = TxtEdit.Text;
    SelectedLSI = null;
    TxtEdit.Text = "";
}

Android LinearLayout Gradient Background

You can used a custom view to do that. With this solution, it's finished the gradient shapes of all colors in your projects:

class GradientView(context: Context, attrs: AttributeSet) : View(context, attrs) {

    // Properties
    private val paint: Paint = Paint()
    private val rect = Rect()

    //region Attributes
    var start: Int = Color.WHITE
    var end: Int = Color.WHITE
    //endregion

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        // Update Size
        val usableWidth = width - (paddingLeft + paddingRight)
        val usableHeight = height - (paddingTop + paddingBottom)
        rect.right = usableWidth
        rect.bottom = usableHeight
        // Update Color
        paint.shader = LinearGradient(0f, 0f, width.toFloat(), 0f,
                start, end, Shader.TileMode.CLAMP)
        // ReDraw
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawRect(rect, paint)
    }

}

I also create an open source project GradientView with this custom view:

https://github.com/lopspower/GradientView

implementation 'com.mikhaellopez:gradientview:1.1.0'

Disable beep of Linux Bash on Windows 10

right click on sound icon (bottom right) >>> open volume mixer >>> mute console window host

How do I create a link using javascript?

You paste this inside :

<A HREF = "index.html">Click here</A>

What is attr_accessor in Ruby?

attr_accessor is very simple:

attr_accessor :foo

is a shortcut for:

def foo=(val)
  @foo = val
end

def foo
  @foo
end

it is nothing more than a getter/setter for an object

Send raw ZPL to Zebra printer via USB

You can use COM, or P/Invoke from .Net, to open the Winspool.drv driver and send bytes directly to devices. But you don't want to do that; this typically works only for the one device on the one version of the one driver you test with, and breaks on everything else. Take this from long, painful, personal experience.

What you want to do is get a barcode font or library that draws barcodes using plain old GDI or GDI+ commands; there's one for .Net here. This works on all devices, even after Zebra changes the driver.

Importing the private-key/public-certificate pair in the Java KeyStore

With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.

# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12

# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert

To verify the contents of the JKS, you can use this command:

keytool -list -v -keystore mykeystore.jks

If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.

Python loop counter in a for loop

enumerate is what you are looking for.

You might also be interested in unpacking:

# The pattern
x, y, z = [1, 2, 3]

# also works in loops:
l = [(28, 'M'), (4, 'a'), (1990, 'r')]
for x, y in l:
    print(x)  # prints the numbers 28, 4, 1990

# and also
for index, (x, y) in enumerate(l):
    print(x)  # prints the numbers 28, 4, 1990

Also, there is itertools.count() so you could do something like

import itertools

for index, el in zip(itertools.count(), [28, 4, 1990]):
    print(el)  # prints the numbers 28, 4, 1990

How to Count Duplicates in List with LINQ

You can also do Dictionary:

 var list = new List<string> { "a", "b", "a", "c", "a", "b" };
 var result = list.GroupBy(x => x)
            .ToDictionary(y=>y.Key, y=>y.Count())
            .OrderByDescending(z => z.Value);

 foreach (var x in result)
        {
            Console.WriteLine("Value: " + x.Key + " Count: " + x.Value);
        }

Sorting arraylist in alphabetical order (case insensitive)

You need to use custom comparator which will use compareToIgnoreCase, not compareTo.

How to validate a form with multiple checkboxes to have atleast one checked

I checked all answers and even in other similar questions, I tried to find optimal way with help of html class and custom rule.

my html structure for multiple checkboxes are like this

_x000D_
_x000D_
$.validator.addMethod('multicheckbox_rule', function (value, element) {_x000D_
   var $parent = $(element).closest('.checkbox_wrapper');_x000D_
   if($parent.find('.checkbox_item').is(':checked')) return true;_x000D_
            return false;_x000D_
}, 'Please at least select one');
_x000D_
<div class="checkbox_wrapper">_x000D_
<label for="checkbox-1"><input class="checkbox_item" id="checkbox-1"  name="checkbox_item[1]" type="checkbox" value="1" data-rule-multicheckbox_rule="1" /> Checkbox_item 1</label>_x000D_
<label for="checkbox-2"><input class="checkbox_item" id="checkbox-2" name="checkbox_item[2]" type="checkbox" value="1" data-rule-multicheckbox_rule="1" /> Checkbox_item 1</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Compile a DLL in C/C++, then call it from another program

Regarding building a DLL using MinGW, here are some very brief instructions.

First, you need to mark your functions for export, so they can be used by callers of the DLL. To do this, modify them so they look like (for example)

__declspec( dllexport ) int add2(int num){
   return num + 2;
}

then, assuming your functions are in a file called funcs.c, you can compile them:

gcc -shared -o mylib.dll funcs.c

The -shared flag tells gcc to create a DLL.

To check if the DLL has actually exported the functions, get hold of the free Dependency Walker tool and use it to examine the DLL.

For a free IDE which will automate all the flags etc. needed to build DLLs, take a look at the excellent Code::Blocks, which works very well with MinGW.

Edit: For more details on this subject, see the article Creating a MinGW DLL for Use with Visual Basic on the MinGW Wiki.

How can I do factory reset using adb in android?

You can send intent MASTER_CLEAR in adb:

adb shell am broadcast -a android.intent.action.MASTER_CLEAR

or as root

adb shell  "su -c 'am broadcast -a android.intent.action.MASTER_CLEAR'"

What do 'lazy' and 'greedy' mean in the context of regular expressions?

Greedy will consume as much as possible. From http://www.regular-expressions.info/repeat.html we see the example of trying to match HTML tags with <.+>. Suppose you have the following:

<em>Hello World</em>

You may think that <.+> (. means any non newline character and + means one or more) would only match the <em> and the </em>, when in reality it will be very greedy, and go from the first < to the last >. This means it will match <em>Hello World</em> instead of what you wanted.

Making it lazy (<.+?>) will prevent this. By adding the ? after the +, we tell it to repeat as few times as possible, so the first > it comes across, is where we want to stop the matching.

I'd encourage you to download RegExr, a great tool that will help you explore Regular Expressions - I use it all the time.

Bootstrap: align input with button

Use .form-inline = This will left-align labels and inline-block controls for a compact layout

Example: http://jsfiddle.net/hSuy4/292/

<div class="form-inline">
<input type="text">
<input type="button" class="btn" value="submit">
</div>

.form-horizontal = Right align labels and float them to the left to make them appear on the same line as controls which is better for 2 column form layout.

(e.g. 
Label 1: [textbox]
Label 2: [textbox]
     : [button]
)

Examples: http://twitter.github.io/bootstrap/base-css.html#forms

Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists

This issue could be related with missing SSH key at Github or any other git server.

In my case I had copied code to another computer and tried to git pull. It failed.

So I had to generate a new SSH key on that machine and update profile on git server with additional SSH key.

Active Directory LDAP Query by sAMAccountName and Domain

If you're using .NET, use the DirectorySearcher class. You can pass in your domain as a string into the constructor.

// if you domain is domain.com...
string username = "user"
string domain = "LDAP://DC=domain,DC=com";
DirectorySearcher search = new DirectorySearcher(domain);
search.Filter = "(SAMAccountName=" + username + ")";

Credit card payment gateway in PHP?

Stripe has a PHP library to accept credit cards without needing a merchant account: https://github.com/stripe/stripe-php

Check out the documentation and FAQ, and feel free to drop by our chatroom if you have more questions.

Setting a checkbox as checked with Vue.js

In the v-model the value of the property might not be a strict boolean value and the checkbox might not 'recognise' the value as checked/unchecked. There is a neat feature in VueJS to make the conversion to true or false:

<input
  type="checkbox"
  v-model="toggle"
  true-value="yes"
  false-value="no"
>

How to configure the web.config to allow requests of any length

In my case ( Visual Studio 2012 / IIS Express / ASP.NET MVC 4 app / .Net Framework 4.5 ) what really worked after 30 minutes of trial and error was setting the maxQueryStringLength property in the <httpRuntime> tag:

<httpRuntime targetFramework="4.5" maxQueryStringLength="10240" enable="true" />

maxQueryStringLength defaults to 2048.

More about it here:

Expanding the Range of Allowable URLs


I tried setting it in <system.webServer> as @MattVarblow suggests, but it didn't work... and this is because I'm using IIS Express (based on IIS 8) on my dev machine with Windows 8.

When I deployed my app to the production environment (Windows Server 2008 R2 with IIS 7), IE 10 started returning 404 errors in AJAX requests with long query strings. Then I thought that the problem was related to the query string and tried @MattVarblow's answer. It just worked on IIS 7. :)

How to import a new font into a project - Angular 5

You need to put the font files in assets folder (may be a fonts sub-folder within assets) and refer to it in the styles:

@font-face {
  font-family: lato;
  src: url(assets/font/Lato.otf) format("opentype");
}

Once done, you can apply this font any where like:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: 'lato', 'arial', sans-serif;
}

You can put the @font-face definition in your global styles.css or styles.scss and you would be able to refer to the font anywhere - even in your component specific CSS/SCSS. styles.css or styles.scss is already defined in angular-cli.json. Or, if you want you can create a separate CSS/SCSS file and declare it in angular-cli.json along with the styles.css or styles.scss like:

"styles": [
  "styles.css",
  "fonts.css"
],

How do I check if a directory exists? "is_dir", "file_exists" or both?

$save_folder = "some/path/" . date('dmy');

if (!file_exists($save_folder)) {
   mkdir($save_folder, 0777);
}

How do I see which version of Swift I'm using?

Project build settings have a block 'Swift Compiler - Languages', which stores information about Swift Language Version in key-value format. It will show you all available (supported) Swift Language Version for your Xcode and active version also by a tick mark.

Project ? (Select Your Project Target) ? Build Settings ? (Type 'swift_version' in the Search bar) Swift Compiler Language ? Swift Language Version ? Click on Language list to open it (and there will be a tick mark on any one of list-item, that will be current swift version).

Look at this snapshot, for easy understanding:

xcode with described areas highlighted


With help of following code, programmatically you can find Swift version supported by your project.

#if swift(>=5.3)
print("Hello, Swift 5.3")

#elseif swift(>=5.2)
print("Hello, Swift 5.2")

#elseif swift(>=5.1)
print("Hello, Swift 5.1")

#elseif swift(>=5.0)
print("Hello, Swift 5.0")

#elseif swift(>=4.2)
print("Hello, Swift 4.2")

#elseif swift(>=4.1)
print("Hello, Swift 4.1")

#elseif swift(>=4.0)
print("Hello, Swift 4.0")

#elseif swift(>=3.2)
print("Hello, Swift 3.2")

#elseif swift(>=3.0)
print("Hello, Swift 3.0")

#elseif swift(>=2.2)
print("Hello, Swift 2.2")

#elseif swift(>=2.1)
print("Hello, Swift 2.1")

#elseif swift(>=2.0)
print("Hello, Swift 2.0")

#elseif swift(>=1.2)
print("Hello, Swift 1.2")

#elseif swift(>=1.1)
print("Hello, Swift 1.1")

#elseif swift(>=1.0)
print("Hello, Swift 1.0")

#endif

Here is result using Playground (with Xcode 11.x)

enter image description here

java: ArrayList - how can I check if an index exists?

This is what you need ...

public boolean indexExists(final List list, final int index) {
    return index >= 0 && index < list.size();
}

Why not use an plain old array? Indexed access to a List is a code smell I think.

How to make gradient background in android

Why not create an image or a 9 Patch image and use that?

The link below has a nice guide on how to do it:

http://android.amberfog.com/?p=247

If you insist on using a Shape, try the site below (Select Android at bottom left): http://angrytools.com/gradient/

I've created a similar gradient (not exact) to the one you have at this link: http://angrytools.com/gradient/?0_6586f0,54_4B6CD6,2_D6D6D6&0_100,100_100&l_269

Equivalent of Clean & build in Android Studio?

I don't know if there's a way to get a clean build via the UI, but it's easy to do from the commandline using gradle wrapper. From the root directory of your project:

./gradlew clean 

How to convert from java.sql.Timestamp to java.util.Date?

Class java.sql.TimeStamp extends from java.util.Date.

You can directly assign a TimeStamp object to Date reference:

TimeStamp timeStamp = //whatever value you have;
Date startDate = timestampValue;

Setting session variable using javascript

You can use

sessionStorage.SessionName = "SessionData" ,

sessionStorage.getItem("SessionName") and

sessionStorage.setItem("SessionName","SessionData");

See the supported browsers on http://caniuse.com/namevalue-storage

HTML tag <a> want to add both href and onclick working

To achieve this use following html:

<a href="www.mysite.com" onclick="make(event)">Item</a>

<script>
    function make(e) {
        // ...  your function code
        // e.preventDefault();   // use this to NOT go to href site
    }
</script>

Here is working example.

What is FCM token in Firebase?

Here is simple steps add this gradle:

dependencies {
  compile "com.google.firebase:firebase-messaging:9.0.0"
}

No extra permission are needed in manifest like GCM. No receiver is needed to manifest like GCM. With FCM, com.google.android.gms.gcm.GcmReceiver is added automatically.

Migrate your listener service

A service extending InstanceIDListenerService is now required only if you want to access the FCM token.

This is needed if you want to

  • Manage device tokens to send a messages to single device directly, or Send messages to device group, or
  • Send messages to device group, or
  • Subscribe devices to topics with the server subscription management API.

Add Service in manifest

<service
    android:name=".MyInstanceIDListenerService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
    </intent-filter>
</service>

<service
    android:name=".MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>

Change MyInstanceIDListenerService to extend FirebaseInstanceIdService, and update code to listen for token updates and get the token whenever a new token is generated.

public class MyInstanceIDListenerService extends FirebaseInstanceIdService {

  ...

  /**
   * Called if InstanceID token is updated. This may occur if the security of
   * the previous token had been compromised. Note that this is also called
   * when the InstanceID token is initially generated, so this is where
   * you retrieve the token.
   */
  // [START refresh_token]
  @Override
  public void onTokenRefresh() {
      // Get updated InstanceID token.
      String refreshedToken = FirebaseInstanceId.getInstance().getToken();
      Log.d(TAG, "Refreshed token: " + refreshedToken);
      // TODO: Implement this method to send any registration to your app's servers.
      sendRegistrationToServer(refreshedToken);
  }

}

For more information visit

  1. How to import former GCM Projects into Firebase
  2. How to force a token refresh
  3. How to access the token
  4. How to set up firebase

Set value of textarea in jQuery

To set textarea value of encoded HTML (to show as HTML) you should use .html( the_var ) but as mentioned if you try and set it again it may (and probably) will not work.

You can fix this by emptying the textarea .empty() and then setting it again with .html( the_var )

Here's a working JSFiddle: https://jsfiddle.net/w7b1thgw/2/

_x000D_
_x000D_
jQuery(function($){_x000D_
    _x000D_
    $('.load_html').click(function(){_x000D_
        var my_var = $(this).data('my_html');_x000D_
        $('#dynamic_html').html( my_var ); _x000D_
    });_x000D_
    _x000D_
    $('#clear_html').click(function(){_x000D_
        $('#dynamic_html').empty(); _x000D_
    });_x000D_
    _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<textarea id="dynamic_html"></textarea>_x000D_
<a id="google_html" class="load_html" href="#" data-my_html="&lt;a href=&quot;google.com&quot;&gt;google.com&lt;/a&gt;">Google HTML</a>_x000D_
<a id="yahoo_html" class="load_html" href="#" data-my_html="&lt;a href=&quot;yahoo.com&quot;&gt;yahoo.com&lt;/a&gt;">Yahoo HTML</a>_x000D_
<a id="clear_html" href="#">Clear HTML</a>
_x000D_
_x000D_
_x000D_

How do I add slashes to a string in Javascript?

var str = "This is a single quote: ' and so is this: '";
console.log(str);

var replaced = str.replace(/'/g, "\\'");
console.log(replaced);

Gives you:

This is a single quote: ' and so is this: '
This is a single quote: \' and so is this: \'

What is the purpose of Order By 1 in SQL select statement?

This:

ORDER BY 1

...is known as an "Ordinal" - the number stands for the column based on the number of columns defined in the SELECT clause. In the query you provided, it means:

ORDER BY A.PAYMENT_DATE

It's not a recommended practice, because:

  1. It's not obvious/explicit
  2. If the column order changes, the query is still valid so you risk ordering by something you didn't intend

How to get the URL of the current page in C#

Try this :

string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx

string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TESTERS/Default6.aspx

string host = HttpContext.Current.Request.Url.Host;
// localhost

How to Clear Console in Java?

Use the following code:


System.out.println("\f");

'\f' is an escape sequence which represents FormFeed. This is what I have used in my projects to clear the console. This is simpler than the other codes, I guess.

GIT commit as different user without email / or only email

An alternative if the concern is to hide the real email address...If you are committing to Github you don't need a real email you can use <username>@users.noreply.github.com

Regardless of using Github or not, you probably first want change your committer details (on windows use SET GIT_...)

GIT_COMMITTER_NAME='username' 
GIT_COMMITTER_EMAIL='[email protected]'

Then set the author

git commit --author="username <[email protected]>"

https://help.github.com/articles/keeping-your-email-address-private

Bootstrap css hides portion of container below navbar navbar-fixed-top

I know this thread is old, but i just got into that exactly problem and i fixed it by just using the page-header class in my page, under the nav. Also i used the <nav> tag instead of <div> but i am not sure it would present any different behavior.

Using the page-header as a container for the page, you won't need to mess with the <body>, only if you disagree with the default space that the page-header gives you.

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
   <div class="container-fluid">_x000D_
        <nav class="navbar navbar-default navbar-fixed-top">_x000D_
    _x000D_
            <div class="navbar-header">_x000D_
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
                <a class="navbar-brand" href="#">Bootstrap</a>_x000D_
            </div>_x000D_
            <div id="navbar" class="navbar-collapse collapse">_x000D_
                <ul class="nav navbar-nav">_x000D_
                    <li class="active"><a href="#">Home</a></li>_x000D_
                    <li class="dropdown">_x000D_
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
                            <ul class="dropdown-menu">_x000D_
                                <li><a href="#">Action</a></li>_x000D_
                                <li><a href="#">Another action</a></li>_x000D_
                                <li><a href="#">Something else here</a></li>_x000D_
                                <li role="separator" class="divider"></li>_x000D_
                                <li class="dropdown-header">Nav header</li>_x000D_
                                <li><a href="#">Separated link</a></li>_x000D_
                                <li><a href="#">One more separated link</a></li>_x000D_
                            </ul>_x000D_
                        </li>_x000D_
                </ul>_x000D_
                <div class="navbar-right">_x000D_
                </div>_x000D_
            </div>_x000D_
        </nav>_x000D_
    </div>_x000D_
    <div class="page-header">_x000D_
        <div class="clearfix">_x000D_
            <div class="col-md-12">_x000D_
                <div class="col-md-8 col-sm-6 col-xs-12">_x000D_
                    <h1>Registration form <br /><small>A Bootstrap template showing a registration form with standard fields</small></h1>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
        <div class="container">_x000D_
        <div class="row">_x000D_
            <form role="form">_x000D_
                <div class="col-lg-6">_x000D_
                    <div class="well well-sm"><strong><span class="glyphicon glyphicon-asterisk"></span>Required Field</strong></div>_x000D_
                    <div class="form-group">_x000D_
                        <label for="InputName">Enter Name</label>_x000D_
                        <div class="input-group">_x000D_
                            <input type="text" class="form-control" name="InputName" id="InputName" placeholder="Enter Name" required>_x000D_
                            <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>_x000D_
                        </div>_x000D_
                    </div>_x000D_
                    <div class="form-group">_x000D_
                        <label for="InputEmail">Enter Email</label>_x000D_
                        <div class="input-group">_x000D_
                            <input type="email" class="form-control" id="InputEmailFirst" name="InputEmail" placeholder="Enter Email" required>_x000D_
                            <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>_x000D_
                        </div>_x000D_
                    </div>_x000D_
                    <div class="form-group">_x000D_
                        <label for="InputEmail">Confirm Email</label>_x000D_
                        <div class="input-group">_x000D_
                            <input type="email" class="form-control" id="InputEmailSecond" name="InputEmail" placeholder="Confirm Email" required>_x000D_
                            <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>_x000D_
                        </div>_x000D_
                    </div>_x000D_
                    <div class="form-group">_x000D_
                        <label for="InputMessage">Enter Message</label>_x000D_
                        <div class="input-group">_x000D_
                            <textarea name="InputMessage" id="InputMessage" class="form-control" rows="5" required></textarea>_x000D_
                            <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>_x000D_
                        </div>_x000D_
                    </div>_x000D_
                    <input type="submit" name="submit" id="submit" value="Submit" class="btn btn-info pull-right">_x000D_
                </div>_x000D_
            </form>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

How do you specify a debugger program in Code::Blocks 12.11?

  1. Go to Settings -> Debugger -> Common -> GDB/CDB Debugger -> Default
  2. Click on executable path to find the address to gdb32.exe
  3. Locate where your codeblock is installed
  4. Follow the given path:

CodeBlock -> MinGW -> bin -> gdb32.exe (locate it and double click on it)

  1. Press OK

How to make Bootstrap carousel slider use mobile left/right swipe

I needed to add this functionality to a project I was working on recently and adding jQuery Mobile just to solve this problem seemed like overkill, so I came up with a solution and put it on github: bcSwipe (Bootstrap Carousel Swipe).

It's a lightweight jQuery plugin (~600 bytes minified vs jQuery Mobile touch events at 8kb), and it's been tested on Android and iOS.

This is how you use it:

$('.carousel').bcSwipe({ threshold: 50 });

Oracle 11g SQL to get unique values in one column of a multi-column query

This will be more efficient, plus you have control over the ordering it uses to pick a value:

SELECT DISTINCT
       FIRST_VALUE(person)
          OVER(PARTITION BY language
               ORDER BY person)
      ,language
FROM   tableA;

If you really don't care which person is picked for each language, you can omit the ORDER BY clause:

SELECT DISTINCT
       FIRST_VALUE(person)
          OVER(PARTITION BY language)
      ,language
FROM   tableA;

WARNING: Exception encountered during context initialization - cancelling refresh attempt

In my case, I'm using j-hipster and I had to do ./mvnw clean to overcome this warning.

jQuery - keydown / keypress /keyup ENTERKEY detection?

JavaScript/jQuery

$("#entersomething").keyup(function(e){ 
    var code = e.key; // recommended to use e.key, it's normalized across devices and languages
    if(code==="Enter") e.preventDefault();
    if(code===" " || code==="Enter" || code===","|| code===";"){
        $("#displaysomething").html($(this).val());
    } // missing closing if brace
});

HTML

<input id="entersomething" type="text" /> <!-- put a type attribute in -->
<div id="displaysomething"></div>

Check if string doesn't contain another string

Use this as your WHERE condition

WHERE CHARINDEX('Apples', column) = 0 

Javascript: The prettiest way to compare one value against multiple values

You can use a switch:

switch (foobar) {
  case foo:
  case bar:
    // do something
}

How to specify HTTP error code?

The version of the errorHandler middleware bundled with some (perhaps older?) versions of express seems to have the status code hardcoded. The version documented here: http://www.senchalabs.org/connect/errorHandler.html on the other hand lets you do what you are trying to do. So, perhaps trying upgrading to the latest version of express/connect.

How to attach a process in gdb

Try one of these:

gdb -p 12271
gdb /path/to/exe 12271

gdb /path/to/exe
(gdb) attach 12271

Refreshing data in RecyclerView and keeping its scroll position

I was making a mistake like this, maybe it will help someone :)

If you use recyclerView.setAdapter every time new data come, it calls the adapter clear() method every time you use it, which causes the recyclerview to refresh and start over. To get rid of this, you need to use adapter.notiftyDatasetChanced().

MongoDb query condition on comparing 2 fields

In case performance is more important than readability and as long as your condition consists of simple arithmetic operations, you can use aggregation pipeline. First, use $project to calculate the left hand side of the condition (take all fields to left hand side). Then use $match to compare with a constant and filter. This way you avoid javascript execution. Below is my test in python:

import pymongo
from random import randrange

docs = [{'Grade1': randrange(10), 'Grade2': randrange(10)} for __ in range(100000)]

coll = pymongo.MongoClient().test_db.grades
coll.insert_many(docs)

Using aggregate:

%timeit -n1 -r1 list(coll.aggregate([
    {
        '$project': {
            'diff': {'$subtract': ['$Grade1', '$Grade2']},
            'Grade1': 1,
            'Grade2': 1
        }
    },
    {
        '$match': {'diff': {'$gt': 0}}
    }
]))

1 loop, best of 1: 192 ms per loop

Using find and $where:

%timeit -n1 -r1 list(coll.find({'$where': 'this.Grade1 > this.Grade2'}))

1 loop, best of 1: 4.54 s per loop

What does "while True" mean in Python?

my question: while WHAT is True?

Everything inside the () of the while statement is going to be evaluated as a boolean. Meaning it gets converted into either true or false.

Consider in the statement while(6 > 5)

It first evaluates the expression 6 > 5 which is true so is the same as saying while(true)

Anything that is not FALSE, 0, an emptry string "", null, or undefined is likely to be evaluated to true.

When I first started programming I used to do things like if(foo == true), I didn't realise that was virtually the same thing as if(foo).

So when you say while(true) its like are saying while(true == true)

So to answer you question: While TRUE is True.