Programs & Examples On #Disco

Disco is a distributed computing framework based on the MapReduce paradigm. Disco is open-source; developed by Nokia Research Center to solve real problems in handling massive amounts of data. Disco distributes and replicates your data, and schedules your jobs efficiently.

Server Discovery And Monitoring engine is deprecated

This works fine for me, and no more errors.

mongoose
.connect(URL_of_mongodb, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => console.log('DB Connected!'))
.catch(err => {
console.log(`DB Connection Error: ${err}`);
});

How to prevent Google Colab from disconnecting?

The most voted answer certainly works for me but it makes the Manage session window popping up again and again.
I've solved that by auto clicking the refresh button using browser console like below

function ClickRefresh(){
    console.log("Clicked on refresh button"); 
    document.querySelector("paper-icon-button").click()
}
setInterval(ClickRefresh, 60000)

Feel free to contribute more snippets for this at this gist https://gist.github.com/Subangkar/fd1ef276fd40dc374a7c80acc247613e

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

For anybody facing a similar issue at this point in time, all you need to do is update your Android Studio to the latest version

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Others have pointed to the root issue, but in my case I was using dbeaver and initially when setting up the mysql connection with dbeaver was selecting the wrong mysql driver (credit here for answer: https://github.com/dbeaver/dbeaver/issues/4691#issuecomment-442173584 )

Selecting the MySQL choice in the below figure will give the error mentioned as the driver is mysql 4+ which can be seen in the database information tip.


For this error selecting the top mysql 4+ choice in this figure will give the error mentioned in this quesiton


Rather than selecting the MySQL driver instead select the MySQL 8+ driver, shown in the figure below.


enter image description here

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

Go to preferences(settings) : click on Build,Execution,Deployment .....then select : Instant Run ......and uncheck its topmost checkbox (i.e Disable Instant Run)

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

And clean the project.

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

I simply ran composer update and it resolved my issue - Laravel 6.*

Angular + Material - How to refresh a data source (mat-table)

So for me, nobody gave the good answer to the problem that i met which is almost the same than @Kay. For me it's about sorting, sorting table does not occur changes in the mat. I purpose this answer since it's the only topic that i find by searching google. I'm using Angular 6.

As said here:

Since the table optimizes for performance, it will not automatically check for changes to the data array. Instead, when objects are added, removed, or moved on the data array, you can trigger an update to the table's rendered rows by calling its renderRows() method.

So you just have to call renderRows() in your refresh() method to make your changes appears.

See here for integration.

Kubernetes Pod fails with CrashLoopBackOff

I faced similar issue "CrashLoopBackOff" when I debugged getting pods and logs of pod. Found out that my command arguments are wrong

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

I Had the same problem and finally reached to the solution.

add "--stacktrace --debug" to your command-line options(File -> Settings -> Compiler) then run it. This will show the problem(unwanted code) in your code.

Put request with simple string as request body

I was having trouble sending plain text and found that I needed to surround the body's value with double quotes:

const request = axios.put(url, "\"" + values.guid + "\"", {
    headers: {
        "Accept": "application/json",
        "Content-type": "application/json",
        "Authorization": "Bearer " + sessionStorage.getItem('jwt')
    }
})

My webapi server method signature is this:

public IActionResult UpdateModelGuid([FromRoute] string guid, [FromBody] string newGuid)

Unit Tests not discovered in Visual Studio 2017

In the case of .NET Framework, in the test project there were formerly references to the following DLLs:

Microsoft.VisualStudio.TestPlatform.TestFramework
Microsoft.VisualStudio.TestPlatform.TestFramework.Extentions

I deleted them and added reference to:

Microsoft.VisualStudio.QualityTools.UnitTestFramework

And then all the tests appeared and started working in the same way as before.

I tried almost all of the other suggestions above before, but simply re-referencing the test DLLs worked alright. I posted this answer for those who are in my case.

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

Sending private messages to user

The above answers work fine too, but I've found you can usually just use message.author.send("blah blah") instead of message.author.sendMessage("blah blah").

-EDIT- : This is because the sendMessage command is outdated as of v12 in Discord Js

.send tends to work better for me in general than .sendMessage, which sometimes runs into problems. Hope that helps a teeny bit!

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

Using Apollo Server 2.

Per https://github.com/apollographql/apollo-client/issues/4778#issuecomment-509638071, this solved my problem:

try 'ws://localhost:4000/graphql'

...since incoming and outgoing requests now use the same address.

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

IF YOU ARE NOT IN PRODUCTION, you can look in your flywayTable in the data base and remove the line which contain the name of the script which has been applied.

flywayTable is a project option which define the name of the table in the db used by flyway which contain information about the version of this db, already applied scripts...

currently unable to handle this request HTTP ERROR 500

Have you included the statement include ("fileName.php"); ?

Are you sure that file is in the correct directory?

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

The most simple way is to use Record type Record<number, productDetails >

interface productDetails {
   productId : number , 
   price : number , 
   discount : number
};

const myVar : Record<number, productDetails> = {
   1: {
       productId : number , 
       price : number , 
       discount : number
   }
}

Merge two dataframes by index

By default:
join is a column-wise left join
pd.merge is a column-wise inner join
pd.concat is a row-wise outer join

pd.concat:
takes Iterable arguments. Thus, it cannot take DataFrames directly (use [df,df2])
Dimensions of DataFrame should match along axis

Join and pd.merge:
can take DataFrame arguments

Deprecation warning in Moment.js - Not in a recognized ISO format

Check out all their awesome documentation!

Here is where they discuss the Warning Message.

String + Format

Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.

For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

moment("12-25-1995", "MM-DD-YYYY");

String + Formats (multiple formats)

If you have more than one format, check out their String + Formats (with an 's').

If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.

moment("12-25-1995", ["MM-DD-YYYY", "YYYY-MM-DD"]);

Please checkout the documentation for anything more specific.

Timezone

Checkout Parsing in Zone, the equivalent documentation for timezones.

The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.

var b = moment.tz("May 12th 2014 8PM", "MMM Do YYYY hA", "America/Toronto");

EDIT

//...
var dateFormat = "YYYY-M-D H:m"; //<-------- This part will get rid of the warning.
var aus1_s, aus2_s, aus3_s, aus4_s, aus5_s, aus6_s, aus6_e;
if ($("#custom1 :selected").val() == "AU" ) {
    var region = 'Australia/Sydney';

    aus1_s = moment.tz('2016-9-26 19:30', dateFormat, region);              
    aus2_s = moment.tz('2016-10-2 19:30', dateFormat, region);              
    aus3_s = moment.tz('2016-10-9 19:30', dateFormat, region);                  
    aus4_s = moment.tz('2016-10-16 19:30', dateFormat, region);                 
    aus5_s = moment.tz('2016-10-23 19:30', dateFormat, region);
    aus6_s = moment.tz('2016-10-30 19:30', dateFormat, region);
    aus6_e = moment.tz('2016-11-5 19:30', dateFormat, region);
} else if ($("#custom1 :selected").val() == "NZ" ) {
    var region = 'Pacific/Auckland';

    aus1_s =  moment.tz('2016-9-28 20:30', dateFormat, region);
    aus2_s =  moment.tz('2016-10-4 20:30', dateFormat, region);
    aus3_s =  moment.tz('2016-10-11 20:30', dateFormat, region);
    aus4_s =  moment.tz('2016-10-18 20:30', dateFormat, region);
    aus5_s =  moment.tz('2016-10-25 20:30', dateFormat, region);
    aus6_s =  moment.tz('2016-11-2 20:30', dateFormat, region);
    aus6_e =  moment.tz('2016-11-9 20:30', dateFormat, region);
}
//...

No assembly found containing an OwinStartupAttribute Error

Check if you have the Startup class created in your project. This is an example:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof({project_name}.Startup))]

namespace AuctionPortal
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

Moment.js - How to convert date string into date?

if you have a string of date, then you should try this.

const FORMAT = "YYYY ddd MMM DD HH:mm";

const theDate = moment("2019 Tue Apr 09 13:30", FORMAT);
// Tue Apr 09 2019 13:30:00 GMT+0300

const theDate1 = moment("2019 Tue Apr 09 13:30", FORMAT).format('LL')
// April 9, 2019

or try this :

const theDate1 = moment("2019 Tue Apr 09 13:30").format(FORMAT);

What are the "spec.ts" files generated by Angular CLI for?

The .spec.ts files are for unit tests for individual components. You can run Karma task runner through ng test. In order to see code coverage of unit test cases for particular components run ng test --code-coverage

Make Error 127 when running trying to compile code

Error 127 means one of two things:

  1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
  2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

if the problem is (2), then you can solve it in a few diff ways:

  1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
  2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
  3. build your own cross-compiler using something like crosstool-ng.
  4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

Basic example for sharing text or image with UIActivityViewController in Swift

You may use the following functions which I wrote in one of my helper class in a project.

just call

showShareActivity(msg:"message", image: nil, url: nil, sourceRect: nil) 

and it will work for both iPhone and iPad. If you pass any view's CGRect value by sourceRect it will also shows a little arrow in iPad.

func topViewController()-> UIViewController{
    var topViewController:UIViewController = UIApplication.shared.keyWindow!.rootViewController!

    while ((topViewController.presentedViewController) != nil) {
        topViewController = topViewController.presentedViewController!;
    }

    return topViewController
}

func showShareActivity(msg:String?, image:UIImage?, url:String?, sourceRect:CGRect?){
    var objectsToShare = [AnyObject]()

    if let url = url {
        objectsToShare = [url as AnyObject]
    }

    if let image = image {
        objectsToShare = [image as AnyObject]
    }

    if let msg = msg {
        objectsToShare = [msg as AnyObject]
    }

    let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
    activityVC.modalPresentationStyle = .popover
    activityVC.popoverPresentationController?.sourceView = topViewController().view
    if let sourceRect = sourceRect {
        activityVC.popoverPresentationController?.sourceRect = sourceRect
    }

    topViewController().present(activityVC, animated: true, completion: nil)
}

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

None of these answers worked for me. I am using Android studio 3.4.1.

I was able to build the project but Android studio showing this error when I was going to deploy it to mobile device. It turns out it is "instant runs" fault.

Follow this answer: https://stackoverflow.com/a/42695197/3197467

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

It's happened to me a couple of times - when I Clean the project and Build it again it tends to be fine.

configuring project ':app' failed to find Build Tools revision

It happens because Build Tools revision 24.4.1 doesn't exist.

The latest version is 23.0.2.
These tools is included in the SDK package and installed in the <sdk>/build-tools/ directory.

Don't confuse the Android SDK Tools with SDK Build Tools.

Change in your build.gradle

android {
   buildToolsVersion "23.0.2"
   // ...

}

How to send push notification to web browser?

this is simple way to do push notification for all browser https://pushjs.org

Push.create("Hello world!", {
body: "How's it hangin'?",
icon: '/icon.png',
timeout: 4000,
onClick: function () {
    window.focus();
    this.close();
 }
});

How to build and use Google TensorFlow C++ api

Tensorflow itself only provides very basic examples about C++ APIs.
Here is a good resource which includes examples of datasets, rnn, lstm, cnn and more
tensorflow c++ examples

Can a website detect when you are using Selenium with chromedriver?

The bot detection I've seen seems more sophisticated or at least different than what I've read through in the answers below.

EXPERIMENT 1:

  1. I open a browser and web page with Selenium from a Python console.
  2. The mouse is already at a specific location where I know a link will appear once the page loads. I never move the mouse.
  3. I press the left mouse button once (this is necessary to take focus from the console where Python is running to the browser).
  4. I press the left mouse button again (remember, cursor is above a given link).
  5. The link opens normally, as it should.

EXPERIMENT 2:

  1. As before, I open a browser and the web page with Selenium from a Python console.

  2. This time around, instead of clicking with the mouse, I use Selenium (in the Python console) to click the same element with a random offset.

  3. The link doesn't open, but I am taken to a sign up page.

IMPLICATIONS:

  • opening a web browser via Selenium doesn't preclude me from appearing human
  • moving the mouse like a human is not necessary to be classified as human
  • clicking something via Selenium with an offset still raises the alarm

Seems mysterious, but I guess they can just determine whether an action originates from Selenium or not, while they don't care whether the browser itself was opened via Selenium or not. Or can they determine if the window has focus? Would be interesting to hear if anyone has any insights.

Remote desktop connection protocol error 0x112f

Might not be a solution for all but I found that if I reduced the screen resolution of the RDP session, I was able to get in. The server was at 95% capacity I went from 3 high res monitors to 1 800x600 window.

How to customize the configuration file of the official PostgreSQL Docker image?

A fairly low-tech solution to this problem seems to be to declare the service (I'm using swarm on AWS and a yaml file) with your database files mounted to a persisted volume (here AWS EFS as denoted by the cloudstor:aws driver specification).

  version: '3.3'
  services:
    database:
      image: postgres:latest
      volumes:
        - postgresql:/var/lib/postgresql
        - postgresql_data:/var/lib/postgresql/data
    volumes:
       postgresql:
         driver: "cloudstor:aws" 
       postgresql_data:
         driver: "cloudstor:aws"
  1. The db comes up as initialized with the image default settings.
  2. You edit the conf settings inside the container, e.g if you want to increase the maximum number of concurrent connections that requires a restart
  3. stop the running container (or scale the service down to zero and then back to one)
  4. the swarm spawns a new container, which this time around picks up your persisted configuration settings and merrily applies them.

A pleasant side-effect of persisting your configuration is that it also persists your databases (or was it the other way around) ;-)

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

If you are using intellij and want to use gradle you need to add this to the dependencies section of build.gradle file:

testImplementation("org.junit.jupiter:junit-jupiter-api:5.4.2")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.4.2")

How to search JSON data in MySQL?

  1. Storing JSON in database violates the first normal form.

    The best thing you can do is to normalize and store features in another table. Then you will be able to use a much better looking and performing query with joins. Your JSON even resembles the table.

  2. Mysql 5.7 has builtin JSON functionality:
    http://mysqlserverteam.com/mysql-5-7-lab-release-json-functions-part-2-querying-json-data/

  3. Correct pattern is:

    WHERE  `attribs_json` REGEXP '"1":{"value":[^}]*"3"[^}]*}'
    

    [^}] will match any character except }

How to restart ADB manually from Android Studio

After reinstalling Android Studio, Is working without adb kill-server

How to get the hostname of the docker host from inside a docker container on that host without env vars

You can pass in the hostname as an environment variable. You could also mount /etc so you can cat /etc/hostname. But I agree with Vitaly, this isn't the intended use case for containers IMO.

Visual Studio 2015 or 2017 does not discover unit tests

I had the same issue. The unit test template of Visual Studio 2015 (Update 3) generates a class with TestContext property defined as follow:

    private TestContext testContextInstance;

    /// <summary>
    ///Gets or sets the test context which provides
    ///information about and functionality for the current test run.
    ///</summary>
    public TestContext TestContext
    {
        get
        {
            return testContextInstance;
        }
        set
        {
            testContextInstance = value;
        }
    }

After changing it to a public field (ungly) the test runner could discover the test.

public TestContext TestContext;

Very strange behaviour, but it was the cause of the issue in my case.

pandas loc vs. iloc vs. at vs. iat?

Let's start with this small df:

import pandas as pd
import time as tm
import numpy as np
n=10
a=np.arange(0,n**2)
df=pd.DataFrame(a.reshape(n,n))

We'll so have

df
Out[25]: 
        0   1   2   3   4   5   6   7   8   9
    0   0   1   2   3   4   5   6   7   8   9
    1  10  11  12  13  14  15  16  17  18  19
    2  20  21  22  23  24  25  26  27  28  29
    3  30  31  32  33  34  35  36  37  38  39
    4  40  41  42  43  44  45  46  47  48  49
    5  50  51  52  53  54  55  56  57  58  59
    6  60  61  62  63  64  65  66  67  68  69
    7  70  71  72  73  74  75  76  77  78  79
    8  80  81  82  83  84  85  86  87  88  89
    9  90  91  92  93  94  95  96  97  98  99

With this we have:

df.iloc[3,3]
Out[33]: 33

df.iat[3,3]
Out[34]: 33

df.iloc[:3,:3]
Out[35]: 
    0   1   2   3
0   0   1   2   3
1  10  11  12  13
2  20  21  22  23
3  30  31  32  33



df.iat[:3,:3]
Traceback (most recent call last):
   ... omissis ...
ValueError: At based indexing on an integer index can only have integer indexers

Thus we cannot use .iat for subset, where we must use .iloc only.

But let's try both to select from a larger df and let's check the speed ...

# -*- coding: utf-8 -*-
"""
Created on Wed Feb  7 09:58:39 2018

@author: Fabio Pomi
"""

import pandas as pd
import time as tm
import numpy as np
n=1000
a=np.arange(0,n**2)
df=pd.DataFrame(a.reshape(n,n))
t1=tm.time()
for j in df.index:
    for i in df.columns:
        a=df.iloc[j,i]
t2=tm.time()
for j in df.index:
    for i in df.columns:
        a=df.iat[j,i]
t3=tm.time()
loc=t2-t1
at=t3-t2
prc = loc/at *100
print('\nloc:%f at:%f prc:%f' %(loc,at,prc))

loc:10.485600 at:7.395423 prc:141.784987

So with .loc we can manage subsets and with .at only a single scalar, but .at is faster than .loc

:-)

How to use color picker (eye dropper)?

It is just called the eyedropper tool. There is no shortcut key for it that I'm aware of. The only way you can use it now is by clicking on the color picker box in styles sidebar and then clicking on the page as you have already been doing.

Synchronous XMLHttpRequest warning and <script>

UPDATE: This has been fixed in jQuery 3.x. If you have no possibility to upgrade to any version above 3.0, you could use following snippet BUT be aware that now you will lose sync behaviour of script loading in the targeted content.

You could fix it, setting explicitly async option of xhr request to true:

$.ajaxPrefilter(function( options, original_Options, jqXHR ) {
    options.async = true;
});

laravel the requested url was not found on this server

First enable a2enmod rewrite next restart the apache

/etc/init.d/apache2 restart

click here for answer these question

How to configure Docker port mapping to use Nginx as an upstream proxy?

@gdbj's answer is a great explanation and the most up to date answer. Here's however a simpler approach.

So if you want to redirect all traffic from nginx listening to 80 to another container exposing 8080, minimum configuration can be as little as:

nginx.conf:

server {
    listen 80;

    location / {
        proxy_pass http://client:8080; # this one here
        proxy_redirect off;
    }

}

docker-compose.yml

version: "2"
services:
  entrypoint:
    image: some-image-with-nginx
    ports:
      - "80:80"
    links:
      - client  # will use this one here

  client:
    image: some-image-with-api
    ports:
      - "8080:8080"

Docker docs

Fixing npm path in Windows 8 and 10

If after installing your npm successfully, and you want to install VueJS then this is what you should do

after running the following command (as Admin)

npm install --global vue-cli

It will place the vue.cmd in the following directory C:\Users\YourUserName\AppData\Roaming\npm

you will see this in your directory.

Now to use vue as a command in cmd. Open the cmd as admin and run the following command.

setx /M path "%path%;%appdata%\npm"

Now restart the cmd and run the vue again. It should work just fine, and then you can begin to develop with VueJS.

I hope this helps.

Debugging with Android Studio stuck at "Waiting For Debugger" forever

I had the same problem. Restart my android device and closed the adb.exe process. With that I could solve the problem

Postman: sending nested JSON object

Select the body tab and select application/json in the Content-Type drop-down and add a body like this:

{
  "Username":"ABC",
  "Password":"ABC"
}

enter image description here

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

My issue was that i had multiple versions of MS SQL express installed. I went to installation folder C:/ProgramFiles/MicrosoftSQL Server/ where i found 3 versions of it. I deleted 2 folders, and left only MSSQL13.SQLEXPRESS which solved the problem.

How can I inspect the file system of a failed `docker build`?

Docker caches the entire filesystem state after each successful RUN line.

Knowing that:

  • to examine the latest state before your failing RUN command, comment it out in the Dockerfile (as well as any and all subsequent RUN commands), then run docker build and docker run again.
  • to examine the state after the failing RUN command, simply add || true to it to force it to succeed; then proceed like above (keep any and all subsequent RUN commands commented out, run docker build and docker run)

Tada, no need to mess with Docker internals or layer IDs, and as a bonus Docker automatically minimizes the amount of work that needs to be re-done.

Read specific columns with pandas or other python module

Got a solution to above problem in a different way where in although i would read entire csv file, but would tweek the display part to show only the content which is desired.

import pandas as pd

df = pd.read_csv('data.csv', skipinitialspace=True)
print df[['star_name', 'ra']]

This one could help in some of the scenario's in learning basics and filtering data on the basis of columns in dataframe.

How to mount host volumes into docker containers in Dockerfile during build

As many have already answered, mounting host volumes during the build is not possible. I just would like to add docker-compose way, I think it'll be nice to have, mostly for development/testing usage

Dockerfile

FROM node:10
WORKDIR /app
COPY . .
RUN npm ci
CMD sleep 999999999

docker-compose.yml

version: '3'
services:
  test-service:
    image: test/image
    build:
      context: .
      dockerfile: Dockerfile
    container_name: test
    volumes:
      - ./export:/app/export
      - ./build:/app/build

And run your container by docker-compose up -d --build

Java ElasticSearch None of the configured nodes are available

NoNodeAvailableException[None of the configured nodes are available: [{#transport#-1}{UfB9geJCR--spyD7ewmoXQ}{192.168.1.245}{192.168.1.245:9300}]]

In my case it was the difference in versions. If you check the logs in elasticsearch cluster you will see.

Elasticsearch logs

[node1] exception caught on transport layer [NettyTcpChannel{localAddress=/192.168.1.245:9300, remoteAddress=/172.16.1.47:65130}], closing connection
java.lang.IllegalStateException: Received message from unsupported version: [5.0.0] minimal compatible version is: [5.6.0]

I was using elasticsearch client and transport version 5.1.1. And my elasticsearch cluster version was in 6. So I changes my library version to 5.4.3.

Explanation of polkitd Unregistered Authentication Agent

Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.

No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?

As it is correctly suggested in previous answers, lazy loading means that when you fetch your object from the database, the nested objects are not fetched (and may be fetched later when required).

Now Jackson tries to serialize the nested object (== make JSON out of it), but fails as it finds JavassistLazyInitializer instead of normal object. This is the error you see. Now, how to solve it?

As suggested by CP510 previously, one option is to suppress the error by this line of configuration:

spring.jackson.serialization.fail-on-empty-beans=false

But this is dealing with the symptoms, not the cause. To solve it elegantly, you need to decide whether you need this object in JSON or not?

  1. Should you need the object in JSON, remove the FetchType.LAZY option from the field that causes it (it might also be a field in some nested object, not only in the root entity you are fetching).

  2. If do not need the object in JSON, annotate the getter of this field (or the field itself, if you do not need to accept incoming values either) with @JsonIgnore, for example:

    // this field will not be serialized to/from JSON @JsonIgnore private NestedType secret;

Should you have more complex needs (e.g. different rules for different REST controllers using the same entity), you can use jackson views or filtering or for very simple use case, fetch nested objects separately.

Disable Proximity Sensor during call

I also had problem with proximity sensor (I shattered screen in that region on my Nexus 6, Android Marshmallow) and none of proposed solutions / third party apps worked when I tried to disable proximity sensor. What worked for me was to calibrate the sensor using Proximity Sensor Reset/Repair. You have to follow the instruction in app (cover sensor and uncover it) and then restart your phone. Although my sensor is no longer behind the glass, it still showed slightly different results when covered / uncovered and recalibration did the job.

What I tried and didn't work? Proximity Screen Off Lite, Macrodroid and KinScreen.

What would've I tried had it still not worked?[XPOSED] Sensor Disabler, but it requires you to be rooted and have Xposed Framework, so I'm really glad I've found the easier way.

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

net use \\<host> /delete should work, but many times it does not.

net stop workstation as @DaveInCaz offered works in such cases.

I have some why and hows I couldn't fit into a comment.

  • It's not enough to restart the Workstation service (e.g. from services.msc console)
    The service probably needs to be disabled for some short period of time. If you do this restart from a script, might be better to add a 1 second delay.

  • In cases when net use \\<host> /delete does not work because another program is still using that share, you can identify such program and remove the blocking handle without closing it. Use Sysinternals Process Explorer, press Ctrl+F for search and enter the name of host machine owning such share. Click on each result, program window behind search dialog jumps to found program's handle. Right click that handle and select Close Handle. (or just close such program if you can) This works only in regular cases where there really is a program blocking the share disconnect. Not in those weird cases when it's blocked for no reason.

  • elevated account has it's own environment. This brings some unexpected behavior.
    If you do net use command in an elevated cmd/PS console, it will not affect which user will Windows Explorer use to access the share.
    And also other way around, if you run a program from the share and the program will ask and get elevated access, that program will loose connection to that share and any files it might need to run. You need to run net use from elevated cmd/PS to create an elevated share connection to that share.

  • Removing Recent folders from Quick Access in Windows Explorer (top of left panel) might help in certain cases.
    If the Host you are connecting to offers different access levels based on user, and/or has a Guest user (anonymous) share access, this is a situation you might often run into.
    When you access a share using your username, folder inside such share might get assigned to Quick Access panel as a Recent item. When you open Windows Explorer after restart, Recent items inside Quick Access will be checked and a connection will be made to the Host machine and will stay open in form of a MUP. If your share accepts both authorized and anonymous connections, just opening Windows Explorer will create anonymous connection and when you click on a share which needs authorization, you will not get credential dialog but an error.

Why is it that "No HTTP resource was found that matches the request URI" here?

Your problems have nothing to do with POST/GET but only with how you specify parameters in RouteAttribute. To ensure this, I added support for both verbs in my samples.

Let's go back to two very simple working examples.

[Route("api/deliveryitems/{anyString}")]
[HttpGet, HttpPost]
public HttpResponseMessage GetDeliveryItemsOne(string anyString)
{
    return Request.CreateResponse<string>(HttpStatusCode.OK, anyString);
}

And

[Route("api/deliveryitems")]
[HttpGet, HttpPost]
public HttpResponseMessage GetDeliveryItemsTwo(string anyString = "default")
{
    return Request.CreateResponse<string>(HttpStatusCode.OK, anyString);
}

The first sample says that the "anyString" is a path segment parameter (part of the URL).

First sample example URL is:

  • localhost:xxx/api/deliveryItems/dkjd;dslkf;dfk;kkklm;oeop
    • returns "dkjd;dslkf;dfk;kkklm;oeop"

The second sample says that the "anyString" is a query string parameter (optional here since a default value has been provided, but you can make it non-optional by simply removing the default value).

Second sample examples URL are:

  • localhost:xxx/api/deliveryItems?anyString=dkjd;dslkf;dfk;kkklm;oeop
    • returns "dkjd;dslkf;dfk;kkklm;oeop"
  • localhost:xxx/api/deliveryItems
    • returns "default"

Of course, you can make it even more complex, like with this third sample:

[Route("api/deliveryitems")]
[HttpGet, HttpPost]
public HttpResponseMessage GetDeliveryItemsThree(string anyString, string anotherString = "anotherDefault")
{
    return Request.CreateResponse<string>(HttpStatusCode.OK, anyString + "||" + anotherString);
}

Third sample examples URL are:

  • localhost:xxx/api/deliveryItems?anyString=dkjd;dslkf;dfk;kkklm;oeop
    • returns "dkjd;dslkf;dfk;kkklm;oeop||anotherDefault"
  • localhost:xxx/api/deliveryItems
    • returns "No HTTP resource was found that matches the request URI ..." (parameter anyString is mandatory)
  • localhost:xxx/api/deliveryItems?anotherString=bluberb&anyString=dkjd;dslkf;dfk;kkklm;oeop
    • returns "dkjd;dslkf;dfk;kkklm;oeop||bluberb"
    • note that the parameters have been reversed, which does not matter, this is not possible with "URL-style" of first example

When should you use path segment or query parameters? Some advice has already been given here: REST API Best practices: Where to put parameters?

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

I had the same problem, by accident mistake. I'll share it here, in case someone may have made the same mistake.

Basic steps, as others described.

  1. Download putty and puttygen, or the putty package and install it.
  2. Get the .pem file from your AWS EC2 instance.
  3. Use puttygen to convert the .pem file so that you'll have a private key --- mistake happened here. I chose "Conversions" tab from PuttyGen, and load my .pem file. After loading pem file, here DO NOT hit "Generate", instead directly "Save private key". That's the key you need. If you click Generate, you'll have a totally different pair of keys.
  4. In putty, use [email protected], and load the private key at SSH/Auth

Good luck!

Java 8 Stream and operation on arrays

You can turn an array into a stream by using Arrays.stream():

int[] ns = new int[] {1,2,3,4,5};
Arrays.stream(ns);

Once you've got your stream, you can use any of the methods described in the documentation, like sum() or whatever. You can map or filter like in Python by calling the relevant stream methods with a Lambda function:

Arrays.stream(ns).map(n -> n * 2);
Arrays.stream(ns).filter(n -> n % 4 == 0);

Once you're done modifying your stream, you then call toArray() to convert it back into an array to use elsewhere:

int[] ns = new int[] {1,2,3,4,5};
int[] ms = Arrays.stream(ns).map(n -> n * 2).filter(n -> n % 4 == 0).toArray();

How do you find out the type of an object (in Swift)?

Old question, but this works for my need (Swift 5.x):

print(type(of: myObjectName))

connecting MySQL server to NetBeans

  1. Download XAMPP
  2. Run XAMPP server. Click on Start button in front of MY SQL. Now you can see that color is changed to green. Now, Click on Admin.The new browser window will be open. Copy the link from browser and paste to the Admin properties as shown in below. Set path in the admin properties of database connection. Click on OK. Now your database is connected. enter image description here

Sniffing/logging your own Android Bluetooth traffic

Android 4.4 (Kit Kat) does have a new sniffing capability for Bluetooth. You should give it a try.

If you don’t own a sniffing device however, you aren’t necessarily out of luck. In many cases we can obtain positive results with a new feature introduced in Android 4.4: the ability to capture all Bluetooth HCI packets and save them to a file.

When the Analyst has finished populating the capture file by running the application being tested, he can pull the file generated by Android into the external storage of the device and analyze it (with Wireshark, for example).

Once this setting is activated, Android will save the packet capture to /sdcard/btsnoop_hci.log to be pulled by the analyst and inspected.

Type the following in case /sdcard/ is not the right path on your particular device:

adb shell echo \$EXTERNAL_STORAGE

We can then open a shell and pull the file: $adb pull /sdcard/btsnoop_hci.log and inspect it with Wireshark, just like a PCAP collected by sniffing WiFi traffic for example, so it is very simple and well supported:

screenshot of wireshark capture using Android HCI Snoop

[source]

You can enable this by going to Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log."

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

After looking around a little longer I came across this. Apparently, there isn't a solution to this issue yet, but there is a workaround - going back to the legacy workflow.

The legacy workflow did work for me, and the only additional thing I had to do was to go to the platform-tools folder from android SDK download, open a command window here and run command "adb devices". This caused the computer RSA key fingerprint panel to pop on my mobile screen, and after granting permission, the device showed up under Chrome's Inspect page.

Turns out that it was not an issue caused by mobile OS upgrade but by Chrome (I was thrown off by the fact that it worked on my Nexus4 somehow). In the older versions of Chrome there was't a need to download the 500 odd mb Android SDK, as it supported an ADB plugin. But with latest version of Chrome, I guess, going legacy is the only way to go.

Start redis-server with config file

Okay, redis is pretty user friendly but there are some gotchas.

Here are just some easy commands for working with redis on Ubuntu:

install:

sudo apt-get install redis-server

start with conf:

sudo redis-server <path to conf>
sudo redis-server config/redis.conf

stop with conf:

redis-ctl shutdown

(not sure how this shuts down the pid specified in the conf. Redis must save the path to the pid somewhere on boot)

log:

tail -f /var/log/redis/redis-server.log

Also, various example confs floating around online and on this site were beyond useless. The best, sure fire way to get a compatible conf is to copy-paste the one your installation is already using. You should be able to find it here:

/etc/redis/redis.conf

Then paste it at <path to conf>, tweak as needed and you're good to go.

Return from lambda forEach() in java

This what helped me:

List<RepositoryFile> fileList = response.getRepositoryFileList();
RepositoryFile file1 = fileList.stream().filter(f -> f.getName().contains("my-file.txt")).findFirst().orElse(null);

Taken from Java 8 Finding Specific Element in List with Lambda

curl Failed to connect to localhost port 80

If anyone else comes across this and the accepted answer doesn't work (it didn't for me), check to see if you need to specify a port other than 80. In my case, I was running a rails server at localhost:3000 and was just using curl http://localhost, which was hitting port 80.

Changing the command to curl http://localhost:3000 is what worked in my case.

Vagrant error : Failed to mount folders in Linux guest

by now the mounting works on some machines (ubuntu) and some doesn't (centos 7) but installing the plugin solves it

vagrant plugin install vagrant-vbguest

without having to do anything else on top of that, just

vagrant reload

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

I hate answering my own question, but @Matt Bodily put me on the right track.

The @Html.Action method actually invokes a controller and renders the view, so that wouldn't work to create a snippet of HTML in my case, as this was causing a recursive function call resulting in a StackOverflowException. The @Url.Action(action, controller, { area = "abc" }) does indeed return the URL, but I finally discovered an overload of Html.ActionLink that provided a better solution for my case:

@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)

Note: , null is significant in this case, to match the right signature.

Documentation: @Html.ActionLink (LinkExtensions.ActionLink)

Documentation for this particular overload:

LinkExtensions.ActionLink(Controller, Action, Text, RouteArgs, HtmlAttributes)

It's been difficult to find documentation for these helpers. I tend to search for "Html.ActionLink" when I probably should have searched for "LinkExtensions.ActionLink", if that helps anyone in the future.

Still marking Matt's response as the answer.

Edit: Found yet another HTML helper to solve this:

@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

You have to play with JSFiddle loading option :

set it to "No wrap - in body" instead of "onload"

Working fiddle : http://jsfiddle.net/zQv9n/1/

How to use Monitor (DDMS) tool to debug application

As far as I know, currently (Android Studio 2.3) there is no way to do this.

As per Android Studio documentation:

"Note: Only one debugger can be connected to your device at a time."

When you attempt to connect Android Device Monitor it disconnects Android Studio's debug session and vice versa, when you attempt to connect Android Studio's debugger, it disconnects Android Device Monitor.

Fortunately the new version of Android Studio (3.0) will feature a Device File Explorer that will allow you to pull files from within Android Studio without the need to open the Android Device Monitor which should resolve the problem.

Sharing link on WhatsApp from mobile website (not application) for Android

Recently WhatsApp updated on its official website that we need to use this HTML tag in order to make it shareable to mobile sites:

_x000D_
_x000D_
<a href="whatsapp://send?text=Hello%20World!">Hello, world!</a>
_x000D_
_x000D_
_x000D_

You can replace text= to have your link or any text content

How to implement the Java comparable interface?

You need to:

  • Add implements Comparable<Animal> to the class declaration; and
  • Implement a int compareTo( Animal a ) method to perform the comparisons.

Like this:

public class Animal implements Comparable<Animal>{
    public String name;
    public int year_discovered; 
    public String population; 

    public Animal(String name, int year_discovered, String population){
        this.name = name;
        this.year_discovered = year_discovered;
        this.population = population;
    }

    public String toString(){
     String s = "Animal name: "+ name+"\nYear Discovered: "+year_discovered+"\nPopulation: "+population;
     return s;
    }

    @Override
    public int compareTo( final Animal o) {
        return Integer.compare(this.year_discovered, o.year_discovered);
    }
}

Why is "except: pass" a bad programming practice?

All comments brought up so far are valid. Where possible you need to specify what exactly exception you want to ignore. Where possible you need to analyze what caused exception, and only ignore what you meant to ignore, and not the rest. If exception causes application to "crash spectacularly", then be it, because it's much more important to know the unexpected happened when it happened, than concealing that the problem ever occurred.

With all that said, do not take any programming practice as a paramount. This is stupid. There always is the time and place to do ignore-all-exceptions block.

Another example of idiotic paramount is usage of goto operator. When I was in school, our professor taught us goto operator just to mention that thou shalt not use it, EVER. Don't believe people telling you that xyz should never be used and there cannot be a scenario when it is useful. There always is.

Install mysql-python (Windows)

try running the following command:

pip install mysqlclient

Get SSID when WIFI is connected

Android 9 SSID showing NULL values use this code..

ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (networkInfo.isConnected()) {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            wifiInfo.getSSID();
            String name = networkInfo.getExtraInfo();
            String ssid = wifiInfo.getSSID();
            return ssid.replaceAll("^\"|\"$", "");
        }

How does an SSL certificate chain bundle work?

You need to use the openssl pkcs12 -export -chain -in server.crt -CAfile ...

See https://www.openssl.org/docs/apps/pkcs12.html

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

I know this is an old question, but I had the same problem and solved it thanks to this answer.

I use Putty regularly and have never had any problems. I use and have always used public key authentication. Today I could not connect again to my server, without changing any settings.

Then I saw the answer and remembered that I inadvertently ran chmod 777 . in my user's home directory. I connected from somewhere else and simply ran chmod 755 ~. Everything was back to normal instantly, I didn't even have to restart sshd.

I hope I saved some time from someone

nodejs mysql Error: Connection lost The server closed the connection

I do not recall my original use case for this mechanism. Nowadays, I cannot think of any valid use case.

Your client should be able to detect when the connection is lost and allow you to re-create the connection. If it important that part of program logic is executed using the same connection, then use transactions.

tl;dr; Do not use this method.


A pragmatic solution is to force MySQL to keep the connection alive:

setInterval(function () {
    db.query('SELECT 1');
}, 5000);

I prefer this solution to connection pool and handling disconnect because it does not require to structure your code in a way thats aware of connection presence. Making a query every 5 seconds ensures that the connection will remain alive and PROTOCOL_CONNECTION_LOST does not occur.

Furthermore, this method ensures that you are keeping the same connection alive, as opposed to re-connecting. This is important. Consider what would happen if your script relied on LAST_INSERT_ID() and mysql connection have been reset without you being aware about it?

However, this only ensures that connection time out (wait_timeout and interactive_timeout) does not occur. It will fail, as expected, in all others scenarios. Therefore, make sure to handle other errors.

Python: import module from another directory at the same level in project hierarchy

In the "root" __init__.py you can also do a

import sys
sys.path.insert(1, '.')

which should make both modules importable.

Java String to JSON conversion

Converting the String to JsonNode using ObjectMapper object :

ObjectMapper mapper = new ObjectMapper();

// For text string
JsonNode = mapper.readValue(mapper.writeValueAsString("Text-string"), JsonNode.class)

// For Array String
JsonNode = mapper.readValue("[\"Text-Array\"]"), JsonNode.class)

// For Json String 
String json = "{\"id\" : \"1\"}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser jsonParser = factory.createParser(json);
JsonNode node = mapper.readTree(jsonParser);

OWIN Startup Class Missing

I had this problem, understand this isn't what was wrong in the OP's case, but in my case I did have a Startup class, it just wasn't finding it by default.

My problem was the I had spaces in my Assembly Name, and hence the default namespace was different from assembly name, hence the namespace for the startup class was different than the assembly name.

As the error suggests, by convention it looks for [Assembly Name].Startup for the class... so be sure the namespace for your Startup class is the same as the Assembly name. Fixed the problem for me.

jQuery looping .each() JSON key/value not working

Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()

$.each(json, function (key, data) {
    console.log(key)
    $.each(data, function (index, data) {
        console.log('index', data)
    })
})

Demo: Fiddle

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I was having the same issue, but with Glide. When I was going to disconnect from wifi and reconnect (just like it was suggested here), I noticed that I was in Airplane mode ???

Warning :-Presenting view controllers on detached view controllers is discouraged

Wait for viewDidAppear():

This error can also arise if you are trying to present view controller before view actually did appear, for example presenting view in viewWillAppear() or earlier. Try to present another view after viewDidAppear() or inside of it.

SOAP vs REST (differences)

A lot of these answers entirely forgot to mention hypermedia controls (HATEOAS) which is completely fundamental to REST. A few others touched on it, but didn't really explain it so well.

This article should explain the difference between the concepts, without getting into the weeds on specific SOAP features.

Excel VBA Run-time Error '32809' - Trying to Understand it

I've been struggling with this for awhile too. It actually occurred due to some Microsoft Office updates via Windows Update starting in December. It has caused quite a bit of a headache, not to mention hours of lost productivity due to this issue.

One of the updates breaks the forms, and you need to clear the Office cache as stated by UHsoccer

Additionally, another answer thread here: Suddenly several VBA macro errors, mostly 32809 has a link to the MS blog with details.

Another of the updates causes another error where if you create or modify one of these forms (even as simple as saving the form data) it will update the internals of the spreadsheet, which, when given to another person without the updates, will cause the error above.

The solution (if you are working with others on the same spreadsheet)? Sadly, either have everyone you deal with use the office updates, then have them clear the office cache, or revert back to pre Dec '14 updates via a system restore (or by manually removing them).

I know, not much of a solution, right? I'm not happy either.

Just as a back-story, I updated my machine, keeping up with updates, and one of the companies I dealt with did not. I was pulling out my hair just before Christmas trying to figure out the issue, and without any restore points, I finally relented and reformatted.

Now, a month later, the company's IT department updated their workstations. And, without surprise, they began having issues similar to this as well (not to mention when I received their spreadsheets, I had the same issue).

Now, we are all up on the same updates, and everything is well as can be.

css display table cell requires percentage width

Note also that vertical-align:top; is often necessary for correct table cell appearance.

css table-cell, contents have unnecessary top margin

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

This post is high up when you google that error message, which I got when installing security patch KB4505224 on SQL Server 2017 Express i.e. None of the above worked for me, but did consume several hours trying.

The solution for me, partly from here was:

  1. uninstall SQL Server
  2. in Regional Settings / Management / System Locale, "Beta: UTF-8 support" should be OFF
  3. re-install SQL Server
  4. Let Windows install the patch.

And all was well.

More on this here.

Keytool is not recognized as an internal or external command

You are getting that error because the keytool executable is under the bin directory, not the lib directory in your example. And you will need to add the location of your keystore as well in the command line. There is a pretty good reference to all of this here - Jrun Help / Import certificates | Certificate stores | ColdFusion

The default truststore is the JRE's cacerts file. This file is typically located in the following places:

  • Server Configuration:

    cf_root/runtime/jre/lib/security/cacerts

  • Multiserver/J2EE on JRun 4 Configuration:

    jrun_root/jre/lib/security/cacerts

  • Sun JDK installation:

    jdk_root/jre/lib/security/cacerts

  • Consult documentation for other J2EE application servers and JVMs


The keytool is part of the Java SDK and can be found in the following places:

  • Server Configuration:

    cf_root/runtime/bin/keytool

  • Multiserver/J2EE on JRun 4 Configuration:

    jrun_root/jre/bin/keytool

  • Sun JDK installation:

    jdk_root/bin/keytool

  • Consult documentation for other J2EE application servers and JVMs

So if you navigate to the directory where the keytool executable is located your command line would look something like this:

keytool -list -v -keystore JAVA_HOME\jre\lib\security\cacert -storepass changeit

You will need to supply pathing information depending on where you run the keytool command from and where your certificate file resides.

Also, be sure you are updating the correct cacerts file that ColdFusion is using. In case you have more than one JRE installed on that server. You can verify the JRE ColdFusion is using from the administrator under the 'System Information'. Look for the Java Home line.

With ng-bind-html-unsafe removed, how do I inject HTML?

Strict Contextual Escaping can be disabled entirely, allowing you to inject html using ng-html-bind. This is an unsafe option, but helpful when testing.

Example from the AngularJS documentation on $sce:

angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  // Completely disable SCE.  For demonstration purposes only!
  // Do not use in new projects.
  $sceProvider.enabled(false);
});

Attaching the above config section to your app will allow you inject html into ng-html-bind, but as the doc remarks:

SCE gives you a lot of security benefits for little coding overhead. It will be much harder to take an SCE disabled application and either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE for cases where you have a lot of existing code that was written before SCE was introduced and you're migrating them a module at a time.

Can I use VARCHAR as the PRIMARY KEY?

It depends on the specific use case.

If your table is static and only has a short list of values (and there is just a small chance that this would change during a lifetime of DB), I would recommend this construction:

CREATE TABLE Foo 
(
    FooCode VARCHAR(16), -- short code or shortcut, but with some meaning.
    Name NVARCHAR(128), -- full name of entity, can be used as fallback in case when your localization for some language doesn't exist
    LocalizationCode AS ('Foo.' + FooCode) -- This could be a code for your localization table...&nbsp;
)

Of course, when your table is not static at all, using INT as primary key is the best solution.

How to query for Xml values and attributes from table in SQL Server?

use value instead of query (must specify index of node to return in the XQuery as well as passing the sql data type to return as the second parameter):

select
    xt.Id
    , x.m.value( '@id[1]', 'varchar(max)' ) MetricId
from
    XmlTest xt
    cross apply xt.XmlData.nodes( '/Sqm/Metrics/Metric' ) x(m)

Reading JSON POST using PHP

You have empty $_POST. If your web-server wants see data in json-format you need to read the raw input and then parse it with JSON decode.

You need something like that:

$json = file_get_contents('php://input');
$obj = json_decode($json);

Also you have wrong code for testing JSON-communication...

CURLOPT_POSTFIELDS tells curl to encode your parameters as application/x-www-form-urlencoded. You need JSON-string here.

UPDATE

Your php code for test page should be like that:

$data_string = json_encode($data);

$ch = curl_init('http://webservice.local/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);

Also on your web-service page you should remove one of the lines header('Content-type: application/json');. It must be called only once.

What is the iBeacon Bluetooth Profile

It’s very simple, it just advertises a string which contains a few characters conforming to Apple’s iBeacon standard. you can refer the Link http://glimwormbeacons.com/learn/what-makes-an-ibeacon-an-ibeacon/

Transfer data between iOS and Android via Bluetooth?

Maybe a bit delayed, but technologies have evolved since so there is certainly new info around which draws fresh light on the matter...

As iOS has yet to open up an API for WiFi Direct and Multipeer Connectivity is iOS only, I believe the best way to approach this is to use BLE, which is supported by both platforms (some better than others).

On iOS a device can act both as a BLE Central and BLE Peripheral at the same time, on Android the situation is more complex as not all devices support the BLE Peripheral state. Also the Android BLE stack is very unstable (to date).

If your use case is feature driven, I would suggest to look at Frameworks and Libraries that can achieve cross platform communication for you, without you needing to build it up from scratch.

For example: http://p2pkit.io or google nearby

Disclaimer: I work for Uepaa, developing p2pkit.io for Android and iOS.

IntelliJ does not show 'Class' when we right click and select 'New'

Most of the people already gave the answer but this one is just for making someone's life easier.

TL;DR

Screenshot of how to add test sources

You must add the test folder as source.

  1. Right click on java directory under test
  2. Mark it as Tests
  3. Add src/test/java in Test Source Folders

Thats it, IntelliJ will consider them as test source.

Build an iOS app without owning a mac?

Also if you want to save some money you don't must buy a Mac. There is other ways how to do it:

1.) You can use practically any OS to run latest MacOS in virtual machine (look at YouTube). I am using this method really long time without any problems on windows with VMWare.

2.) Hackintosh. Install MacOS to your PC. You must have compatible components, but if you have, this is the best way, because you eliminate the lags in VM... I am using this in this time. Perfect. On my laptop, but please don't tell this to Apple, because practically this is illegal

3.) If you are making simple apps with minimum UI, you can use Theos. Also with Theos you can create cydia tweaks. Only one problem: codesign. If you want to publish app on App Store you still must have MacOS, but if you want to make app in home you can use CydiaImpactor to sign the apps with Apple ID.

I used all of this ways and all is working. By my VM is best solution if you don't want to spend lot of time by installing Hackintosh.

IOException: read failed, socket might closed - Bluetooth on Android 4.3

I've had this problem and the solution was to use the special magic GUID.

            val id: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB") // Any other GUID doesn't work.
            val device: BluetoothDevice = bta!!.bondedDevices.first { z -> z.name == deviceName }

            bts = device.createRfcommSocketToServiceRecord(id) // mPort is -1
            bts?.connect()
            // Start processing thread.

I suspect that these are the UUIDs that work:

var did: Array<ParcelUuid?> = device.uuids

However, I have not tried them all.

Map vs Object in JavaScript

I don't think the following points have been mentioned in the answers so far, and I thought they'd be worth mentioning.


Maps can be bigger

In chrome I can get 16.7 million key/value pairs with Map vs. 11.1 million with a regular object. Almost exactly 50% more pairs with a Map. They both take up about 2GB of memory before they crash, and so I think may be to do with memory limiting by chrome (Edit: Yep, try filling 2 Maps and you only get to 8.3 million pairs each before it crashes). You can test it yourself with this code (run them separately and not at the same time, obviously):

var m = new Map();
var i = 0;
while(1) {
    m.set(((10**30)*Math.random()).toString(36), ((10**30)*Math.random()).toString(36));
    i++;
    if(i%1000 === 0) { console.log(i/1000,"thousand") }
}
// versus:
var m = {};
var i = 0;
while(1) {
    m[((10**30)*Math.random()).toString(36)] = ((10**30)*Math.random()).toString(36);
    i++;
    if(i%1000 === 0) { console.log(i/1000,"thousand") }
}

Objects have some properties/keys already

This one has tripped me up before. Regular objects have toString, constructor, valueOf, hasOwnProperty, isPrototypeOf and a bunch of other pre-existing properties. This may not be a big problem for most use cases, but it has caused problems for me before.

Maps can be slower:

Due to the .get function call overhead and lack of internal optimisation, Map can be considerably slower than a plain old JavaScript object for some tasks.

Run ssh and immediately execute command

You can use the LocalCommand command-line option if the PermitLocalCommand option is enabled:

ssh username@hostname -o LocalCommand="tmux list-sessions"

For more details about the available options, see the ssh_config man page.

How to hide the bar at the top of "youtube" even when mouse hovers over it?

The answer to this question in 2020 is IT DOESN'T WORK AT ALL NOW.

Update query with PDO and MySQL

This has nothing to do with using PDO, it's just that you are confusing INSERT and UPDATE.

Here's the difference:

  • INSERT creates a new row. I'm guessing that you really want to create a new row.
  • UPDATE changes the values in an existing row, but if this is what you're doing you probably should use a WHERE clause to restrict the change to a specific row, because the default is that it applies to every row.

So this will probably do what you want:

$sql = "INSERT INTO `access_users`   
  (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`) 
  VALUES (:firstname, :surname, :email, :telephone);
  ";

Note that I've also changed the order of columns; the order of your columns must match the order of values in your VALUES clause.

MySQL also supports an alternative syntax for INSERT:

$sql = "INSERT INTO `access_users`   
  SET `contact_first_name` = :firstname,
    `contact_surname` = :surname,
    `contact_email` = :email,
    `telephone` = :telephone
  ";

This alternative syntax looks a bit more like an UPDATE statement, but it creates a new row like INSERT. The advantage is that it's easier to match up the columns to the correct parameters.

How to scale Docker containers in production

Have a look at Rancher.com - it can manage multiple Docker hosts and much more.

PDO closing connection

According to documentation you're correct (http://php.net/manual/en/pdo.connections.php):

The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

Note that if you initialise the PDO object as a persistent connection it will not automatically close the connection.

ImportError: No module named apiclient.discovery

This can also happen if the interpreter on your IDE is pointing to the wrong virtual environment. In VSCODE I've set it manually to the correct interpreter and my problem was solved.

Node.js: socket.io close client connection

Just try socket.disconnect(true) on the server side by emitting any event from the client side.

Options for embedding Chromium instead of IE WebBrowser control with WPF/C#

Here is another one:

http://www.essentialobjects.com/Products/WebBrowser/Default.aspx

This one is also based on the latest Chrome engine but it's much easier to use than CEF. It's a single .NET dll that you can simply reference and use.

How to add a "sleep" or "wait" to my Lua Script?

if you're using a MacBook or UNIX based system, use this:

function wait(time)
if tonumber(time) ~= nil then
os.execute("Sleep "..tonumber(time))
else
os.execute("Sleep "..tonumber("0.1"))
end
wait()

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

Use curly braces to initialize a Set in Python

Compare also the difference between {} and set() with a single word argument.

>>> a = set('aardvark')
>>> a
{'d', 'v', 'a', 'r', 'k'} 
>>> b = {'aardvark'}
>>> b
{'aardvark'}

but both a and b are sets of course.

Excel VBA Automation Error: The object invoked has disconnected from its clients

The error in the below line of code (as mentioned by the requestor-William) is due to the following reason:

fromBook.Sheets("Report").Copy Before:=newBook.Sheets("Sheet1")

The destination sheet you are trying to copy to is closed. (Here newbook.Sheets("Sheet1")). Add the below statement just before copying to destination.

Application.Workbooks.Open ("YOUR SHEET NAME")

This will solve the problem!!

Socket.IO handling disconnect event

Create a Map or a Set, and using "on connection" event set to it each connected socket, in reverse "once disconnect" event delete that socket from the Map we created earlier

import * as Server from 'socket.io';

const io = Server();
io.listen(3000);

const connections = new Set();

io.on('connection', function (s) {

  connections.add(s);

  s.once('disconnect', function () {
    connections.delete(s);
  });

});

Relative URLs in WordPress

There is an easy way

Instead of /pagename/ use index.php/pagename/ or if you don't use permalinks do the following :

Post

index.php?p=123

Page

index.php?page_id=42

Category

index.php?cat=7

More information here : http://codex.wordpress.org/Linking_Posts_Pages_and_Categories

Git merge master into feature branch

You might be able to do a "cherry-pick" to pull the exact commit(s) that you need in to your feature branch.

Do a git checkout hotfix1 to get on the hotfix1 branch. Then do a git log to get the SHA-1 hash (big sequence of random letters and numbers that uniquely identifies a commit) of the commit in question. Copy that (or the first 10 or so characters).

Then, git checkout feature1 to get back onto your feature branch.

Then, git cherry-pick <the SHA-1 hash that you just copied>

That will pull that commit, and only that commit, into your feature branch. That change will be in the branch - you just "cherry-picked" it in. Then, resume work, edit, commit, push, etc. to your heart's content.

When, eventually, you perform another merge from one branch into your feature branch (or vice-versa), Git will recognize that you've already merged in that particular commit, know that it doesn't have to make it again, and just "skip over" it.

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

The problem is you are not in the correct directory. A simple fix in Jupyter is to do the following command:

  1. Move to the GitHub directory for your installation
  2. Run the GitHub command

Here is an example command to use in Jupyter:

%%bash
cd /home/ec2-user/ml_volume/GitHub_BMM
git show

Note you need to do the commands in the same cell.

C# : Converting Base Class to Child Class

In OOP, you can't cast an instance of a parent class into a child class. You can only cast a child instance into a parent that it inherits from.

Get connection status on Socket.io client

Track the state of the connection yourself. With a boolean. Set it to false at declaration. Use the various events (connect, disconnect, reconnect, etc.) to reassign the current boolean value. Note: Using undocumented API features (e.g., socket.connected), is not a good idea; the feature could get removed in a subsequent version without the removal being mentioned.

postgres, ubuntu how to restart service on startup? get stuck on clustering after instance reboot

ENABLE is what you are looking for

USAGE: type this command once and then you are good to go. Your service will start automaticaly at boot up

 sudo systemctl enable postgresql

DISABLE exists as well ofc

Some DOC: freedesktop man systemctl

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

Apparently, document.addEventListener() is unreliable, and hence, my error. Use window.addEventListener() with the same parameters, instead.

How to ftp with a batch file?

Use

ftp -s:FileName 

as decribed in Windows XP Professional Product Documentation.

The file name that you have to specify in place of FileName must contain FTP commands that you want to send to the server. Among theses commands are

  • open Computer [Port] to connect to an FTP server,
  • user UserName [Password] [Account] to authenticate with the FTP server,
  • get RemoteFile [LocalFile] to retrieve a file,
  • quit to end the FTP session and terminate the ftp program.

More commands can be found under Ftp subcommands.

JavaScript math, round to two decimal places

Here is a working example

var value=200.2365455;
result=Math.round(value*100)/100    //result will be 200.24

Getting java.net.SocketTimeoutException: Connection timed out in android

I was facing this problem and the solution was to restart my modem (router). I could get connection for my app to internet after that.

I think the library I am using is not managing connections properly because it happeend just few times.

Include CSS and Javascript in my django template

First, create staticfiles folder. Inside that folder create css, js, and img folder.

settings.py

import os

PROJECT_DIR = os.path.dirname(__file__)

DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.sqlite3', 
         'NAME': os.path.join(PROJECT_DIR, 'myweblabdev.sqlite'),                        
         'USER': '',
         'PASSWORD': '',
         'HOST': '',                      
         'PORT': '',                     
    }
}

MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')

MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR, 'staticfiles'),
)

main urls.py

from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from myweblab import settings

admin.autodiscover()

urlpatterns = patterns('',
    .......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += staticfiles_urlpatterns()

template

{% load static %}

<link rel="stylesheet" href="{% static 'css/style.css' %}">

Advantages of using display:inline-block vs float:left in CSS

While I agree that in general inline-block is better, there's one extra thing to take into account if you're using percentage widths to create a responsive grid (or if you want pixel-perfect widths):

If you're using inline-block for grids that total 100% or near to 100% width, you need to make sure your HTML markup contains no white space between columns.

With floats, this is not something you need to worry about - the columns float over any whitespace or other content between columns. This question's answers have some good tips on ways to remove HTML whitespace without making your code ugly.

If for any reason you can't control the HTML markup (e.g. a restrictive CMS), you can try the tricks described here, or you might need to compromise and use floats instead of inline-block. There are also ugly CSS tricks that should only be used in extreme circumstances, like font-size:0; on the column container then reapply font size within each column.

For example:

SFTP file transfer using Java JSch

The most trivial way to upload a file over SFTP with JSch is:

JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();

ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();

sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");

Similarly for a download:

sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");

You may need to deal with UnknownHostKey exception.

How do I tokenize a string sentence in NLTK?

This is actually on the main page of nltk.org:

>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

Rebase feature branch onto another feature branch

I know you asked to Rebase, but I'd Cherry-Pick the commits I wanted to move from Branch2 to Branch1 instead. That way, I wouldn't need to care about when which branch was created from master, and I'd have more control over the merging.

a -- b -- c                  <-- Master
     \     \
      \     d -- e -- f -- g <-- Branch1 (Cherry-Pick f & g)
       \
        f -- g               <-- Branch2

npm global path prefix

If you have linked the node packages using sudo command

Then go to the folder where node_modules are installed globally.

On Unix systems they are normally placed in /usr/local/lib/node or /usr/local/lib/node_modules when installed globally. If you set the NODE_PATH environment variable to this path, the modules can be found by node.

Windows XP - %USERPROFILE%\Application Data\npm\node_modules Windows 7 - %AppData%\npm\node_modules

and then run the command

ls -l

This will give the list of all global node_modules and you can easily see the linked node modules.

Can't access Eclipse marketplace

Go to the folder where eclipse is installed

open eclipse.ini file
look for the line -vmargs
put -Djava.net.preferIPv4Stack=true below the -vmargs line and restart eclipse

How to get the last N rows of a pandas DataFrame?

This is because of using integer indices (ix selects those by label over -3 rather than position, and this is by design: see integer indexing in pandas "gotchas"*).

*In newer versions of pandas prefer loc or iloc to remove the ambiguity of ix as position or label:

df.iloc[-3:]

see the docs.

As Wes points out, in this specific case you should just use tail!

How to drop a list of rows from Pandas dataframe?

Look at the following dataframe df

df

   column1  column2  column3
0        1       11       21
1        2       12       22
2        3       13       23
3        4       14       24
4        5       15       25
5        6       16       26
6        7       17       27
7        8       18       28
8        9       19       29
9       10       20       30

Lets drop all the rows which has an odd number in column1

Create a list of all the elements in column1 and keep only those elements that are even numbers (the elements that you dont want to drop)

keep_elements = [x for x in df.column1 if x%2==0]

All the rows with the values [2, 4, 6, 8, 10] in its column1 will be retained or not dropped.

df.set_index('column1',inplace = True)
df.drop(df.index.difference(keep_elements),axis=0,inplace=True)
df.reset_index(inplace=True)

We make the column1 as index and drop all the rows that are not required. Then we reset the index back. df

   column1  column2  column3
0        2       12       22
1        4       14       24
2        6       16       26
3        8       18       28
4       10       20       30

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

You are debugging two or more times. so the application may run more at a time. Then only this issue will occur. You should close all debugging applications using task-manager, Then debug again.

How to create websockets server in PHP

I was in the same boat as you recently, and here is what I did:

  1. I used the phpwebsockets code as a reference for how to structure the server-side code. (You seem to already be doing this, and as you noted, the code doesn't actually work for a variety of reasons.)

  2. I used PHP.net to read the details about every socket function used in the phpwebsockets code. By doing this, I was finally able to understand how the whole system works conceptually. This was a pretty big hurdle.

  3. I read the actual WebSocket draft. I had to read this thing a bunch of times before it finally started to sink in. You will likely have to go back to this document again and again throughout the process, as it is the one definitive resource with correct, up-to-date information about the WebSocket API.

  4. I coded the proper handshake procedure based on the instructions in the draft in #3. This wasn't too bad.

  5. I kept getting a bunch of garbled text sent from the clients to the server after the handshake and I couldn't figure out why until I realized that the data is encoded and must be unmasked. The following link helped me a lot here: (original link broken) Archived copy.

    Please note that the code available at this link has a number of problems and won't work properly without further modification.

  6. I then came across the following SO thread, which clearly explains how to properly encode and decode messages being sent back and forth: How can I send and receive WebSocket messages on the server side?

    This link was really helpful. I recommend consulting it while looking at the WebSocket draft. It'll help make more sense out of what the draft is saying.

  7. I was almost done at this point, but had some issues with a WebRTC app I was making using WebSocket, so I ended up asking my own question on SO, which I eventually solved: What is this data at the end of WebRTC candidate info?

  8. At this point, I pretty much had it all working. I just had to add some additional logic for handling the closing of connections, and I was done.

That process took me about two weeks total. The good news is that I understand WebSocket really well now and I was able to make my own client and server scripts from scratch that work great. Hopefully the culmination of all that information will give you enough guidance and information to code your own WebSocket PHP script.

Good luck!


Edit: This edit is a couple of years after my original answer, and while I do still have a working solution, it's not really ready for sharing. Luckily, someone else on GitHub has almost identical code to mine (but much cleaner), so I recommend using the following code for a working PHP WebSocket solution:
https://github.com/ghedipunk/PHP-Websockets/blob/master/websockets.php


Edit #2: While I still enjoy using PHP for a lot of server-side related things, I have to admit that I've really warmed up to Node.js a lot recently, and the main reason is because it's better designed from the ground up to handle WebSocket than PHP (or any other server-side language). As such, I've found recently that it's a lot easier to set up both Apache/PHP and Node.js on your server and use Node.js for running the WebSocket server and Apache/PHP for everything else. And in the case where you're on a shared hosting environment in which you can't install/use Node.js for WebSocket, you can use a free service like Heroku to set up a Node.js WebSocket server and make cross-domain requests to it from your server. Just make sure if you do that to set your WebSocket server up to be able to handle cross-origin requests.

jQuery 1.9 .live() is not a function

.live() was deprecated and has now been removed from jQuery 1.9 You should use .on()

Android + Pair devices via bluetooth programmatically

if you have the BluetoothDevice object you can create bond(pair) from api 19 onwards with bluetoothDevice.createBond() method.

Edit

for callback, if the request was accepted or denied you will have to create a BroadcastReceiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED action

Tool to compare directories (Windows 7)

The tool that richardtz suggests is excellent.

Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.

You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

I was looking for a solution to this problem myself with no luck, so I had to roll my own which I would like to share here with you. (Please excuse my bad English) (It's a little crazy to answer another Czech guy in English :-) )

The first thing I tried was to use a good old PopupWindow. It's quite easy - one only has to listen to the OnMarkerClickListener and then show a custom PopupWindow above the marker. Some other guys here on StackOverflow suggested this solution and it actually looks quite good at first glance. But the problem with this solution shows up when you start to move the map around. You have to move the PopupWindow somehow yourself which is possible (by listening to some onTouch events) but IMHO you can't make it look good enough, especially on some slow devices. If you do it the simple way it "jumps" around from one spot to another. You could also use some animations to polish those jumps but this way the PopupWindow will always be "a step behind" where it should be on the map which I just don't like.

At this point, I was thinking about some other solution. I realized that I actually don't really need that much freedom - to show my custom views with all the possibilities that come with it (like animated progress bars etc.). I think there is a good reason why even the google engineers don't do it this way in the Google Maps app. All I need is a button or two on the InfoWindow that will show a pressed state and trigger some actions when clicked. So I came up with another solution which splits up into two parts:

First part:
The first part is to be able to catch the clicks on the buttons to trigger some action. My idea is as follows:

  1. Keep a reference to the custom infoWindow created in the InfoWindowAdapter.
  2. Wrap the MapFragment (or MapView) inside a custom ViewGroup (mine is called MapWrapperLayout)
  3. Override the MapWrapperLayout's dispatchTouchEvent and (if the InfoWindow is currently shown) first route the MotionEvents to the previously created InfoWindow. If it doesn't consume the MotionEvents (like because you didn't click on any clickable area inside InfoWindow etc.) then (and only then) let the events go down to the MapWrapperLayout's superclass so it will eventually be delivered to the map.

Here is the MapWrapperLayout's source code:

package com.circlegate.tt.cg.an.lib.map;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.Marker;

import android.content.Context;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

public class MapWrapperLayout extends RelativeLayout {
    /**
     * Reference to a GoogleMap object 
     */
    private GoogleMap map;

    /**
     * Vertical offset in pixels between the bottom edge of our InfoWindow 
     * and the marker position (by default it's bottom edge too).
     * It's a good idea to use custom markers and also the InfoWindow frame, 
     * because we probably can't rely on the sizes of the default marker and frame. 
     */
    private int bottomOffsetPixels;

    /**
     * A currently selected marker 
     */
    private Marker marker;

    /**
     * Our custom view which is returned from either the InfoWindowAdapter.getInfoContents 
     * or InfoWindowAdapter.getInfoWindow
     */
    private View infoWindow;    

    public MapWrapperLayout(Context context) {
        super(context);
    }

    public MapWrapperLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MapWrapperLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * Must be called before we can route the touch events
     */
    public void init(GoogleMap map, int bottomOffsetPixels) {
        this.map = map;
        this.bottomOffsetPixels = bottomOffsetPixels;
    }

    /**
     * Best to be called from either the InfoWindowAdapter.getInfoContents 
     * or InfoWindowAdapter.getInfoWindow. 
     */
    public void setMarkerWithInfoWindow(Marker marker, View infoWindow) {
        this.marker = marker;
        this.infoWindow = infoWindow;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        boolean ret = false;
        // Make sure that the infoWindow is shown and we have all the needed references
        if (marker != null && marker.isInfoWindowShown() && map != null && infoWindow != null) {
            // Get a marker position on the screen
            Point point = map.getProjection().toScreenLocation(marker.getPosition());

            // Make a copy of the MotionEvent and adjust it's location
            // so it is relative to the infoWindow left top corner
            MotionEvent copyEv = MotionEvent.obtain(ev);
            copyEv.offsetLocation(
                -point.x + (infoWindow.getWidth() / 2), 
                -point.y + infoWindow.getHeight() + bottomOffsetPixels);

            // Dispatch the adjusted MotionEvent to the infoWindow
            ret = infoWindow.dispatchTouchEvent(copyEv);
        }
        // If the infoWindow consumed the touch event, then just return true.
        // Otherwise pass this event to the super class and return it's result
        return ret || super.dispatchTouchEvent(ev);
    }
}

All this will make the views inside the InfoView "live" again - the OnClickListeners will start triggering etc.

Second part: The remaining problem is, that obviously, you can't see any UI changes of your InfoWindow on screen. To do that you have to manually call Marker.showInfoWindow. Now, if you perform some permanent change in your InfoWindow (like changing the label of your button to something else), this is good enough.

But showing a button pressed state or something of that nature is more complicated. The first problem is, that (at least) I wasn't able to make the InfoWindow show normal button's pressed state. Even if I pressed the button for a long time, it just remained unpressed on the screen. I believe this is something that is handled by the map framework itself which probably makes sure not to show any transient state in the info windows. But I could be wrong, I didn't try to find this out.

What I did is another nasty hack - I attached an OnTouchListener to the button and manually switched it's background when the button was pressed or released to two custom drawables - one with a button in a normal state and the other one in a pressed state. This is not very nice, but it works :). Now I was able to see the button switching between normal to pressed states on the screen.

There is still one last glitch - if you click the button too fast, it doesn't show the pressed state - it just remains in its normal state (although the click itself is fired so the button "works"). At least this is how it shows up on my Galaxy Nexus. So the last thing I did is that I delayed the button in it's pressed state a little. This is also quite ugly and I'm not sure how would it work on some older, slow devices but I suspect that even the map framework itself does something like this. You can try it yourself - when you click the whole InfoWindow, it remains in a pressed state a little longer, then normal buttons do (again - at least on my phone). And this is actually how it works even on the original Google Maps app.

Anyway, I wrote myself a custom class which handles the buttons state changes and all the other things I mentioned, so here is the code:

package com.circlegate.tt.cg.an.lib.map;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

import com.google.android.gms.maps.model.Marker;

public abstract class OnInfoWindowElemTouchListener implements OnTouchListener {
    private final View view;
    private final Drawable bgDrawableNormal;
    private final Drawable bgDrawablePressed;
    private final Handler handler = new Handler();

    private Marker marker;
    private boolean pressed = false;

    public OnInfoWindowElemTouchListener(View view, Drawable bgDrawableNormal, Drawable bgDrawablePressed) {
        this.view = view;
        this.bgDrawableNormal = bgDrawableNormal;
        this.bgDrawablePressed = bgDrawablePressed;
    }

    public void setMarker(Marker marker) {
        this.marker = marker;
    }

    @Override
    public boolean onTouch(View vv, MotionEvent event) {
        if (0 <= event.getX() && event.getX() <= view.getWidth() &&
            0 <= event.getY() && event.getY() <= view.getHeight())
        {
            switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN: startPress(); break;

            // We need to delay releasing of the view a little so it shows the pressed state on the screen
            case MotionEvent.ACTION_UP: handler.postDelayed(confirmClickRunnable, 150); break;

            case MotionEvent.ACTION_CANCEL: endPress(); break;
            default: break;
            }
        }
        else {
            // If the touch goes outside of the view's area
            // (like when moving finger out of the pressed button)
            // just release the press
            endPress();
        }
        return false;
    }

    private void startPress() {
        if (!pressed) {
            pressed = true;
            handler.removeCallbacks(confirmClickRunnable);
            view.setBackground(bgDrawablePressed);
            if (marker != null) 
                marker.showInfoWindow();
        }
    }

    private boolean endPress() {
        if (pressed) {
            this.pressed = false;
            handler.removeCallbacks(confirmClickRunnable);
            view.setBackground(bgDrawableNormal);
            if (marker != null) 
                marker.showInfoWindow();
            return true;
        }
        else
            return false;
    }

    private final Runnable confirmClickRunnable = new Runnable() {
        public void run() {
            if (endPress()) {
                onClickConfirmed(view, marker);
            }
        }
    };

    /**
     * This is called after a successful click 
     */
    protected abstract void onClickConfirmed(View v, Marker marker);
}

Here is a custom InfoWindow layout file that I used:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginRight="10dp" >

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:text="Title" />

        <TextView
            android:id="@+id/snippet"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="snippet" />

    </LinearLayout>

    <Button
        android:id="@+id/button" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

Test activity layout file (MapFragment being inside the MapWrapperLayout):

<com.circlegate.tt.cg.an.lib.map.MapWrapperLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map_relative_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />

</com.circlegate.tt.cg.an.lib.map.MapWrapperLayout>

And finally source code of a test activity, which glues all this together:

package com.circlegate.testapp;

import com.circlegate.tt.cg.an.lib.map.MapWrapperLayout;
import com.circlegate.tt.cg.an.lib.map.OnInfoWindowElemTouchListener;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {    
    private ViewGroup infoWindow;
    private TextView infoTitle;
    private TextView infoSnippet;
    private Button infoButton;
    private OnInfoWindowElemTouchListener infoButtonListener;

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

        final MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
        final MapWrapperLayout mapWrapperLayout = (MapWrapperLayout)findViewById(R.id.map_relative_layout);
        final GoogleMap map = mapFragment.getMap();

        // MapWrapperLayout initialization
        // 39 - default marker height
        // 20 - offset between the default InfoWindow bottom edge and it's content bottom edge 
        mapWrapperLayout.init(map, getPixelsFromDp(this, 39 + 20)); 

        // We want to reuse the info window for all the markers, 
        // so let's create only one class member instance
        this.infoWindow = (ViewGroup)getLayoutInflater().inflate(R.layout.info_window, null);
        this.infoTitle = (TextView)infoWindow.findViewById(R.id.title);
        this.infoSnippet = (TextView)infoWindow.findViewById(R.id.snippet);
        this.infoButton = (Button)infoWindow.findViewById(R.id.button);

        // Setting custom OnTouchListener which deals with the pressed state
        // so it shows up 
        this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton,
                getResources().getDrawable(R.drawable.btn_default_normal_holo_light),
                getResources().getDrawable(R.drawable.btn_default_pressed_holo_light)) 
        {
            @Override
            protected void onClickConfirmed(View v, Marker marker) {
                // Here we can perform some action triggered after clicking the button
                Toast.makeText(MainActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
            }
        }; 
        this.infoButton.setOnTouchListener(infoButtonListener);


        map.setInfoWindowAdapter(new InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker marker) {
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                // Setting up the infoWindow with current's marker info
                infoTitle.setText(marker.getTitle());
                infoSnippet.setText(marker.getSnippet());
                infoButtonListener.setMarker(marker);

                // We must call this to set the current marker and infoWindow references
                // to the MapWrapperLayout
                mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
                return infoWindow;
            }
        });

        // Let's add a couple of markers
        map.addMarker(new MarkerOptions()
            .title("Prague")
            .snippet("Czech Republic")
            .position(new LatLng(50.08, 14.43)));

        map.addMarker(new MarkerOptions()
            .title("Paris")
            .snippet("France")
            .position(new LatLng(48.86,2.33)));

        map.addMarker(new MarkerOptions()
            .title("London")
            .snippet("United Kingdom")
            .position(new LatLng(51.51,-0.1)));
    }

    public static int getPixelsFromDp(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(dp * scale + 0.5f);
    }
}

That's it. So far I only tested this on my Galaxy Nexus (4.2.1) and Nexus 7 (also 4.2.1), I will try it on some Gingerbread phone when I have a chance. A limitation I found so far is that you can't drag the map from where is your button on the screen and move the map around. It could probably be overcome somehow but for now, I can live with that.

I know this is an ugly hack but I just didn't find anything better and I need this design pattern so badly that this would really be a reason to go back to the map v1 framework (which btw. I would really really like to avoid for a new app with fragments etc.). I just don't understand why Google doesn't offer developers some official way to have a button on InfoWindows. It's such a common design pattern, moreover this pattern is used even in the official Google Maps app :). I understand the reasons why they can't just make your views "live" in the InfoWindows - this would probably kill performance when moving and scrolling map around. But there should be some way how to achieve this effect without using views.

Sending a JSON HTTP POST request from Android

try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

References :

  1. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  2. Java - sending HTTP parameters via POST method easily

CSS animation delay in repeating

Delay is possible only once at the beginning with infinite. in sort delay doesn't work with infinite loop. for that you have to keep keyframes animation blanks example:

@-webkit-keyframes barshine {
  10% {background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#1e5799), color-stop(100%,#7db9e8));
    }
  60% {background: -webkit-linear-gradient(top, #7db9e8 0%,#d32a2d 100%);}
}

it will animate 10% to 60% and wait to complete 40% more. So 40% comes in delay.

find fiddle example

Spring RestTemplate timeout

For Spring Boot >= 1.4

@Configuration
public class AppConfig
{
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) 
    {
        return restTemplateBuilder
           .setConnectTimeout(...)
           .setReadTimeout(...)
           .build();
    }
}

For Spring Boot <= 1.3

@Configuration
public class AppConfig
{
    @Bean
    @ConfigurationProperties(prefix = "custom.rest.connection")
    public HttpComponentsClientHttpRequestFactory customHttpRequestFactory() 
    {
        return new HttpComponentsClientHttpRequestFactory();
    }

    @Bean
    public RestTemplate customRestTemplate()
    {
        return new RestTemplate(customHttpRequestFactory());
    }
}

then in your application.properties

custom.rest.connection.connection-request-timeout=...
custom.rest.connection.connect-timeout=...
custom.rest.connection.read-timeout=...

This works because HttpComponentsClientHttpRequestFactory has public setters connectionRequestTimeout, connectTimeout, and readTimeout and @ConfigurationProperties sets them for you.


For Spring 4.1 or Spring 5 without Spring Boot using @Configuration instead of XML

@Configuration
public class AppConfig
{
    @Bean
    public RestTemplate customRestTemplate()
    {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(...);
        httpRequestFactory.setConnectTimeout(...);
        httpRequestFactory.setReadTimeout(...);

        return new RestTemplate(httpRequestFactory);
    }
}

Is there a php echo/print equivalent in javascript

We would create our own function in js like echo "Hello world".

function echo( ...s ) // rest operator
 { 
   for(var i = 0; i < s.length; i++ ) {

    document.write(s[i] + ' '); // quotes for space

   }

 } 

  // Now call to this function like echo

 echo('Hellow', "World");

Note: (...) rest operator dotes for access more parameters in one as object/array, to get value from object/array we should iterate the whole object/array by using for loop, like above and s is name i just kept you can write whatever you want.

ORACLE: Updating multiple columns at once

It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?

Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:

UPDATE INVOICE
   SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
     , INV_TOTAL    = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)     
WHERE INV_ID = I_INV_ID;

        

Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.

Why does visual studio 2012 not find my tests?

None of the solutions here helped me. The tests wouldn't be discovered for one solution whereas another solution referencing the same projects worked fine. I finally solved this by deleting the solutionname.v12.suo file.

Fixing slow initial load for IIS

I was getting a consistent 15 second delay on the first request after 4 minutes of inactivity. My problem was that my app was using Windows Integrated Authentication to SQL Server and the service profile was in a different domain than the server. This caused a cross-domain authentication from IIS to SQL upon app initialization - and this was the real source of my delay. I changed to using a SQL login instead of windows authentication. The delay was immediately gone. I still have all the app initialization settings in place to help improve performance but they may have not been needed at all in my case.

Chmod recursively

You can use chmod with the X mode letter (the capital X) to set the executable flag only for directories.

In the example below the executable flag is cleared and then set for all directories recursively:

~$ mkdir foo
~$ mkdir foo/bar
~$ mkdir foo/baz
~$ touch foo/x
~$ touch foo/y

~$ chmod -R go-X foo 
~$ ls -l foo
total 8
drwxrw-r-- 2 wq wq 4096 Nov 14 15:31 bar
drwxrw-r-- 2 wq wq 4096 Nov 14 15:31 baz
-rw-rw-r-- 1 wq wq    0 Nov 14 15:31 x
-rw-rw-r-- 1 wq wq    0 Nov 14 15:31 y

~$ chmod -R go+X foo 
~$ ls -l foo
total 8
drwxrwxr-x 2 wq wq 4096 Nov 14 15:31 bar
drwxrwxr-x 2 wq wq 4096 Nov 14 15:31 baz
-rw-rw-r-- 1 wq wq    0 Nov 14 15:31 x
-rw-rw-r-- 1 wq wq    0 Nov 14 15:31 y

A bit of explaination:

  • chmod -x foo - clear the eXecutable flag for foo
  • chmod +x foo - set the eXecutable flag for foo
  • chmod go+x foo - same as above, but set the flag only for Group and Other users, don't touch the User (owner) permission
  • chmod go+X foo - same as above, but apply only to directories, don't touch files
  • chmod -R go+X foo - same as above, but do this Recursively for all subdirectories of foo

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

Try this:

net use * /delete /y

The /y key makes it select Yes in prompt silently

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

I was facing this issue in a web application hosted on a shared hosting server. So obviously did not have direct access to IIS, so could not apply many solution proposed here.

On the hosting provider's control panel I enabled error logging for IIS and ASP.Net. And then got to know that error actually lied in a missing cshtml.

set serveroutput on in oracle procedure

If you want to execute any procedure then firstly you have to set serveroutput on in the sqldeveloper work environment like.

->  SET SERVEROUTPUT ON;
-> BEGIN
dbms_output.put_line ('Hello World..');
dbms_output.put_line('Its displaying the values only for the Testing purpose');
END;
/

Possible reason for NGINX 499 error codes

Turns out 499's really does mean "client interrupted connection."

I had a client "read timeout" setting of 60s (and nginx also has a default proxy_read_timeout of 60s). So what was happening in my case is that nginx would error.log an upstream timed out (110: Connection timed out) while reading upstream and then nginx retries "the next proxy server in the backend server group you configured." That's if you have more than one.

Then it tries the next and next till (by default) it has exhausted all of them. As each one times out, it removes them from the list of "live" backend servers, as well. After all are exhausted, it returns a 504 gateway timeout.

So in my case nginx marked the server as "unavailable", re-tried it on the next server, then my client's 60s timeout (immediately) occurred, so I'd see a upstream timed out (110: Connection timed out) while reading upstream log, immediately followed by a 499 log. But it was just timing coincidence.

Related:

If all servers in the group are marked as currently unavailable, then it returns a 502 Bad Gateway. for 10s as well. See here max_fails and fail_timeout. Inn the logs it will say no live upstreams while connecting to upstream.

If you only have one proxy backend in your server group, it just try's the one server, and returns a 504 Gateway Time-out and doesn't remove the single server from the list of "live" servers, if proxy_read_timeout is surpassed. See here "If there is only a single server in a group, max_fails, fail_timeout and slow_start parameters are ignored, and such a server will never be considered unavailable."

The really tricky part is that if you specify proxy_pass to "localhost" and your box happens to also have ipv6 and ipv4 "versions of location" on it at the same time (most boxes do by default), it will count as if you had a "list" of multiple servers in your server group, which means you can get into the situation above of having it return "502 for 10s" even though you list only one server. See here "If a domain name resolves to several addresses, all of them will be used in a round-robin fashion." One workaround is to declare it as proxy_pass http://127.0.0.1:5001; (its ipv4 address) to avoid it being both ipv6 and ipv4. Then it counts as "only a single server" behavior.

There's a few different settings you can tweak to make this "less" of a problem. Like increasing timeouts or making it so it doesn't mark servers as "disabled" when they timeout...or fixing the list so it's only size 1, see above :)

See also: https://serverfault.com/a/783624/27813

redistributable offline .NET Framework 3.5 installer for Windows 8

You don't have to copy everything to C:\dotnet35. Usually all the files are already copied to the folder C:\Windows\WinSxS. Then the command becomes (assuming Windows was installed to C:): "Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:C:\Windows\WinSxS /LimitAccess" If not you can also point the command to the DVD directly. Then the command becomes (assuming DVD is mounted to D:): "Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:D:\sources\sxs /LimitAccess".

Error TF30063: You are not authorized to access ... \DefaultCollection

After updating from TFS 2018 v3 to DevOps Server 2019.0.1 last weekend I now receive this authentication error when attempting to manage security:

TF30063: You are not authorized to access tfs.

I receive this error when attempting to manage security from the Server Administration Console via Application Tier > Administer Security. I also receive the error when I attempt to set permissions via tfssecurity cli tool. I am in the local administrator group and I am listed in the console administration user section.

I'm trying to set permissions because after the update I received several reports from employees that receive errors when they try to access their projects. Those errors are:

TF40049: You do not have licensing rights to access this feature: Code.

I spent 8 hrs working through this issue yesterday, and this is what fixed our problem:

  • deleted DevOps server cache. (location of cache listed in devops admin console on server)
  • reboot server.

I deleted the cache off the server based on an article I read with the same error, a user was having security/permissions issues with visual studio and they deleted the vs cache on their local machine and it solved their problem. I don't know if deleting the cache or the reboot would have fixed it independently because I did them both as a single troubleshooting step.

Hope this helps someone.

outline on only one border

Try with Shadow( Like border ) + Border

border-bottom: 5px solid #fff;
box-shadow: 0 5px 0 #ffbf0e;

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

In my case I kept getting a 403.14 after I had setup the correct rewrite rules. It turns out that I had a directory that was the same name as one of my URL routes. Once I removed the IsDirectory rewrite rule my routes worked correctly. Is there a case where removing the directory negation may cause problems? I can't think of any in my case. The only case I can think of is if you can browse a directory with your app.

<rule name="fixhtml5mode" stopProcessing="true">
  <match url=".*"/>
  <conditions logicalGrouping="MatchAll">
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
  </conditions>
  <action type="Rewrite" url="/" />
</rule>

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

Encrypt & Decrypt using PyCrypto AES 256

You can get a passphrase out of an arbitrary password by using a cryptographic hash function (NOT Python's builtin hash) like SHA-1 or SHA-256. Python includes support for both in its standard library:

import hashlib

hashlib.sha1("this is my awesome password").digest() # => a 20 byte string
hashlib.sha256("another awesome password").digest() # => a 32 byte string

You can truncate a cryptographic hash value just by using [:16] or [:24] and it will retain its security up to the length you specify.

Loading and parsing a JSON file with multiple JSON objects

You have a JSON Lines format text file. You need to parse your file line by line:

import json

data = []
with open('file') as f:
    for line in f:
        data.append(json.loads(line))

Each line contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.

Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and then process everything if your file is really big.

If you have a file containing individual JSON objects with delimiters in-between, use How do I use the 'json' module to read in one JSON object at a time? to parse out individual objects using a buffered method.

Converting VS2012 Solution to VS2010

Just to elaborate on Bhavin's excellent answer - editing the solution file works but you may still get the incompatible error (as David reported) if you had .NET 4.5 selected as the default .NET version in your VS2012 project and your VS2010 enviroment doesn't support that.

To quickly fix that, open the VS2012 .csproj file in a text editor and change the TargetFrameworkVersion down to 4.0 (from 4.5). VS2010 will then happily load the "edited" solution and projects.

You'll also have to edit an app.config files that have references to .NET 4.5 in a similar way to allow them to run on a .NET 4.0 environment.

Sending files using POST with HttpURLConnection

Here is what i did for uploading photo using post request.

public void uploadFile(int directoryID, String filePath) {
    Bitmap bitmapOrg = BitmapFactory.decodeFile(filePath);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();

    String upload_url = BASE_URL + UPLOAD_FILE;
    bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);

    byte[] data = bao.toByteArray();

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(upload_url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    try {
        // Set Data and Content-type header for the image
        FileBody fb = new FileBody(new File(filePath), "image/jpeg");
        StringBody contentString = new StringBody(directoryID + "");

        entity.addPart("file", fb);
        entity.addPart("directory_id", contentString);
        postRequest.setEntity(entity);

        HttpResponse response = httpClient.execute(postRequest);
        // Read the response
        String jsonString = EntityUtils.toString(response.getEntity());
        Log.e("response after uploading file ", jsonString);

    } catch (Exception e) {
        Log.e("Error in uploadFile", e.getMessage());
    }
}

NOTE: This code requires libraries so Follow the instructions here in order to get the libraries.

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

I was going to leave this after this comment: Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

But Stack Overflow was formatting it weirdly.

If you don't have identical machines and are checking in node_modules, do a .gitignore on the native extensions. Our .gitignore looks like:

# Ignore native extensions in the node_modules folder (things changed by npm rebuild)
node_modules/**/*.node
node_modules/**/*.o
node_modules/**/*.a
node_modules/**/*.mk
node_modules/**/*.gypi
node_modules/**/*.target
node_modules/**/.deps/
node_modules/**/build/Makefile
node_modules/**/**/build/Makefile

Test this by first checking everything in, and then have another developer do the following:

rm -rf node_modules
git checkout -- node_modules
npm rebuild
git status

Ensure that no files changed.

Connecting to SQL Server Express - What is my server name?

Sometimes none of these would work for me. So I used to create a new web project in VS and select Authorization as "Individual User Accounts". I believe this work with some higher version of .NET Framework or something. But when you do this it will have your connection details. Mostly something like this

(LocalDb)\MSSQLLocalDB

WCF service maxReceivedMessageSize basicHttpBinding issue

When using HTTPS instead of ON the binding, put it IN the binding with the httpsTransport tag:

    <binding name="MyServiceBinding">
      <security defaultAlgorithmSuite="Basic256Rsa15" 
                authenticationMode="MutualCertificate" requireDerivedKeys="true" 
                securityHeaderLayout="Lax" includeTimestamp="true" 
                messageProtectionOrder="SignBeforeEncrypt" 
                messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
                requireSignatureConfirmation="false">
        <localClientSettings detectReplays="true" />
        <localServiceSettings detectReplays="true" />
        <secureConversationBootstrap keyEntropyMode="CombinedEntropy" />
      </security>
      <textMessageEncoding messageVersion="Soap11WSAddressing10">
        <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" 
                      maxArrayLength="2147483647" maxBytesPerRead="4096" 
                      maxNameTableCharCount="16384"/>
      </textMessageEncoding>
      <httpsTransport maxReceivedMessageSize="2147483647" 
                      maxBufferSize="2147483647" maxBufferPoolSize="2147483647" 
                      requireClientCertificate="false" />
    </binding>

Getting coordinates of marker in Google Maps API

Also, you can display current position by "drag" listener and write it to visible or hidden field. You may also need to store zoom. Here's copy&paste from working tool:

            function map_init() {
            var lt=48.451778;
            var lg=31.646305;

            var myLatlng = new google.maps.LatLng(lt,lg);
            var mapOptions = {
                center: new google.maps.LatLng(lt,lg),
                zoom: 6,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById('map'),mapOptions);   
            var marker = new google.maps.Marker({
                position:myLatlng,
                map:map,
                draggable:true
            });

            google.maps.event.addListener(
                marker,
                'drag',
                function() {
                    document.getElementById('lat1').innerHTML = marker.position.lat().toFixed(6);
                    document.getElementById('lng1').innerHTML = marker.position.lng().toFixed(6);
                    document.getElementById('zoom').innerHTML = mapObject.getZoom();

                    // Dynamically show it somewhere if needed
                    $(".x").text(marker.position.lat().toFixed(6));
                    $(".y").text(marker.position.lng().toFixed(6));
                    $(".z").text(map.getZoom());

                }
            );                  
            }

Switching from zsh to bash on OSX, and back again?

you can just type bash or if you always want to use bash:

on "iTerm2"

  • Go to preferences > Profiles > Command
  • Select "Command" from the dropdown
  • Type bash

Test by closing iTerm and open it again

Java socket API: How to tell if a connection has been closed?

Thats how I handle it

 while(true) {
        if((receiveMessage = receiveRead.readLine()) != null ) {  

        System.out.println("first message same :"+receiveMessage);
        System.out.println(receiveMessage);      

        }
        else if(receiveRead.readLine()==null)
        {

        System.out.println("Client has disconected: "+sock.isClosed()); 
        System.exit(1);
         }    } 

if the result.code == null

Open file with associated application

In .Net Core (as of v2.2) it should be:

new Process
{
    StartInfo = new ProcessStartInfo(@"file path")
    {
        UseShellExecute = true
    }
}.Start();

Related github issue can be found here

Optimal way to DELETE specified rows from Oracle

First, disabling the index during the deletion would be helpful.

Try with a MERGE INTO statement :
1) create a temp table with IDs and an additional column from TABLE1 and test with the following

MERGE INTO table1 src
USING (SELECT id,col1
         FROM test_merge_delete) tgt
ON (src.id = tgt.id)
WHEN MATCHED THEN
  UPDATE
     SET src.col1 = tgt.col1
  DELETE
   WHERE src.id = tgt.id

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Taking up @ZF007's answer, this is not answering your question as a whole, but can be the solution for the same error. I post it here since I have not found a direct solution as an answer to this error message elsewhere on Stack Overflow.

The error appears when you check whether an array was empty or not.

  • if np.array([1,2]): print(1) --> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

  • if np.array([1,2])[0]: print(1) --> no ValueError, but: if np.array([])[0]: print(1) --> IndexError: index 0 is out of bounds for axis 0 with size 0.

  • if np.array([1]): print(1) --> no ValueError, but again will not help at an array with many elements.

  • if np.array([]): print(1) --> DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use 'array.size > 0' to check that an array is not empty.

Doing so:

  • if np.array([]).size: print(1) solved the error.

Any reason not to use '+' to concatenate two strings?

When working with multiple people, it's sometimes difficult to know exactly what's happening. Using a format string instead of concatenation can avoid one particular annoyance that's happened a whole ton of times to us:

Say, a function requires an argument, and you write it expecting to get a string:

In [1]: def foo(zeta):
   ...:     print 'bar: ' + zeta

In [2]: foo('bang')
bar: bang

So, this function may be used pretty often throughout the code. Your coworkers may know exactly what it does, but not necessarily be fully up-to-speed on the internals, and may not know that the function expects a string. And so they may end up with this:

In [3]: foo(23)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/izkata/<ipython console> in <module>()

/home/izkata/<ipython console> in foo(zeta)

TypeError: cannot concatenate 'str' and 'int' objects

There would be no problem if you just used a format string:

In [1]: def foo(zeta):
   ...:     print 'bar: %s' % zeta
   ...:     
   ...:     

In [2]: foo('bang')
bar: bang

In [3]: foo(23)
bar: 23

The same is true for all types of objects that define __str__, which may be passed in as well:

In [1]: from datetime import date

In [2]: zeta = date(2012, 4, 15)

In [3]: print 'bar: ' + zeta
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/izkata/<ipython console> in <module>()

TypeError: cannot concatenate 'str' and 'datetime.date' objects

In [4]: print 'bar: %s' % zeta
bar: 2012-04-15

So yes: If you can use a format string do it and take advantage of what Python has to offer.

Applying a single font to an entire website with CSS

As a different font is likely to be already defined by the browser for form elements, here are 2 ways to use this font everywhere:

body, input, textarea {
    font-family: Algerian;
}

body {
    font-family: Algerian !important;
}

There'll still have a monospace font on elements like pre/code, kbd, etc but, in case you use these elements, you'd better use a monospace font there.

Important note: if very few people has this font installed on their OS, then the second font in the list will be used. Here you defined no second font so the default serif font will be used, and it'll be Times, Times New Roman except maybe on Linux.
Two options there: use @font-face if your font is free of use as a downloadable font or add fallback(s): a second, a third, etc and finally a default family (sans-serif, cursive (*), monospace or serif). The first of the list that exists on the OS of the user will be used.

(*) default cursive on Windows is Comic Sans. Except if you want to troll Windows users, don't do that :) This font is terrible except for your children birthdays where it's welcome.

Improve SQL Server query performance on large tables

The question specifically states the performance needs to be improved for ad-hoc queries, and that indexes can't be added. So taking that at face value, what can be done to improve performance on any table?

Since we're considering ad-hoc queries, the WHERE clause and the ORDER BY clause can contain any combination of columns. This means that almost regardless of what indexes are placed on the table there will be some queries that require a table scan, as seen above in query plan of a poorly performing query.

Taking this into account, let's assume there are no indexes at all on the table apart from a clustered index on the primary key. Now let's consider what options we have to maximize performance.

  • Defragment the table

    As long as we have a clustered index then we can defragment the table using DBCC INDEXDEFRAG (deprecated) or preferably ALTER INDEX. This will minimize the number of disk reads required to scan the table and will improve speed.

  • Use the fastest disks possible. You don't say what disks you're using but if you can use SSDs.

  • Optimize tempdb. Put tempdb on the fastest disks possible, again SSDs. See this SO Article and this RedGate article.

  • As stated in other answers, using a more selective query will return less data, and should be therefore be faster.

Now let's consider what we can do if we are allowed to add indexes.

If we weren't talking about ad-hoc queries, then we would add indexes specifically for the limited set of queries being run against the table. Since we are discussing ad-hoc queries, what can be done to improve speed most of the time?

  • Add a single column index to each column. This should give SQL Server at least something to work with to improve the speed for the majority of queries, but won't be optimal.
  • Add specific indexes for the most common queries so they are optimized.
  • Add additional specific indexes as required by monitoring for poorly performing queries.

Edit

I've run some tests on a 'large' table of 22 million rows. My table only has six columns but does contain 4GB of data. My machine is a respectable desktop with 8Gb RAM and a quad core CPU and has a single Agility 3 SSD.

I removed all indexes apart from the primary key on the Id column.

A similar query to the problem one given in the question takes 5 seconds if SQL server is restarted first and 3 seconds subsequently. The database tuning advisor obviously recommends adding an index to improve this query, with an estimated improvement of > 99%. Adding an index results in a query time of effectively zero.

What's also interesting is that my query plan is identical to yours (with the clustered index scan), but the index scan accounts for 9% of the query cost and the sort the remaining 91%. I can only assume your table contains an enormous amount of data and/or your disks are very slow or located over a very slow network connection.

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

You could add the following VBA code to your sheet:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Range("A1") > 0.5 Then
        MsgBox "Discount too high"
    End If
End Sub

Every time a cell is changed on the sheet, it will check the value of cell A1.

Notes:

  • if A1 also depends on data located in other spreadsheets, the macro will not be called if you change that data.
  • the macro will be called will be called every time something changes on your sheet. If it has lots of formula (as in 1000s) it could be slow.

Widor uses a different approach (Worksheet_Calculate instead of Worksheet_Change):

  • Pros: his method will work if A1's value is linked to cells located in other sheets.
  • Cons: if you have many links on your sheet that reference other sheets, his method will run a bit slower.

Conclusion: use Worksheet_Change if A1 only depends on data located on the same sheet, use Worksheet_Calculate if not.

Connecting client to server using Socket.io

Have you tried loading the socket.io script not from a relative URL?

You're using:

<script src="socket.io/socket.io.js"></script>

And:

socket.connect('http://127.0.0.1:8080');

You should try:

<script src="http://localhost:8080/socket.io/socket.io.js"></script>

And:

socket.connect('http://localhost:8080');

Switch localhost:8080 with whatever fits your current setup.

Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.

Search for [^\x00-\x7F] and check the box for Regex.

The result will look like this (in dark mode):

zero width space made visible

How to read an http input stream

try this code

String data = "";
InputStream iStream = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream, "utf8"));
StringBuffer sb = new StringBuffer();
String line = "";

while ((line = br.readLine()) != null) {
    sb.append(line);
}

data = sb.toString();
System.out.println(data);

Emulator error: This AVD's configuration is missing a kernel file

In my own case, I had multiple errors most of which were about mis-configured ANDROID_SDK_ROOT, at the end of the day, one thing seemed to fix the whole thing.

Follow the following process:

After Creating the A new Emulator Device on AVD, go to the Actions menu and click on the arrow pointing downwards as shown below.

enter image description here

Click on Show on Disk

Edit Config.ini

Look for image.sysdir.1

it should have a value like this : **image.sysdir.1=system-images\android-28\google_apis_playstore\x86**

Your own value might be different

Now, fix in the path of the Android Sdk to make a complete path.

image.sysdir.1=**C:\androidsdk**system-images\android-28\google_apis_playstore\x86\

If you noticed, the android sdk path shown above is different from the normal default android sdk, I had to move it to C:/androidsdk to avoid NDK issues as my main USER HOME on my PC has whitespaces which NDK might not support.

NOTE: Moving the SDK directory away from its default directory is usually the cause of these errors AVD emulator gives, most especially as regarding broken and misconfigured path. The fix I provided above is a quick fix, you may have to do that each time you create a new device on AVD Emulator.

This fix should also work when working on CMD with cordova .

How do I run Visual Studio as an administrator by default?

Right click on icon --> Properties --> Advanced --> Check checkbox run as Administrator and everytime it will open under Admin Mode (Same for Windows 8)

Git fetch remote branch

You use 'git pull' to keep your branches separate. I will use the actual repository and branch names to help since 'lbranch' and 'rbranch' are tough to decipher.

Let's use:

  • myteam.unfuddle.com = the remote Git server
  • tlc = Unfuddle project account where the repository exists
  • daves_branch = remote branch name

    You, or any colleague, can run this to pull only your branch, no matter how many branches there are:

    git init
    git pull [email protected]:myteam/tlc daves_branch:refs/remotes/origin/daves_branch
    
  • Perform Segue programmatically and pass parameters to the destination view

    In case if you use new swift version.

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "ChannelMoreSegue" {
    
            }
    }
    

    Connect Android to WiFi Enterprise network EAP(PEAP)

    Thanks for enlightening us Cypawer.

    I also tried this app https://play.google.com/store/apps/details?id=com.oneguyinabasement.leapwifi

    and it worked flawlessly.

    Leap Wifi Connector

    Tips for debugging .htaccess rewrite rules

    I'll leave this here, maybe obvious detail, but got me banging my head for hours: be careful using %{REQUEST_URI} because what @Krist van Besien say in his answer is totally right, but not for the REQUEST_URI string, because the out put of this TestString starts with a /. So take care:

    RewriteCond %{REQUEST_URI} ^/assets/$  
                                ^
                                | check this pesky fella right here if missing
    

    Cannot connect to repo with TortoiseSVN

    I faced similar issue while doing svn update.

    The approach which worked for me is to rename C:\Users\user\AppData\Roaming\TortoiseSVN folder to TortoiseSVN_bkp folder and then tried svn update again. This time I was able to connect to repository and it got updated.

    Properly close mongoose's connection once you're done

    Probably you have this:

    const db = mongoose.connect('mongodb://localhost:27017/db');
    
    // Do some stuff
    
    db.disconnect();
    

    but you can also have something like this:

    mongoose.connect('mongodb://localhost:27017/db');
    
    const model = mongoose.model('Model', ModelSchema);
    
    model.find().then(doc => {
      console.log(doc);
    }
    

    you cannot call db.disconnect() but you can close the connection after you use it.

    model.find().then(doc => {
      console.log(doc);
    }).then(() => {
      mongoose.connection.close();
    });
    

    HREF="" automatically adds to current page URL (in PHP). Can't figure it out

    This is how a browser interprets and empty href. It assumes you want to link back to the page that you are on. This is the same as if you dont assign an action to a <form> element.

    If you add any word in the href it will append it to the current page unless you:

    • Add a slash / to the front of it telling it to append it to your base url e.g. http://www.whatever.com/something
    • add a # sign in which case it is an in-page anchor
    • or a valid URL

    EDIT: It was suggested that I add a link to help clarify the situation. I found the following site that I think does a really good job explaining the href attribute of anchor tags and how it interprets URL paths. It is not incredibly technical and very human-readable. It uses lots of examples to illustrate the differences between the path types: http://www.mediacollege.com/internet/html/hyperlinks.html

    How to close TCP and UDP ports via windows command line

    Use CurrPorts (it's free and no-install): http://www.nirsoft.net/utils/cports.html

    /close <Local Address> <Local Port> <Remote Address> <Remote Port> {Process Name}

    Examples:

    # Close all connections with remote port 80 and remote address 192.168.1.10: 
    /close * * 192.168.1.10 80
    # Close all connections with remote port 80 (for all remote addresses): 
    /close * * * 80
    # Close all connections to remote address 192.168.20.30: 
    /close * * 192.168.20.30 *
    # Close all connections with local port 80: 
    /close * 80 * *
    # Close all connections of Firefox with remote port 80: 
    /close * * * 80 firefox.exe
    

    It also has a nice GUI with search and filter features.

    Note: This answer is huntharo and JasonXA's answer and comment put together and simplified to make it easier for readers. Examples come from CurrPorts' web page.

    Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

    You could convert your recursive code into an iterative code, which simulates the recursion. This means that you have to push the current status (url, document, position in document etc.) into an array, when you reach a link, and pop it out of the array, when this link has finished.

    Http Get using Android HttpURLConnection

    Try getting the input stream from this you can then get the text data as so:-

        URL url;
        HttpURLConnection urlConnection = null;
        try {
            url = new URL("http://www.mysite.se/index.asp?data=99");
    
            urlConnection = (HttpURLConnection) url
                    .openConnection();
    
            InputStream in = urlConnection.getInputStream();
    
            InputStreamReader isw = new InputStreamReader(in);
    
            int data = isw.read();
            while (data != -1) {
                char current = (char) data;
                data = isw.read();
                System.out.print(current);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }    
        }
    

    You can probably use other inputstream readers such as buffered reader also.

    The problem is that when you open the connection - it does not 'pull' any data.

    How do I find all of the symlinks in a directory tree?

    What I do is create a script in my bin directory that is like an alias. For example I have a script named lsd ls -l | grep ^d

    you could make one lsl ls -lR | grep ^l

    Just chmod them +x and you are good to go.

    Serializing with Jackson (JSON) - getting "No serializer found"?

    If you use Lomdok libraray (https://projectlombok.org/) then add @Data (https://projectlombok.org/features/Data) annotation to your data object class.

    iOS Launching Settings -> Restrictions URL Scheme

    As of iOS10 you can use

    UIApplication.sharedApplication().openURL(NSURL(string:"App-Prefs:root")!) 
    

    to open general settings.

    also you can add known urls(you can see them in the most upvoted answer) to it to open specific settings. For example the below one opens touchID and passcode.

    UIApplication.sharedApplication().openURL(NSURL(string:"App-Prefs:root=TOUCHID_PASSCODE")!)
    

    How to programmatically empty browser cache?

    There's no way a browser will let you clear its cache. It would be a huge security issue if that were possible. This could be very easily abused - the minute a browser supports such a "feature" will be the minute I uninstall it from my computer.

    What you can do is to tell it not to cache your page, by sending the appropriate headers or using these meta tags:

    <meta http-equiv='cache-control' content='no-cache'>
    <meta http-equiv='expires' content='0'>
    <meta http-equiv='pragma' content='no-cache'>
    

    You might also want to consider turning off auto-complete on form fields, although I'm afraid there's a standard way to do it (see this question).

    Regardless, I would like to point out that if you are working with sensitive data you should be using SSL. If you aren't using SSL, anyone with access to the network can sniff network traffic and easily see what your user is seeing.

    Using SSL also makes some browsers not use caching unless explicitly told to. See this question.

    What is the difference between __dirname and ./ in node.js?

    The gist

    In Node.js, __dirname is always the directory in which the currently executing script resides (see this). So if you typed __dirname into /d1/d2/myscript.js, the value would be /d1/d2.

    By contrast, . gives you the directory from which you ran the node command in your terminal window (i.e. your working directory) when you use libraries like path and fs. Technically, it starts out as your working directory but can be changed using process.chdir().

    The exception is when you use . with require(). The path inside require is always relative to the file containing the call to require.

    For example...

    Let's say your directory structure is

    /dir1
      /dir2
        pathtest.js
    

    and pathtest.js contains

    var path = require("path");
    console.log(". = %s", path.resolve("."));
    console.log("__dirname = %s", path.resolve(__dirname));
    

    and you do

    cd /dir1/dir2
    node pathtest.js
    

    you get

    . = /dir1/dir2
    __dirname = /dir1/dir2
    

    Your working directory is /dir1/dir2 so that's what . resolves to. Since pathtest.js is located in /dir1/dir2 that's what __dirname resolves to as well.

    However, if you run the script from /dir1

    cd /dir1
    node dir2/pathtest.js
    

    you get

    . = /dir1
    __dirname = /dir1/dir2
    

    In that case, your working directory was /dir1 so that's what . resolved to, but __dirname still resolves to /dir1/dir2.

    Using . inside require...

    If inside dir2/pathtest.js you have a require call into include a file inside dir1 you would always do

    require('../thefile')
    

    because the path inside require is always relative to the file in which you are calling it. It has nothing to do with your working directory.

    Loop through JSON object List

    It's close! Try this:

    for (var prop in result) {
        if (result.hasOwnProperty(prop)) {
            alert(result[prop]);
        }
    }
    

    Update:

    If your result is truly is an array of one object, then you might have to do this:

    for (var prop in result[0]) {
        if (result[0].hasOwnProperty(prop)) {
            alert(result[0][prop]);
        }
    }
    

    Or if you want to loop through each result in the array if there are more, try:

    for (var i = 0; i < results.length; i++) {
        for (var prop in result[i]) {
            if (result[i].hasOwnProperty(prop)) {
                alert(result[i][prop]);
            }
        }
    }
    

    Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

    This is how you save the relevant file as a Excel12 (.xlsx) file... It is not as you would intuitively think i.e. using Excel.XlFileFormat.xlExcel12 but Excel.XlFileFormat.xlOpenXMLWorkbook. The actual C# command was

    excelWorkbook.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
        Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange, 
        Excel.XlSaveConflictResolution.xlUserResolution, true, 
        Missing.Value, Missing.Value, Missing.Value);
    

    I hope this helps someone else in the future.


    Missing.Value is found in the System.Reflection namespace.

    What is the difference between ( for... in ) and ( for... of ) statements?

    A see a lot of good answers, but I decide to put my 5 cents just to have good example:

    For in loop

    iterates over all enumerable props

    _x000D_
    _x000D_
    let nodes = document.documentElement.childNodes;_x000D_
    _x000D_
    for (var key in nodes) {_x000D_
      console.log( key );_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    For of loop

    iterates over all iterable values

    _x000D_
    _x000D_
    let nodes = document.documentElement.childNodes;_x000D_
    _x000D_
    for (var node of nodes) {_x000D_
      console.log( node.toString() );_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    SQL Server Linked Server Example Query

    You need to specify the schema/owner (dbo by default) as part of the reference. Also, it would be preferable to use the newer (ANSI-92) join style.

    select foo.id 
        from databaseserver1.db1.dbo.table1 foo
            inner join databaseserver2.db1.dbo.table1 bar 
                on foo.name = bar.name
    

    How to run Java program in command prompt

    You can use javac *.java command to compile all you java sources. Also you should learn a little about classpath because it seems that you should set appropriate classpath for succesful compilation (because your IDE use some libraries for building WebService clients). Also I can recommend you to check wich command your IDE use to build your project.

    Leap year calculation

    You could just check if the Year number is divisible by both 4 and 400. You dont really need to check if it is indivisible by 100. The reason 400 comes into question is because according to the Gregorian Calendar, our "day length" is slightly off, and thus to compensate that, we have 303 regular years (365 days each) and 97 leap years (366 days each). The difference of those 3 extra years that are not leap years is to stay in cycle with the Gregorian calendar, which repeats every 400 years. Look up Christian Zeller's congruence equation. It will help understanding the real reason. Hope this helps :)

    How do I update a Linq to SQL dbml file?

    Here is the complete step-by-step method that worked for me in order to update the LINQ to SQL dbml and associated files to include a new column that I added to one of the database tables.

    You need to make the changes to your design surface as suggested by other above; however, you need to do some extra steps. These are the complete steps:

    1. Drag your updated table from Server Explorer onto the design surface

    2. Copy the new column from this "new" table to the "old" table (see M463 answer for details on this step)

    3. Delete the "new" table that you just dragged over

    4. Click and highlight the stored procedure, then delete it

    5. Drag the new stored procedure and drop into place.

    6. Delete the .designer.vb file in the code-behind of the .dbml (if you do not delete this, your code-behind containing the schema will not update even if you rebuild and the new table field will not be included)

    7. Clean and Rebuild the solution (this will rebuild the .designer.vb file to include all the new changes!).

    Display exact matches only with grep

    Try the below command, because it works perfectly:

    grep -ow "yourstring"
    
    crosscheck:-
    

    Remove the instance of word from file, then re-execute this command and it should display empty result.

    How can I use SUM() OVER()

    Query would be like this:

    SELECT ID, AccountID, Quantity, 
           SUM(Quantity) OVER (PARTITION BY AccountID ) AS TopBorcT 
    
           FROM #Empl ORDER BY AccountID
    

    Partition by works like group by. Here we are grouping by AccountID so sum would be corresponding to AccountID.

    First first case, AccountID = 1 , then sum(quantity) = 10 + 5 + 2 => 17 & For AccountID = 2, then sum(Quantity) = 7+3 => 10

    so result would appear like attached snapshot.

    MSVCP120d.dll missing

    I have found myself wasting time searching for a solution on this, and i suspect doing it again in future. So here's a note to myself and others who might find this useful.

    If MSVCP120.DLL is missing, that means you have not installed Visual C++ Redistributable Packages for Visual Studio 2013 (x86 and x64). Install that, restart and you should find this file in c:\Windows\System32 .

    Now if MSVCP120D.DLL is missing, this means that the application you are trying to run is built in Debug mode. As OP has mentioned, the debug version of the runtime is NOT distributable.

    So what do we do?

    Well, there is one option that I know of: Go to your Project's Debug configuration > C/C++ > Code Generation > Runtime Library and select Multi-threaded Debug (/MTd). This will statically link MSVCP120D.dll into your executable.

    There is also a quick-fix if you just want to get something up quickly: Copy the MSVCP120D.DLL from sys32 (mine is C:\Windows\System32) folder. You may also need MSVCR120D.DLL.

    Addendum to the quick fix: To reduce guesswork, you can use dependency walker. Open your application with dependency walker, and you'll see what dll files are needed.

    For example, my recent application was built in Visual Studio 2015 (Windows 10 64-bit machine) and I am targeting it to a 32-bit Windows XP machine. Using dependency walker, my application (see screenshot) needs the following files:

    • opencv_*.dll <-- my own dll files (might also have dependency)
    • msvcp140d.dll <-- SysWOW64\msvcp140d.dll
    • kernel32.dll <-- SysWOW64\kernel32.dll
    • vcruntime140d.dll <-- SysWOW64\vcruntime140d.dll
    • ucrtbased.dll <-- SysWOW64\ucrtbased.dll

    Aside from the opencv* files that I have built, I would also need to copy the system files from C:\Windows\SysWow64 (System32 for 32-bit).

    You're welcome. :-)

    JavaScript post request like a form submit

    Three options here.

    1. Standard JavaScript answer: Use a framework! Most Ajax frameworks will have abstracted you an easy way to make an XMLHTTPRequest POST.

    2. Make the XMLHTTPRequest request yourself, passing post into the open method instead of get. (More information in Using POST method in XMLHTTPRequest (Ajax).)

    3. Via JavaScript, dynamically create a form, add an action, add your inputs, and submit that.

    Format an Integer using Java String Format

    If you are using a third party library called apache commons-lang, the following solution can be useful:

    Use StringUtils class of apache commons-lang :

    int i = 5;
    StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"
    

    As StringUtils.leftPad() is faster than String.format()

    How to execute .sql script file using JDBC

    I had the same problem trying to execute an SQL script that creates an SQL database. Googling here and there I found a Java class initially written by Clinton Begin which supports comments (see http://pastebin.com/P14HsYAG). I modified slightly the file to cater for triggers where one has to change the default DELIMITER to something different. I've used that version ScriptRunner (see http://pastebin.com/sb4bMbVv). Since an (open source and free) SQLScriptRunner class is an absolutely necessary utility, it would be good to have some more input from developers and hopefully we'll have soon a more stable version of it.

    Compute mean and standard deviation by group for multiple variables in a data.frame

    This is an aggregation problem, not a reshaping problem as the question originally suggested -- we wish to aggregate each column into a mean and standard deviation by ID. There are many packages that handle such problems. In the base of R it can be done using aggregate like this (assuming DF is the input data frame):

    ag <- aggregate(. ~ ID, DF, function(x) c(mean = mean(x), sd = sd(x)))
    

    Note 1: A commenter pointed out that ag is a data frame for which some columns are matrices. Although initially that may seem strange, in fact it simplifies access. ag has the same number of columns as the input DF. Its first column ag[[1]] is ID and the ith column of the remainder ag[[i+1]] (or equivalanetly ag[-1][[i]]) is the matrix of statistics for the ith input observation column. If one wishes to access the jth statistic of the ith observation it is therefore ag[[i+1]][, j] which can also be written as ag[-1][[i]][, j] .

    On the other hand, suppose there are k statistic columns for each observation in the input (where k=2 in the question). Then if we flatten the output then to access the jth statistic of the ith observation column we must use the more complex ag[[k*(i-1)+j+1]] or equivalently ag[-1][[k*(i-1)+j]] .

    For example, compare the simplicity of the first expression vs. the second:

    ag[-1][[2]]
    ##        mean      sd
    ## [1,] 36.333 10.2144
    ## [2,] 32.250  4.1932
    ## [3,] 43.500  4.9497
    
    ag_flat <- do.call("data.frame", ag) # flatten
    ag_flat[-1][, 2 * (2-1) + 1:2]
    ##   Obs_2.mean Obs_2.sd
    ## 1     36.333  10.2144
    ## 2     32.250   4.1932
    ## 3     43.500   4.9497
    

    Note 2: The input in reproducible form is:

    Lines <- "ID  Obs_1   Obs_2   Obs_3
    1   43      48      37
    1   27      29      22
    1   36      32      40
    2   33      38      36
    2   29      32      27
    2   32      31      35
    2   25      28      24
    3   45      47      42
    3   38      40      36"
    DF <- read.table(text = Lines, header = TRUE)
    

    Importing large sql file to MySql via command line

    The solution I use for large sql restore is a mysqldumpsplitter script. I split my sql.gz into individual tables. then load up something like mysql workbench and process it as a restore to the desired schema.

    Here is the script https://github.com/kedarvj/mysqldumpsplitter

    And this works for larger sql restores, my average on one site I work with is a 2.5gb sql.gz file, 20GB uncompressed, and ~100Gb once restored fully

    C convert floating point to int

    my_var = (int)my_var;
    

    As simple as that. Basically you don't need it if the variable is int.

    Simple and clean way to convert JSON string to Object in Swift

    let jsonString = "{\"id\":123,\"Name\":\"Munish\"}"
    

    Convert String to NSData

     var data: NSData =jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
    
     var error: NSError?
    

    Convert NSData to AnyObject

    var jsonObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data,     options: NSJSONReadingOptions.allZeros, error: &error)
    
    println("Error: \\(error)")
    
    let id = (jsonObject as! NSDictionary)["id"] as! Int
    
    let name = (jsonObject as! NSDictionary)["name"] as! String
    
    println("Id: \\(id)")
    
    println("Name: \\(name)")
    

    MongoDB vs Firebase

    • Firebase is a real-time engine with backward connectivity. I.e. you might build a cross-platform app where clients subscribe to events on specific data and server actively informs clients about changes
    • The data layer is hosted for you. Mind that it is highly scalable. It's a nice kickstarter solution. Including auth management
    • Geo-Fire. Real-time geo coordinates solution.
    • Evident drawbacks of Firebase are:
      • You have to pay for it as soon as you start growing
      • You can't host datalayer (if owning data is critical or you develop an app for some separated subnet)

    EDIT: here is a nice article how to replace Firebase in your app with Node.js+MongoDb. It shows how much work you would have to do on your own, and explains, IMHO, why a startup (small app) should begin with Firebase (if real-time updates to clients are required) and proceed with MongoDb (in any case self-written solution) if the project keeps evolving

    EDIT 2: after being acquired by Google Firebase now offers various perks on top of its basic features which you would struggle to build on your own:

    • For development

      • Cloud Messaging: Deliver and receive messages across platforms reliably
      • File Storage: Easy file storage (including iOS)
      • Hosting: deliver static files from Firebase's servers (Included in Free plan)
      • Crash Reporting: Not a full logging service, but crucial help
    • For growth

    Why does sed not replace all occurrences?

    You have to put a g at the end, it stands for "global":

    echo dog dog dos | sed -r 's:dog:log:g'
                                         ^
    

    How to convert all tables in database to one collation?

    Below is the more accurate query. I am giving example how to convert it to utf8

    SELECT CONCAT("ALTER TABLE `", TABLE_NAME,"` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;") AS    mySQL
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA="myschema"
    AND TABLE_TYPE="BASE TABLE"
    

    How to deal with page breaks when printing a large HTML table

    Use these CSS properties:

    page-break-after
    
    page-break-before 
    

    For instance:

    <html>
    <head>
    <style>
    @media print
    {
    table {page-break-after:always}
    }
    </style>
    </head>
    
    <body>
    ....
    </body>
    </html>
    

    via

    How to assign bean's property an Enum value in Spring config file?

    To be specific, set the value to be the name of a constant of the enum type, e.g., "TYPE1" or "TYPE2" in your case, as shown below. And it will work:

    <bean name="someName" class="my.pkg.classes">
       <property name="type" value="TYPE1" />
    </bean>
    

    How to find out the server IP address (using JavaScript) that the browser is connected to?

    _x000D_
    _x000D_
    <script type="application/javascript">
      function getIP(json) {
        document.write("My public IP address is: ", json.ip);
      }
    </script>
    <script type="application/javascript" src="http://ipinfo.io/?format=jsonp&callback=getIP"></script>
    _x000D_
    _x000D_
    _x000D_

    "use database_name" command in PostgreSQL

    Use this commad when first connect to psql

    =# psql <databaseName> <usernamePostgresql>
    

    Manipulating an Access database from Java without ODBC

    UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

     

    Option 1: Using Maven

    If your project uses Maven you can simply include UCanAccess via the following coordinates:

    groupId: net.sf.ucanaccess
    artifactId: ucanaccess

    The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

      <dependencies>
        <dependency>
            <groupId>net.sf.ucanaccess</groupId>
            <artifactId>ucanaccess</artifactId>
            <version>4.0.4</version>
        </dependency>
      </dependencies>
    

     

    Option 2: Manually adding the JARs to your project

    As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

    UCanAccess (ucanaccess-x.x.x.jar)
    HSQLDB (hsqldb.jar, version 2.2.5 or newer)
    Jackcess (jackcess-2.x.x.jar)
    commons-lang (commons-lang-2.6.jar, or newer 2.x version)
    commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

    Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

    ucanaccess-4.0.1.jar  
      /lib/
        commons-lang-2.6.jar  
        commons-logging-1.1.1.jar  
        hsqldb.jar  
        jackcess-2.1.6.jar
    

    All you need to do is add all five (5) JARs to your project.

    NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

    Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

    BuildPath.png

    NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

    nbAddJar.png

    After adding all five (5) JAR files the "Libraries" folder should look something like this:

    nbLibraries.png

    IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

    IntelliJ.png

     

    That's it!

    Now "U Can Access" data in .accdb and .mdb files using code like this

    // assumes...
    //     import java.sql.*;
    Connection conn=DriverManager.getConnection(
            "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
    Statement s = conn.createStatement();
    ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
    while (rs.next()) {
        System.out.println(rs.getString(1));
    }
    

     

    Disclosure

    At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

    How to have css3 animation to loop forever

    I stumbled upon the same problem: a page with many independent animations, each one with its own parameters, which must be repeated forever.

    Merging this clue with this other clue I found an easy solution: after the end of all your animations the wrapping div is restored, forcing the animations to restart.

    All you have to do is to add these few lines of Javascript, so easy they don't even need any external library, in the <head> section of your page:

    <script>
    setInterval(function(){
    var container = document.getElementById('content');
    var tmp = container.innerHTML;
    container.innerHTML= tmp;
    }, 35000 // length of the whole show in milliseconds
    );
    </script>
    

    BTW, the closing </head> in your code is misplaced: it must be before the starting <body>.

    Rename a table in MySQL

    ALTER TABLE old_table_name RENAME new_table_name;
    

    or

    RENAME TABLE old_table_name TO new_table_name;
    

    How to check that a JCheckBox is checked?

    Use the isSelected method.

    You can also use an ItemListener so you'll be notified when it's checked or unchecked.

    Cannot import scipy.misc.imread

    If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

    rather install scipy 1.1.0 by :

    pip install scipy==1.1.0

    check https://github.com/scipy/scipy/issues/6212


    The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

    from matplotlib.pyplot import imread
    im = imread(image.png)
    

    To read jpg images without PIL use:

    import cv2 as cv
    im = cv.imread(image.jpg)
    

    You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

    Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

    Should I call Close() or Dispose() for stream objects?

    No, you shouldn't call those methods manually. At the end of the using block the Dispose() method is automatically called which will take care to free unmanaged resources (at least for standard .NET BCL classes such as streams, readers/writers, ...). So you could also write your code like this:

    using (Stream responseStream = response.GetResponseStream())
        using (StreamReader reader = new StreamReader(responseStream))
            using (StreamWriter writer = new StreamWriter(filename))
            {
                int chunkSize = 1024;
                while (!reader.EndOfStream)
                {
                     char[] buffer = new char[chunkSize];
                     int count = reader.Read(buffer, 0, chunkSize);
                     if (count != 0)
                     {
                         writer.Write(buffer, 0, count);
                     }
                }
             }
    

    The Close() method calls Dispose().

    Find provisioning profile in Xcode 5

    check here:

    ~/Library/MobileDevice/Provisioning Profiles
    

    is of a type that is invalid for use as a key column in an index

    A unique constraint can't be over 8000 bytes per row and will only use the first 900 bytes even then so the safest maximum size for your keys would be:

    create table [misc_info]
    ( 
        [id] INTEGER PRIMARY KEY IDENTITY NOT NULL, 
        [key] nvarchar(450) UNIQUE NOT NULL, 
        [value] nvarchar(max) NOT NULL
    )
    

    i.e. the key can't be over 450 characters. If you can switch to varchar instead of nvarchar (e.g. if you don't need to store characters from more than one codepage) then that could increase to 900 characters.

    how to open popup window using jsp or jquery?

    <a href="javaScript:{openPopUp();}"></a>
    <form action="actionName">
    <div id="divId" style="display:none;">
    UsreName:<input type="text" name="userName"/>
    </div>
    </form>
    
    function openPopUp()
    {
      $('#divId').css('display','block');
    $('#divId').dialog();
    }
    

    How to change Java version used by TOMCAT?

    In Eclipse it is very easy to point Tomcat to a new JVM (in this example JRE6). My problem was I couldn't find where to do it. Here is the trick:

    1. On the ECLIPSE top menu FILE pull down tab, select NEW, -->Other
    2. ...on the New Server: Select A Wizard window, select: Server-> Server... click NEXT
    3. . on the New Server: Define a New Server window, select Apache> Tomcat 7 Server
    4. ..now click the line in blue and underlined entitled: Configure Runtime Environments
    5. on the Server Runtime Environments window,
    6. ..select Apache, expand it(click on the arrow to the left), select TOMCAT v7.0, and click EDIT.
    7. you will see a window called EDIT SERVER RUNTIME ENVIRONMENT: TOMCAT SERVER
    8. On this screen there is a pulldown labeled JREs.
    9. You should find your JRE listed like JRE1.6.0.33. If not use the Installed JRE button.
    10. Select the desired JRE. Click the FINISH button.
    11. Gracefully exit, in the Server: Server Runtime Environments window, click OK
    12. in the New Server: Define a new Server window, hit NEXT
    13. in the New Server: Add and Remove Window, select apps and install them on the server.
    14. in the New Server: Add and Remove Window, click Finish

    That's all. Interesting, only steps 7-10 seem to matter, and they will change the JRE used on all servers you have previously defined to use TOMCAT v7.0. The rest of the steps are just because I can't find any other way to get to the screen except by defining a new server. Does anyone else know an easier way?

    What encoding/code page is cmd.exe using?

    Yes, it’s frustrating—sometimes type and other programs print gibberish, and sometimes they do not.

    First of all, Unicode characters will only display if the current console font contains the characters. So use a TrueType font like Lucida Console instead of the default Raster Font.

    But if the console font doesn’t contain the character you’re trying to display, you’ll see question marks instead of gibberish. When you get gibberish, there’s more going on than just font settings.

    When programs use standard C-library I/O functions like printf, the program’s output encoding must match the console’s output encoding, or you will get gibberish. chcp shows and sets the current codepage. All output using standard C-library I/O functions is treated as if it is in the codepage displayed by chcp.

    Matching the program’s output encoding with the console’s output encoding can be accomplished in two different ways:

    • A program can get the console’s current codepage using chcp or GetConsoleOutputCP, and configure itself to output in that encoding, or

    • You or a program can set the console’s current codepage using chcp or SetConsoleOutputCP to match the default output encoding of the program.

    However, programs that use Win32 APIs can write UTF-16LE strings directly to the console with WriteConsoleW. This is the only way to get correct output without setting codepages. And even when using that function, if a string is not in the UTF-16LE encoding to begin with, a Win32 program must pass the correct codepage to MultiByteToWideChar. Also, WriteConsoleW will not work if the program’s output is redirected; more fiddling is needed in that case.

    type works some of the time because it checks the start of each file for a UTF-16LE Byte Order Mark (BOM), i.e. the bytes 0xFF 0xFE. If it finds such a mark, it displays the Unicode characters in the file using WriteConsoleW regardless of the current codepage. But when typeing any file without a UTF-16LE BOM, or for using non-ASCII characters with any command that doesn’t call WriteConsoleW—you will need to set the console codepage and program output encoding to match each other.


    How can we find this out?

    Here’s a test file containing Unicode characters:

    ASCII     abcde xyz
    German    äöü ÄÖÜ ß
    Polish    aezznl
    Russian   ??????? ???
    CJK       ??
    

    Here’s a Java program to print out the test file in a bunch of different Unicode encodings. It could be in any programming language; it only prints ASCII characters or encoded bytes to stdout.

    import java.io.*;
    
    public class Foo {
    
        private static final String BOM = "\ufeff";
        private static final String TEST_STRING
            = "ASCII     abcde xyz\n"
            + "German    äöü ÄÖÜ ß\n"
            + "Polish    aezznl\n"
            + "Russian   ??????? ???\n"
            + "CJK       ??\n";
    
        public static void main(String[] args)
            throws Exception
        {
            String[] encodings = new String[] {
                "UTF-8", "UTF-16LE", "UTF-16BE", "UTF-32LE", "UTF-32BE" };
    
            for (String encoding: encodings) {
                System.out.println("== " + encoding);
    
                for (boolean writeBom: new Boolean[] {false, true}) {
                    System.out.println(writeBom ? "= bom" : "= no bom");
    
                    String output = (writeBom ? BOM : "") + TEST_STRING;
                    byte[] bytes = output.getBytes(encoding);
                    System.out.write(bytes);
                    FileOutputStream out = new FileOutputStream("uc-test-"
                        + encoding + (writeBom ? "-bom.txt" : "-nobom.txt"));
                    out.write(bytes);
                    out.close();
                }
            }
        }
    }
    

    The output in the default codepage? Total garbage!

    Z:\andrew\projects\sx\1259084>chcp
    Active code page: 850
    
    Z:\andrew\projects\sx\1259084>java Foo
    == UTF-8
    = no bom
    ASCII     abcde xyz
    German    +ñ+Â++ +ä+û+£ +ƒ
    Polish    -à-Ö+¦+++ä+é
    Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
    CJK       õ¢áÕÑ¢
    = bom
    ´++ASCII     abcde xyz
    German    +ñ+Â++ +ä+û+£ +ƒ
    Polish    -à-Ö+¦+++ä+é
    Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
    CJK       õ¢áÕÑ¢
    == UTF-16LE
    = no bom
    A S C I I           a b c d e   x y z
     G e r m a n         õ ÷ ³   - Í _   ¯
     P o l i s h         ????z?|?D?B?
     R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
     C J K               `O}Y
     = bom
     ¦A S C I I           a b c d e   x y z
     G e r m a n         õ ÷ ³   - Í _   ¯
     P o l i s h         ????z?|?D?B?
     R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
     C J K               `O}Y
     == UTF-16BE
    = no bom
     A S C I I           a b c d e   x y z
     G e r m a n         õ ÷ ³   - Í _   ¯
     P o l i s h        ?????z?|?D?B
     R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
     C J K              O`Y}
    = bom
    ¦  A S C I I           a b c d e   x y z
     G e r m a n         õ ÷ ³   - Í _   ¯
     P o l i s h        ?????z?|?D?B
     R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
     C J K              O`Y}
    == UTF-32LE
    = no bom
    A   S   C   I   I                       a   b   c   d   e       x   y   z
       G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
       P   o   l   i   s   h                   ??  ??  z?  |?  D?  B?
       R   u   s   s   i   a   n               0?  1?  2?  3?  4?  5?  6?      M?  N
    ?  O?
       C   J   K                               `O  }Y
       = bom
     ¦  A   S   C   I   I                       a   b   c   d   e       x   y   z
    
       G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
       P   o   l   i   s   h                   ??  ??  z?  |?  D?  B?
       R   u   s   s   i   a   n               0?  1?  2?  3?  4?  5?  6?      M?  N
    ?  O?
       C   J   K                               `O  }Y
       == UTF-32BE
    = no bom
       A   S   C   I   I                       a   b   c   d   e       x   y   z
       G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
       P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
       R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
      ?O
       C   J   K                              O`  Y}
    = bom
      ¦    A   S   C   I   I                       a   b   c   d   e       x   y   z
    
       G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
       P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
       R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
      ?O
       C   J   K                              O`  Y}
    

    However, what if we type the files that got saved? They contain the exact same bytes that were printed to the console.

    Z:\andrew\projects\sx\1259084>type *.txt
    
    uc-test-UTF-16BE-bom.txt
    
    
    ¦  A S C I I           a b c d e   x y z
     G e r m a n         õ ÷ ³   - Í _   ¯
     P o l i s h        ?????z?|?D?B
     R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
     C J K              O`Y}
    
    uc-test-UTF-16BE-nobom.txt
    
    
     A S C I I           a b c d e   x y z
     G e r m a n         õ ÷ ³   - Í _   ¯
     P o l i s h        ?????z?|?D?B
     R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
     C J K              O`Y}
    
    uc-test-UTF-16LE-bom.txt
    
    
    ASCII     abcde xyz
    German    äöü ÄÖÜ ß
    Polish    aezznl
    Russian   ??????? ???
    CJK       ??
    
    uc-test-UTF-16LE-nobom.txt
    
    
    A S C I I           a b c d e   x y z
     G e r m a n         õ ÷ ³   - Í _   ¯
     P o l i s h         ????z?|?D?B?
     R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
     C J K               `O}Y
    
    uc-test-UTF-32BE-bom.txt
    
    
      ¦    A   S   C   I   I                       a   b   c   d   e       x   y   z
    
       G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
       P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
       R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
      ?O
       C   J   K                              O`  Y}
    
    uc-test-UTF-32BE-nobom.txt
    
    
       A   S   C   I   I                       a   b   c   d   e       x   y   z
       G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
       P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
       R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
      ?O
       C   J   K                              O`  Y}
    
    uc-test-UTF-32LE-bom.txt
    
    
     A S C I I           a b c d e   x y z
     G e r m a n         ä ö ü   Ä Ö Ü   ß
     P o l i s h         a e z z n l
     R u s s i a n       ? ? ? ? ? ? ?   ? ? ?
     C J K               ? ?
    
    uc-test-UTF-32LE-nobom.txt
    
    
    A   S   C   I   I                       a   b   c   d   e       x   y   z
       G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
       P   o   l   i   s   h                   ??  ??  z?  |?  D?  B?
       R   u   s   s   i   a   n               0?  1?  2?  3?  4?  5?  6?      M?  N
    ?  O?
       C   J   K                               `O  }Y
    
    uc-test-UTF-8-bom.txt
    
    
    ´++ASCII     abcde xyz
    German    +ñ+Â++ +ä+û+£ +ƒ
    Polish    -à-Ö+¦+++ä+é
    Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
    CJK       õ¢áÕÑ¢
    
    uc-test-UTF-8-nobom.txt
    
    
    ASCII     abcde xyz
    German    +ñ+Â++ +ä+û+£ +ƒ
    Polish    -à-Ö+¦+++ä+é
    Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
    CJK       õ¢áÕÑ¢
    

    The only thing that works is UTF-16LE file, with a BOM, printed to the console via type.

    If we use anything other than type to print the file, we get garbage:

    Z:\andrew\projects\sx\1259084>copy uc-test-UTF-16LE-bom.txt CON
     ¦A S C I I           a b c d e   x y z
     G e r m a n         õ ÷ ³   - Í _   ¯
     P o l i s h         ????z?|?D?B?
     R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
     C J K               `O}Y
             1 file(s) copied.
    

    From the fact that copy CON does not display Unicode correctly, we can conclude that the type command has logic to detect a UTF-16LE BOM at the start of the file, and use special Windows APIs to print it.

    We can see this by opening cmd.exe in a debugger when it goes to type out a file:

    enter image description here

    After type opens a file, it checks for a BOM of 0xFEFF—i.e., the bytes 0xFF 0xFE in little-endian—and if there is such a BOM, type sets an internal fOutputUnicode flag. This flag is checked later to decide whether to call WriteConsoleW.

    But that’s the only way to get type to output Unicode, and only for files that have BOMs and are in UTF-16LE. For all other files, and for programs that don’t have special code to handle console output, your files will be interpreted according to the current codepage, and will likely show up as gibberish.

    You can emulate how type outputs Unicode to the console in your own programs like so:

    #include <stdio.h>
    #define UNICODE
    #include <windows.h>
    
    static LPCSTR lpcsTest =
        "ASCII     abcde xyz\n"
        "German    äöü ÄÖÜ ß\n"
        "Polish    aezznl\n"
        "Russian   ??????? ???\n"
        "CJK       ??\n";
    
    int main() {
        int n;
        wchar_t buf[1024];
    
        HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    
        n = MultiByteToWideChar(CP_UTF8, 0,
                lpcsTest, strlen(lpcsTest),
                buf, sizeof(buf));
    
        WriteConsole(hConsole, buf, n, &n, NULL);
    
        return 0;
    }
    

    This program works for printing Unicode on the Windows console using the default codepage.


    For the sample Java program, we can get a little bit of correct output by setting the codepage manually, though the output gets messed up in weird ways:

    Z:\andrew\projects\sx\1259084>chcp 65001
    Active code page: 65001
    
    Z:\andrew\projects\sx\1259084>java Foo
    == UTF-8
    = no bom
    ASCII     abcde xyz
    German    äöü ÄÖÜ ß
    Polish    aezznl
    Russian   ??????? ???
    CJK       ??
    ? ???
    CJK       ??
     ??
    ?
    ?
    = bom
    ASCII     abcde xyz
    German    äöü ÄÖÜ ß
    Polish    aezznl
    Russian   ??????? ???
    CJK       ??
    ?? ???
    CJK       ??
      ??
    ?
    ?
    == UTF-16LE
    = no bom
    A S C I I           a b c d e   x y z
    …
    

    However, a C program that sets a Unicode UTF-8 codepage:

    #include <stdio.h>
    #include <windows.h>
    
    int main() {
        int c, n;
        UINT oldCodePage;
        char buf[1024];
    
        oldCodePage = GetConsoleOutputCP();
        if (!SetConsoleOutputCP(65001)) {
            printf("error\n");
        }
    
        freopen("uc-test-UTF-8-nobom.txt", "rb", stdin);
        n = fread(buf, sizeof(buf[0]), sizeof(buf), stdin);
        fwrite(buf, sizeof(buf[0]), n, stdout);
    
        SetConsoleOutputCP(oldCodePage);
    
        return 0;
    }
    

    does have correct output:

    Z:\andrew\projects\sx\1259084>.\test
    ASCII     abcde xyz
    German    äöü ÄÖÜ ß
    Polish    aezznl
    Russian   ??????? ???
    CJK       ??
    

    The moral of the story?

    • type can print UTF-16LE files with a BOM regardless of your current codepage
    • Win32 programs can be programmed to output Unicode to the console, using WriteConsoleW.
    • Other programs which set the codepage and adjust their output encoding accordingly can print Unicode on the console regardless of what the codepage was when the program started
    • For everything else you will have to mess around with chcp, and will probably still get weird output.

    Git cli: get user info from username

    Add my two cents, if you're using windows commnad line:

    git config --list | findstr user.name will give username directly.

    The findstr here is quite similar to grep in linux.

    Posting form to different MVC post action depending on the clicked submit button

    you can use ajax calls to call different methods without a postback

    $.ajax({
        type: "POST",
         url: "@(Url.Action("Action", "Controller"))",
         data: {id: 'id', id1: 'id1' },
         contentType: "application/json; charset=utf-8",
         cache: false,
         async: true,
         success: function (result) {
            //do something
         }
    });
    

    jQuery issue - #<an Object> has no method

    For anyone else arriving at this question:

    I was performing the most simple jQuery, trying to hide an element:

    ('#fileselection').hide();
    

    and I was getting the same type of error, "Uncaught TypeError: Object #fileselection has no method 'hide'

    Of course, now it is obvious, but I just left off the jQuery indicator '$'. The code should have been:

    $('#fileselection').hide();
    

    This fixes the no-brainer problem. I hope this helps someone save a few minutes debugging!

    Pure JavaScript: a function like jQuery's isNumeric()

    var str = 'test343',
        isNumeric = /^[-+]?(\d+|\d+\.\d*|\d*\.\d+)$/;
    
    isNumeric.test(str);
    

    DevTools failed to load SourceMap: Could not load content for chrome-extension

    I resolved this by clearing App Data.

    Cypress documentation admits that App Data can get corrupted:

    Cypress maintains some local application data in order to save user preferences and more quickly start up. Sometimes this data can become corrupted. You may fix an issue you have by clearing this app data.

    1. Open Cypress via cypress open
    2. Go to File -> View App Data
    3. This will take you to the directory in your file system where your App Data is stored. If you cannot open Cypress, search your file system for a directory named cy whose content should look something like this:

           production
                all.log
                browsers
                bundles
                cache
                projects
                proxy
                state.json

    1. Delete everything in the cy folder
    2. Close Cypress and open it up again

    Source: https://docs.cypress.io/guides/references/troubleshooting.html#To-clear-App-Data

    What does java.lang.Thread.interrupt() do?

    Thread.interrupt() method sets internal 'interrupt status' flag. Usually that flag is checked by Thread.interrupted() method.

    By convention, any method that exists via InterruptedException have to clear interrupt status flag.

    Print JSON parsed object?

    The following code will display complete json data in alert box

    var data= '{"employees":[' +
    '{"firstName":"John","lastName":"Doe" },' +
    '{"firstName":"Anna","lastName":"Smith" },' +
    '{"firstName":"Peter","lastName":"Jones" }]}';
    
    json = JSON.parse(data);
    window.alert(JSON.stringify(json));
    

    Sort array of objects by single key with date value

    With ES2015 support it can be done by:

    foo.sort((a, b) => a.updated_at < b.updated_at ? -1 : 1)
    

    Possible to view PHP code of a website?

    Noone cand read the file except for those who have access to the file. You must make the code readable (but not writable) by the web server. If the php code handler is running properly you can't read it by requesting by name from the web server.

    If someone compromises your server you are at risk. Ensure that the web server can only write to locations it absolutely needs to. There are a few locations under /var which should be properly configured by your distribution. They should not be accessible over the web. /var/www should not be writable, but may contain subdirectories written to by the web server for dynamic content. Code handlers should be disabled for these.

    Ensure you don't do anything in your php code which can lead to code injection. The other risk is directory traversal using paths containing .. or begining with /. Apache should already be patched to prevent this when it is handling paths. However, when it runs code, including php, it does not control the paths. Avoid anything that allows the web client to pass a file path.

    How can I add a custom HTTP header to ajax request with js or jQuery?

    You can use js fetch

    _x000D_
    _x000D_
    async function send(url,data) {_x000D_
      let r= await fetch(url, {_x000D_
            method: "POST", _x000D_
            headers: {_x000D_
              "My-header": "abc"  _x000D_
            },_x000D_
            body: JSON.stringify(data), _x000D_
      })_x000D_
      return await r.json()_x000D_
    }_x000D_
    _x000D_
    // Example usage_x000D_
    _x000D_
    let url='https://server.test-cors.org/server?enable=true&status=200&methods=POST&headers=my-header';_x000D_
    _x000D_
    async function run() _x000D_
    {_x000D_
     let jsonObj = await send(url,{ some: 'testdata' });_x000D_
     console.log(jsonObj[0].request.httpMethod + ' was send - open chrome console > network to see it');_x000D_
    }_x000D_
    _x000D_
    run();
    _x000D_
    _x000D_
    _x000D_

    JavaScript replace \n with <br />

    You need the /g for global matching

    replace(/\n/g, "<br />");

    This works for me for \n - see this answer if you might have \r\n

    NOTE: The dupe is the most complete answer for any combination of \r\n, \r or \n

    _x000D_
    _x000D_
    var messagetoSend = document.getElementById('x').value.replace(/\n/g, "<br />");_x000D_
    console.log(messagetoSend);
    _x000D_
    <textarea id="x" rows="9">_x000D_
        Line 1_x000D_
        _x000D_
        _x000D_
        Line 2_x000D_
        _x000D_
        _x000D_
        _x000D_
        _x000D_
        Line 3_x000D_
    </textarea>
    _x000D_
    _x000D_
    _x000D_

    UPDATE

    It seems some visitors of this question have text with the breaklines escaped as

    some text\r\nover more than one line"

    In that case you need to escape the slashes:

    replace(/\\r\\n/g, "<br />");

    NOTE: All browsers will ignore \r in a string when rendering.

    How can I make git show a list of the files that are being tracked?

    If you want to list all the files currently being tracked under the branch master, you could use this command:

    git ls-tree -r master --name-only
    

    If you want a list of files that ever existed (i.e. including deleted files):

    git log --pretty=format: --name-only --diff-filter=A | sort - | sed '/^$/d'
    

    How do I resolve ClassNotFoundException?

    Go up to the top and remove the import statement if there is one, and re import the class. But if that isn't the case do a clean then build. Are you using Netbeans or Eclipse?

    default value for struct member in C

    If you are using gcc you can give designated initializers in object creation.

    typedef struct
    {
       int id=0;
       char* name="none";
    }employee;
    
    employee e = 
    {
     .id = 0;
     .name = "none";
    };
    

    Or , simply use like array initialization.

    employee e = {0 , "none"};

    Extracting jar to specified directory

    Current working version as of Oct 2020, updated to use maven-antrun-plugin 3.0.0.

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <id>prepare</id>
                        <phase>package</phase>
                        <configuration>
                            <target>
                                <unzip src="target/shaded-jar/shade-test.jar"
                                       dest="target/unpacked-shade/"/>
                            </target>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
    

    Replace Div with another Div

    HTML

    <div id="replaceMe">i need to be replaced</div>
    <div id="iamReplacement">i am replacement</div>
    

    JavaScript

    jQuery('#replaceMe').replaceWith(jQuery('#iamReplacement'));
    

    Output grep results to text file, need cleaner output

    Redirection of program output is performed by the shell.

    grep ... > output.txt
    

    grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

    How to dynamically change a web page's title?

    Update: as per the comments and reference on SearchEngineLand most web crawlers will index the updated title. Below answer is obsolete, but the code is still applicable.

    You can just do something like, document.title = "This is the new page title.";, but that would totally defeat the purpose of SEO. Most crawlers aren't going to support javascript in the first place, so they will take whatever is in the element as the page title.

    If you want this to be compatible with most of the important crawlers, you're going to need to actually change the title tag itself, which would involve reloading the page (PHP, or the like). You're not going to be able to get around that, if you want to change the page title in a way that a crawler can see.

    How to use google maps without api key

    Hey You can Use this insted

    <iframe width="100%" height="100%" class="absolute inset-0" frameborder="0" title="map" marginheight="0" marginwidth="0" scrolling="no" src="https://maps.google.com/maps?width=100%&amp;height=600&amp;hl=en&amp;q=%C4%B0ikaneir+(Mumma's%20Bakery)&amp;ie=UTF8&amp;t=&amp;z=14&amp;iwloc=B&amp;output=embed" style="filter: scale(100) contrast(1.2) opacity(0.4);"></iframe>
    

    Use basic authentication with jQuery and Ajax

    As others have suggested, you can set the username and password directly in the Ajax call:

    $.ajax({
      username: username,
      password: password,
      // ... other parameters.
    });
    

    OR use the headers property if you would rather not store your credentials in plain text:

    $.ajax({
      headers: {"Authorization": "Basic xxxx"},
      // ... other parameters.
    });
    

    Whichever way you send it, the server has to be very polite. For Apache, your .htaccess file should look something like this:

    <LimitExcept OPTIONS>
        AuthUserFile /path/to/.htpasswd
        AuthType Basic
        AuthName "Whatever"
        Require valid-user
    </LimitExcept>
    
    Header always set Access-Control-Allow-Headers Authorization
    Header always set Access-Control-Allow-Credentials true
    
    SetEnvIf Origin "^(.*?)$" origin_is=$0
    Header always set Access-Control-Allow-Origin %{origin_is}e env=origin_is
    

    Explanation:

    For some cross domain requests, the browser sends a preflight OPTIONS request that is missing your authentication headers. Wrap your authentication directives inside the LimitExcept tag to respond properly to the preflight.

    Then send a few headers to tell the browser that it is allowed to authenticate, and the Access-Control-Allow-Origin to grant permission for the cross-site request.

    In some cases, the * wildcard doesn't work as a value for Access-Control-Allow-Origin: You need to return the exact domain of the callee. Use SetEnvIf to capture this value.

    How can I check if a directory exists?

    Use the following code to check if a folder exists. It works on both Windows & Linux platforms.

    #include <stdio.h>
    #include <sys/stat.h>
    
    int main(int argc, char* argv[])
    {
        const char* folder;
        //folder = "C:\\Users\\SaMaN\\Desktop\\Ppln";
        folder = "/tmp";
        struct stat sb;
    
        if (stat(folder, &sb) == 0 && S_ISDIR(sb.st_mode)) {
            printf("YES\n");
        } else {
            printf("NO\n");
        }
    }
    

    How to run a Powershell script from the command line and pass a directory as a parameter

    Change your code to the following :

    Function Foo($directory)
        {
            echo $directory
        }
    
        if ($args.Length -eq 0)
        {
            echo "Usage: Foo <directory>"
        }
        else
        {
            Foo([string[]]$args)
        }
    

    And then invoke it as:

    powershell -ExecutionPolicy RemoteSigned -File "c:\foo.ps1" "c:\Documents and Settings" "c:\test"

    Are 64 bit programs bigger and faster than 32 bit versions?

    Only justification for moving your application to 64 bit is need for more memory in applications like large databases or ERP applications with at least 100s of concurrent users where 2 GB limit will be exceeded fairly quickly when applications cache for better performance. This is case specially on Windows OS where integer and long is still 32 bit (they have new variable _int64. Only pointers are 64 bit. In fact WOW64 is highly optimised on Windows x64 so that 32 bit applications run with low penalty on 64 bit Windows OS. My experience on Windows x64 is 32 bit application version run 10-15% faster than 64 bit since in former case at least for proprietary memory databases you can use pointer arithmatic for maintaining b-tree (most processor intensive part of database systems). Compuatation intensive applications which require large decimals for highest accuracy not afforded by double on 32-64 bit operating system. These applications can use _int64 in natively instead of software emulation. Of course large disk based databases will also show improvement over 32 bit simply due to ability to use large memory for caching query plans and so on.

    Int to Decimal Conversion - Insert decimal point at specified location

    int i = 7122960;
    decimal d = (decimal)i / 100;
    

    iOS: Convert UTC NSDate to local Timezone

    If you want local Date and time. Try this code:-

    NSString *localDate = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];
    

    Insert the same fixed value into multiple rows

    To update the content of existing rows use the UPDATE statement:

    UPDATE table_name SET table_column = 'test';
    

    Vertical align text in block element

    DO NOT USE THE 4th solution from top if you are using ag-grid. It will fix the issue for aligning the element in middle but it might break the thing in ag-grid (for me i was not able to select checkbox after some row). Problem is not with the solution or ag-grid but somehow the combination is not good.

    DO NOT USE THIS SOLUTION FOR AG-GRID

    li a {
        width: 300px;
        height: 100px;
        margin: auto 0;
        display: inline-block;
        vertical-align: middle;
        background: red;  
    }
    
    li a:after {
        content:"";
        display: inline-block;
        width: 1px solid transparent;
        height: 100%;
        vertical-align: middle;
    }
    

    Laravel check if collection is empty

    From php7 you can use Null Coalesce Opperator:

    $employee = $mentors->intern ?? $mentors->intern->employee
    

    This will return Null or the employee.

    Material effect on button with background color

    Programmatically applying the colors:

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
    
        ColorStateList colorStateListRipple = new ColorStateList(
                new int[][] {{0}},
                new int[] {Color.WHITE} // ripple color
                );
    
        RippleDrawable rippleDrawable = (RippleDrawable) myButton.getBackground();
        rippleDrawable.setColor(colorStateListRipple);
        myButton.setBackground(rippleDrawable); // applying the ripple color
    }
    
    ColorStateList colorStateList = new ColorStateList(
            new int[][]{
                    new int[]{android.R.attr.state_pressed}, // when pressed
                    new int[]{android.R.attr.state_enabled}, // normal state color
                    new int[]{} // normal state color
            },
            new int[]{
                    Color.CYAN, // when pressed
                    Color.RED, // normal state color
                    Color.RED // normal state color
            }
    );
    
    ViewCompat.setBackgroundTintList(myButton, colorStateList); // applying the state colors
    

    jquery, selector for class within id

    Always use

    //Super Fast
    $('#my_id').find('.my_class'); 
    

    instead of

    // Fast:
    $('#my_id .my_class');
    

    Have look at JQuery Performance Rules.

    Also at Jquery Doc

    DataSet panel (Report Data) in SSRS designer is gone

    View -> Datasets (bottom of menu, above Refresh)

    Simple WPF RadioButton Binding?

    I created an attached property based on Aviad's Answer which doesn't require creating a new class

    public static class RadioButtonHelper
    {
        [AttachedPropertyBrowsableForType(typeof(RadioButton))]
        public static object GetRadioValue(DependencyObject obj) => obj.GetValue(RadioValueProperty);
        public static void SetRadioValue(DependencyObject obj, object value) => obj.SetValue(RadioValueProperty, value);
        public static readonly DependencyProperty RadioValueProperty =
            DependencyProperty.RegisterAttached("RadioValue", typeof(object), typeof(RadioButtonHelper), new PropertyMetadata(new PropertyChangedCallback(OnRadioValueChanged)));
    
        private static void OnRadioValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is RadioButton rb)
            {
                rb.Checked -= OnChecked;
                rb.Checked += OnChecked;
            }
        }
    
        public static void OnChecked(object sender, RoutedEventArgs e)
        {
            if (sender is RadioButton rb)
            {
                rb.SetCurrentValue(RadioBindingProperty, rb.GetValue(RadioValueProperty));
            }
        }
    
        [AttachedPropertyBrowsableForType(typeof(RadioButton))]
        public static object GetRadioBinding(DependencyObject obj) => obj.GetValue(RadioBindingProperty);
        public static void SetRadioBinding(DependencyObject obj, object value) => obj.SetValue(RadioBindingProperty, value);
    
        public static readonly DependencyProperty RadioBindingProperty =
            DependencyProperty.RegisterAttached("RadioBinding", typeof(object), typeof(RadioButtonHelper), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(OnRadioBindingChanged)));
    
        private static void OnRadioBindingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is RadioButton rb && rb.GetValue(RadioValueProperty).Equals(e.NewValue))
            {
                rb.SetCurrentValue(RadioButton.IsCheckedProperty, true);
            }
        }
    }
    

    usage :

    <RadioButton GroupName="grp1" Content="Value 1"
        helpers:RadioButtonHelper.RadioValue="val1" helpers:RadioButtonHelper.RadioBinding="{Binding SelectedValue}"/>
    <RadioButton GroupName="grp1" Content="Value 2"
        helpers:RadioButtonHelper.RadioValue="val2" helpers:RadioButtonHelper.RadioBinding="{Binding SelectedValue}"/>
    <RadioButton GroupName="grp1" Content="Value 3"
        helpers:RadioButtonHelper.RadioValue="val3" helpers:RadioButtonHelper.RadioBinding="{Binding SelectedValue}"/>
    <RadioButton GroupName="grp1" Content="Value 4"
        helpers:RadioButtonHelper.RadioValue="val4" helpers:RadioButtonHelper.RadioBinding="{Binding SelectedValue}"/>
    

    SQL multiple columns in IN clause

    It often ends up being easier to load your data into the database, even if it is only to run a quick query. Hard-coded data seems quick to enter, but it quickly becomes a pain if you start having to make changes.

    However, if you want to code the names directly into your query, here is a cleaner way to do it:

    with names (fname,lname) as (
        values
            ('John','Smith'),
            ('Mary','Jones')
    )
    select city from user
        inner join names on
            fname=firstName and
            lname=lastName;
    

    The advantage of this is that it separates your data out of the query somewhat.

    (This is DB2 syntax; it may need a bit of tweaking on your system).

    Convert Float to Int in Swift

    You can type cast like this:

     var float:Float = 2.2
     var integer:Int = Int(float)
    

    psql: FATAL: Peer authentication failed for user "dev"

    This works for me when I run into it:

    sudo -u username psql
    

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

    It is important to notice that in C# the char type is stored as Unicode UTF-16.

    From ASCII equivalent integer to char

    char c = (char)88;
    

    or

    char c = Convert.ToChar(88)
    

    From char to ASCII equivalent integer

    int asciiCode = (int)'A';
    

    The literal must be ASCII equivalent. For example:

    string str = "X?????????";
    Console.WriteLine((int)str[0]);
    Console.WriteLine((int)str[1]);
    

    will print

    X
    3626
    

    Extended ASCII ranges from 0 to 255.

    From default UTF-16 literal to char

    Using the Symbol

    char c = 'X';
    

    Using the Unicode code

    char c = '\u0058';
    

    Using the Hexadecimal

    char c = '\x0058';
    

    How to find list of possible words from a letter matrix [Boggle Solver]

    Here is my java implementation: https://github.com/zouzhile/interview/blob/master/src/com/interview/algorithms/tree/BoggleSolver.java

    Trie build took 0 hours, 0 minutes, 1 seconds, 532 milliseconds
    Word searching took 0 hours, 0 minutes, 0 seconds, 92 milliseconds

    eel eeler eely eer eke eker eld eleut elk ell 
    elle epee epihippus ere erept err error erupt eurus eye 
    eyer eyey hip hipe hiper hippish hipple hippus his hish 
    hiss hist hler hsi ihi iphis isis issue issuer ist 
    isurus kee keek keeker keel keeler keep keeper keld kele 
    kelek kelep kelk kell kelly kelp kelper kep kepi kept 
    ker kerel kern keup keuper key kyl kyle lee leek 
    leeky leep leer lek leo leper leptus lepus ler leu 
    ley lleu lue lull luller lulu lunn lunt lunule luo 
    lupe lupis lupulus lupus lur lure lurer lush lushly lust 
    lustrous lut lye nul null nun nupe nurture nurturer nut 
    oer ore ort ouphish our oust out outpeep outpeer outpipe 
    outpull outpush output outre outrun outrush outspell outspue outspurn outspurt 
    outstrut outstunt outsulk outturn outusure oyer pee peek peel peele 
    peeler peeoy peep peeper peepeye peer pele peleus pell peller 
    pelu pep peplus pepper pepperer pepsis per pern pert pertussis 
    peru perule perun peul phi pip pipe piper pipi pipistrel 
    pipistrelle pipistrellus pipper pish piss pist plup plus plush ply 
    plyer psi pst puerer pul pule puler pulk pull puller 
    pulley pullus pulp pulper pulu puly pun punt pup puppis 
    pur pure puree purely purer purr purre purree purrel purrer 
    puru purupuru pus push puss pustule put putt puture ree 
    reek reeker reeky reel reeler reeper rel rely reoutput rep 
    repel repeller repipe reply repp reps reree rereel rerun reuel 
    roe roer roey roue rouelle roun roup rouper roust rout 
    roy rue ruelle ruer rule ruler rull ruller run runt 
    rupee rupert rupture ruru rus rush russ rust rustre rut 
    shi shih ship shipper shish shlu sip sipe siper sipper 
    sis sish sisi siss sissu sist sistrurus speel speer spelk 
    spell speller splurt spun spur spurn spurrer spurt sput ssi 
    ssu stre stree streek streel streeler streep streke streperous strepsis 
    strey stroup stroy stroyer strue strunt strut stu stue stull 
    stuller stun stunt stupe stupeous stupp sturnus sturt stuss stut 
    sue suer suerre suld sulk sulker sulky sull sully sulu 
    sun sunn sunt sunup sup supe super superoutput supper supple 
    supplely supply sur sure surely surrey sus susi susu susurr 
    susurrous susurrus sutu suture suu tree treey trek trekker trey 
    troupe trouper trout troy true truer trull truller truly trun 
    trush truss trust tshi tst tsun tsutsutsi tue tule tulle 
    tulu tun tunu tup tupek tupi tur turn turnup turr 
    turus tush tussis tussur tut tuts tutu tutulus ule ull 
    uller ulu ululu unreel unrule unruly unrun unrust untrue untruly 
    untruss untrust unturn unurn upper upperer uppish uppishly uppull uppush 
    upspurt upsun upsup uptree uptruss upturn ure urn uro uru 
    urus urushi ush ust usun usure usurer utu yee yeel 
    yeld yelk yell yeller yelp yelper yeo yep yer yere 
    yern yoe yor yore you youl youp your yourn yoy 
    

    Note: I used the dictionary and character matrix at the beginning of this thread. The code was run on my MacBookPro, below is some information about the machine.

    Model Name: MacBook Pro
    Model Identifier: MacBookPro8,1
    Processor Name: Intel Core i5
    Processor Speed: 2.3 GHz
    Number Of Processors: 1
    Total Number Of Cores: 2
    L2 Cache (per core): 256 KB
    L3 Cache: 3 MB
    Memory: 4 GB
    Boot ROM Version: MBP81.0047.B0E
    SMC Version (system): 1.68f96

    javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25

    This should not happen. Can you try doing this? Use the system properties and set the property as below:

    Properties properties = System.getProperties();
    // Setup mail server
    properties.setProperty("mail.smtp.host", "10.101.3.229");
    

    And if you have a port associated, then set this as well.

    properties.setProperty("mail.smtp.port", "8080");
    

    Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

    The error is a stack overflow. That should ring a bell on this site, right? It occurs because a call to poruszanie results in another call to poruszanie, incrementing the recursion depth by 1. The second call results in another call to the same function. That happens over and over again, each time incrementing the recursion depth.

    Now, the usable resources of a program are limited. Each function call takes a certain amount of space on top of what is called the stack. If the maximum stack height is reached, you get a stack overflow error.

    What is the best free memory leak detector for a C/C++ program and its plug-in DLLs?

    I have had good experiences with Rational Purify. I have also heard nice things about Valgrind

    Creating table variable in SQL server 2008 R2

    @tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

    To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

    There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

    Create table #test (Id int, Name varchar(50))
    

    This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

    IF OBJECT_ID('tempdb..#test') IS NOT NULL
      DROP TABLE #test 
    

    Hope this makes sense !

    Adding a 'share by email' link to website

    Something like this might be the easiest way.

    <a href="mailto:?subject=I wanted you to see this site&amp;body=Check out this site http://www.website.com."
       title="Share by Email">
      <img src="http://png-2.findicons.com/files/icons/573/must_have/48/mail.png">
    </a>
    

    You could find another email image and add that if you wanted.

    Is it possible to listen to a "style change" event?

    Since jQuery is open-source, I would guess that you could tweak the css function to call a function of your choice every time it is invoked (passing the jQuery object). Of course, you'll want to scour the jQuery code to make sure there is nothing else it uses internally to set CSS properties. Ideally, you'd want to write a separate plugin for jQuery so that it does not interfere with the jQuery library itself, but you'll have to decide whether or not that is feasible for your project.

    Access item in a list of lists

    for l in list1:
        val = 50 - l[0] + l[1] - l[2]
        print "val:", val
    

    Loop through list and do operation on the sublist as you wanted.

    ThreadStart with parameters

    The ParameterizedThreadStart takes one parameter. You can use that to send one parameter, or a custom class containing several properties.

    Another method is to put the method that you want to start as an instance member in a class along with properties for the parameters that you want to set. Create an instance of the class, set the properties and start the thread specifying the instance and the method, and the method can access the properties.

    Get epoch for a specific date using Javascript

    Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

    const unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
    const javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');
    
    console.log(unixTimeZero);
    // expected output: 0
    
    console.log(javaScriptRelease);
    // expected output: 818035920000
    

    Explore more at: Date.parse()

    What is a good pattern for using a Global Mutex in C#?

    Using the accepted answer I create a helper class so you could use it in a similar way you would use the Lock statement. Just thought I'd share.

    Use:

    using (new SingleGlobalInstance(1000)) //1000ms timeout on global lock
    {
        //Only 1 of these runs at a time
        RunSomeStuff();
    }
    

    And the helper class:

    class SingleGlobalInstance : IDisposable
    {
        //edit by user "jitbit" - renamed private fields to "_"
        public bool _hasHandle = false;
        Mutex _mutex;
    
        private void InitMutex()
        {
            string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value;
            string mutexId = string.Format("Global\\{{{0}}}", appGuid);
            _mutex = new Mutex(false, mutexId);
    
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);
            _mutex.SetAccessControl(securitySettings);
        }
    
        public SingleGlobalInstance(int timeOut)
        {
            InitMutex();
            try
            {
                if(timeOut < 0)
                    _hasHandle = _mutex.WaitOne(Timeout.Infinite, false);
                else
                    _hasHandle = _mutex.WaitOne(timeOut, false);
    
                if (_hasHandle == false)
                    throw new TimeoutException("Timeout waiting for exclusive access on SingleInstance");
            }
            catch (AbandonedMutexException)
            {
                _hasHandle = true;
            }
        }
    
    
        public void Dispose()
        {
            if (_mutex != null)
            {
                if (_hasHandle)
                    _mutex.ReleaseMutex();
                _mutex.Close();
            }
        }
    }
    

    What is the best way to check for Internet connectivity using .NET?

    public static bool HasConnection()
    {
        try
        {
            System.Net.IPHostEntry i = System.Net.Dns.GetHostEntry("www.google.com");
            return true;
        }
        catch
        {
            return false;
        }
    }
    

    That works

    How do you create a temporary table in an Oracle database?

    CREATE TABLE table_temp_list_objects AS
    SELECT o.owner, o.object_name FROM sys.all_objects o WHERE o.object_type ='TABLE';
    

    How to Truncate a string in PHP to the word closest to a certain number of characters?

    $shorttext = preg_replace('/^([\s\S]{1,200})[\s]+?[\s\S]+/', '$1', $fulltext);
    

    Description:

    • ^ - start from beginning of string
    • ([\s\S]{1,200}) - get from 1 to 200 of any character
    • [\s]+? - not include spaces at the end of short text so we can avoid word ... instead of word...
    • [\s\S]+ - match all other content

    Tests:

    1. regex101.com let's add to or few other r
    2. regex101.com orrrr exactly 200 characters.
    3. regex101.com after fifth r orrrrr excluded.

    Enjoy.

    jQuery: print_r() display equivalent?

    Look at this: http://phpjs.org/functions/index and find for print_r or use console.log() with firebug.

    Html.RenderPartial() syntax with Razor

    Html.RenderPartial() is a void method - you can check whether a method is a void method by placing your mouse over the call to RenderPartial in your code and you will see the text (extension) void HtmlHelper.RenderPartial...

    Void methods require a semicolon at the end of the calling code.

    In the Webforms view engine you would have encased your Html.RenderPartial() call within the bee stings <% %>

    like so

    <% Html.RenderPartial("Path/to/my/partial/view"); %>
    

    when you are using the Razor view engine the equivalent is

    @{Html.RenderPartial("Path/to/my/partial/view");}
    

    Why is a div with "display: table-cell;" not affected by margin?

    Table cells don't respect margin, but you could use transparent borders instead:

    div {
      display: table-cell;
      border: 5px solid transparent;
    }
    

    Note: you can't use percentages here... :(

    Can I get div's background-image url?

    I usually prefer .replace() to regular expressions when possible, since it's often easier to read: http://jsfiddle.net/mblase75/z2jKA/2

        $("div").click(function() {
            var bg = $(this).css('background-image');
            bg = bg.replace('url(','').replace(')','').replace(/\"/gi, "");
            alert(bg);
        });
    

    Get current url in Angular

    You can make use of location service available in @angular/common and via this below code you can get the location or current URL

    import { Component, OnInit } from '@angular/core';
    import { Location } from '@angular/common';
    import { Router } from '@angular/router';
    
    @Component({
      selector: 'app-top-nav',
      templateUrl: './top-nav.component.html',
      styleUrls: ['./top-nav.component.scss']
    })
    export class TopNavComponent implements OnInit {
    
      route: string;
    
      constructor(location: Location, router: Router) {
        router.events.subscribe((val) => {
          if(location.path() != ''){
            this.route = location.path();
          } else {
            this.route = 'Home'
          }
        });
      }
    
      ngOnInit() {
      }
    
    }
    

    here is the reference link from where I have copied thing to get location for my project. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts

    Different between parseInt() and valueOf() in java?

    Integer.valueOf(s)
    

    is similar to

    new Integer(Integer.parseInt(s))
    

    The difference is valueOf() returns an Integer, and parseInt() returns an int (a primitive type). Also note that valueOf() can return a cached Integer instance, which can cause confusing results where the result of == tests seem intermittently correct. Before autoboxing there could be a difference in convenience, after java 1.5 it doesn't really matter.

    Moreover, Integer.parseInt(s) can take primitive datatype as well.

    Finding all positions of substring in a larger string in C#

    Without Regex, using string comparison type:

    string search = "123aa456AA789bb9991AACAA";
    string pattern = "AA";
    Enumerable.Range(0, search.Length)
       .Select(index => { return new { Index = index, Length = (index + pattern.Length) > search.Length ? search.Length - index : pattern.Length }; })
       .Where(searchbit => searchbit.Length == pattern.Length && pattern.Equals(search.Substring(searchbit.Index, searchbit.Length),StringComparison.OrdinalIgnoreCase))
       .Select(searchbit => searchbit.Index)
    

    This returns {3,8,19,22}. Empty pattern would match all positions.

    For multiple patterns:

    string search = "123aa456AA789bb9991AACAA";
    string[] patterns = new string[] { "aa", "99" };
    patterns.SelectMany(pattern => Enumerable.Range(0, search.Length)
       .Select(index => { return new { Index = index, Length = (index + pattern.Length) > search.Length ? search.Length - index : pattern.Length }; })
       .Where(searchbit => searchbit.Length == pattern.Length && pattern.Equals(search.Substring(searchbit.Index, searchbit.Length), StringComparison.OrdinalIgnoreCase))
       .Select(searchbit => searchbit.Index))
    

    This returns {3, 8, 19, 22, 15, 16}

    How Do I Make Glyphicons Bigger? (Change Size?)

    I've used bootstrap header classes ("h1", "h2", etc.) for this. This way you get all the style benefits without using the actual tags. Here is an example:

    <div class="h3"><span class="glyphicon glyphicon-tags" aria-hidden="true"></span></div>

    How to delete a stash created with git stash create?

    git stash           // create stash,
    git stash push -m "message" // create stash with msg,
    git stash apply         // to apply stash,
    git stash apply indexno // to apply  specific stash, 
    git stash list          //list stash,
    git stash drop indexno      //to delete stash,
    git stash pop indexno,
    git stash pop = stash drop + stash apply
    git stash clear         //clear all your local stashed code
    

    Round integers to the nearest 10

    Actually, you could still use the round function:

    >>> print round(1123.456789, -1)
    1120.0
    

    This would round to the closest multiple of 10. To 100 would be -2 as the second argument and so forth.

    Android: How do I get string from resources using its name?

    A simple way to getting resource string from string into a TextView. Here resourceName is the name of resource

    int resID = getResources().getIdentifier(resourceName, "string", getPackageName());
    textview.setText(resID);
    

    Get time difference between two dates in seconds

    Below code will give the time difference in second.

    var date1 = new Date(); // current date
    var date2 = new Date("06/26/2018"); // mm/dd/yyyy format
    var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // in miliseconds
    var timeDiffInSecond = Math.ceil(timeDiff / 1000); // in second
    
    alert(timeDiffInSecond );
    

    Where is SQL Server Management Studio 2012?

    I downloaded it from here (named 'Microsoft SQL Server Data Tools'). In this version you will get a Visual Studio 2012 installation with the functionality to manage the SQL Server 2012 server.

    What character represents a new line in a text area

    It seems that, according to the HTML5 spec, the value property of the textarea element should return '\r\n' for a newline:

    The element's value is defined to be the element's raw value with the following transformation applied:

    Replace every occurrence of a "CR" (U+000D) character not followed by a "LF" (U+000A) character, and every occurrence of a "LF" (U+000A) character not preceded by a "CR" (U+000D) character, by a two-character string consisting of a U+000D CARRIAGE RETURN "CRLF" (U+000A) character pair.

    Following the link to 'value' makes it clear that it refers to the value property accessed in javascript:

    Form controls have a value and a checkedness. (The latter is only used by input elements.) These are used to describe how the user interacts with the control.

    However, in all five major browsers (using Windows, 11/27/2015), if '\r\n' is written to a textarea, the '\r' is stripped. (To test: var e=document.createElement('textarea'); e.value='\r\n'; alert(e.value=='\n');) This is true of IE since v9. Before that, IE was returning '\r\n' and converting both '\r' and '\n' to '\r\n' (which is the HTML5 spec). So... I'm confused.

    To be safe, it's usually enough to use '\r?\n' in regular expressions instead of just '\n', but if the newline sequence must be known, a test like the above can be performed in the app.

    How can I see an the output of my C programs using Dev-C++?

    i think you should link your project in console mode

    just press Ctrl+h and in General tab select console.

    socket.emit() vs. socket.send()

    https://socket.io/docs/client-api/#socket-send-args-ack

    socket.send // Sends a message event

    socket.emit(eventName[, ...args][, ack]) // you can custom eventName

    Using Python to execute a command on every file in a folder

    Use os.walk to iterate recursively over directory content:

    import os
    
    root_dir = '.'
    
    for directory, subdirectories, files in os.walk(root_dir):
        for file in files:
            print os.path.join(directory, file)
    

    No real difference between os.system and subprocess.call here - unless you have to deal with strangely named files (filenames including spaces, quotation marks and so on). If this is the case, subprocess.call is definitely better, because you don't need to do any shell-quoting on file names. os.system is better when you need to accept any valid shell command, e.g. received from user in the configuration file.

    How to permanently add a private key with ssh-add on Ubuntu?

    On Ubuntu 14.04 (maybe earlier, maybe still) you don't even need the console:

    • start seahorse or launch that thing you find searching for "key"
    • create an SSH key there (or import one)
      • no need to leave the passphrase empty
      • it is offered to you to even push the public key to a server (or more)
    • you will end up with an ssh-agent running and this key loaded, but locked
    • using ssh will pickup the identity (i.e. key) through the agent
    • on first use during the session, the passphrase will be checked
      • and you have the option to automatically unlock the key on login
      • this means the login auth will be used to wrap the passphrase of the key
    • note: if you want to forward your identity (i.e. agent-forwarding) invoke your ssh with -A or make that the default
      • otherwise you can't authenticate with that key on a machine you login to later to a third machine

    glm rotate usage in Opengl

    GLM has good example of rotation : http://glm.g-truc.net/code.html

    glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.f);
    glm::mat4 ViewTranslate = glm::translate(
        glm::mat4(1.0f),
        glm::vec3(0.0f, 0.0f, -Translate)
    );
    glm::mat4 ViewRotateX = glm::rotate(
        ViewTranslate,
        Rotate.y,
        glm::vec3(-1.0f, 0.0f, 0.0f)
    );
    glm::mat4 View = glm::rotate(
        ViewRotateX,
        Rotate.x,
        glm::vec3(0.0f, 1.0f, 0.0f)
    );
    glm::mat4 Model = glm::scale(
        glm::mat4(1.0f),
        glm::vec3(0.5f)
    );
    glm::mat4 MVP = Projection * View * Model;
    glUniformMatrix4fv(LocationMVP, 1, GL_FALSE, glm::value_ptr(MVP));
    

    Pass table as parameter into sql server UDF

    You can, however no any table. From documentation:

    For Transact-SQL functions, all data types, including CLR user-defined types and user-defined table types, are allowed except the timestamp data type.

    You can use user-defined table types.

    Example of user-defined table type:

    CREATE TYPE TableType 
    AS TABLE (LocationName VARCHAR(50))
    GO 
    
    DECLARE @myTable TableType
    INSERT INTO @myTable(LocationName) VALUES('aaa')
    SELECT * FROM @myTable
    

    So what you can do is to define your table type, for example TableType and define the function which takes the parameter of this type. An example function:

    CREATE FUNCTION Example( @TableName TableType READONLY)
    RETURNS VARCHAR(50)
    AS
    BEGIN
        DECLARE @name VARCHAR(50)
    
        SELECT TOP 1 @name = LocationName FROM @TableName
        RETURN @name
    END
    

    The parameter has to be READONLY. And example usage:

    DECLARE @myTable TableType
    INSERT INTO @myTable(LocationName) VALUES('aaa')
    SELECT * FROM @myTable
    
    SELECT dbo.Example(@myTable)
    

    Depending on what you want achieve you can modify this code.

    EDIT: If you have a data in a table you may create a variable:

    DECLARE @myTable TableType
    

    And take data from your table to the variable

    INSERT INTO @myTable(field_name)
    SELECT field_name_2 FROM my_other_table
    

    Compiling with g++ using multiple cores

    There is no such flag, and having one runs against the Unix philosophy of having each tool perform just one function and perform it well. Spawning compiler processes is conceptually the job of the build system. What you are probably looking for is the -j (jobs) flag to GNU make, a la

    make -j4

    Or you can use pmake or similar parallel make systems.

    How to loop through a directory recursively to delete files with certain extensions

    If you want to do something recursively, I suggest you use recursion (yes, you can do it using stacks and so on, but hey).

    recursiverm() {
      for d in *; do
        if [ -d "$d" ]; then
          (cd -- "$d" && recursiverm)
        fi
        rm -f *.pdf
        rm -f *.doc
      done
    }
    
    (cd /tmp; recursiverm)
    

    That said, find is probably a better choice as has already been suggested.

    execJs: 'Could not find a JavaScript runtime' but execjs AND therubyracer are in Gemfile

    add in your gemfile which is in the folder you have created: gem 'execjs' gem 'therubyracer'

    How can I add a line to a file in a shell script?

    sed is line based, so I'm not sure why you want to do this with sed. The paradigm is more processing one line at a time( you could also programatically find the # of fields in the CSV and generate your header line with awk) Why not just

    echo "c1, c2, ... " >> file
    cat testfile.csv >> file
    

    ?

    How to coerce a list object to type 'double'

    There are problems with some data. Consider:

    as.double(as.character("2.e")) # This results in 2
    

    Another solution:

    get_numbers <- function(X) {
        X[toupper(X) != tolower(X)] <- NA
        return(as.double(as.character(X)))
    }
    

    JPA 2.0, Criteria API, Subqueries, In Expressions

    You can use double join, if table A B are connected only by table AB.

    public static Specification<A> findB(String input) {
        return (Specification<A>) (root, cq, cb) -> {
            Join<A,AB> AjoinAB = root.joinList(A_.AB_LIST,JoinType.LEFT);
            Join<AB,B> ABjoinB = AjoinAB.join(AB_.B,JoinType.LEFT);
            return cb.equal(ABjoinB.get(B_.NAME),input);
        };
    }
    

    That's just an another option
    Sorry for that timing but I have came across this question and I also wanted to make SELECT IN but I didn't even thought about double join. I hope it will help someone.

    How do I POST XML data to a webservice with Postman?

    Send XML requests with the raw data type, then set the Content-Type to text/xml.


    1. After creating a request, use the dropdown to change the request type to POST.

      Set request type to POST

    2. Open the Body tab and check the data type for raw.

      Setting data type to raw

    3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

      Selecting content-type text/xml

    4. Enter your raw XML data into the input field below

      Example of XML request in Postman

    5. Click Send to submit your XML Request to the specified server.

      Clicking the Send button

    Crystal Reports 13 And Asp.Net 3.5

    I had faced the same issue because of some dll files were missing from References of VS13. I went to the location http://scn.sap.com/docs/DOC-7824 and installed the newest pack. It resolved the issue.

    Send form data with jquery ajax json

    The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.

    To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.

    $.ajax({
        url: 'test.php',
        type: "POST",
        dataType: 'json',
        data: formToJson($("form")),
        contentType: 'application/json;charset=UTF-8',
        ...
    })
    

    Static link of shared library function in gcc

    A bit late but ... I found a link that I saved a couple of years ago and I thought it might be useful for you guys:

    CDE: Automatically create portable Linux applications

    http://www.pgbovine.net/cde.html

    • Just download the program
    • Execute the binary passing as a argument the name of the binary you want make portable, for example: nmap

      ./cde_2011-08-15_64bit nmap

    The program will read all of libs linked to nmap and its dependencias and it will save all of them in a folder called cde-package/ (in the same directory that you are).

    • Finally, you can compress the folder and deploy the portable binary in whatever system.

    Remember, to launch the portable program you have to exec the binary located in cde-package/nmap.cde

    Best regards

    pip issue installing almost any library

    The only solution that worked for me is:

    sudo curl https://bootstrap.pypa.io/get-pip.py | sudo python

    Android, How to create option Menu

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.*;
    import android.widget.*;
    
    public class AndroidWalkthroughApp2 extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // show menu when menu button is pressed
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.options_menu, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // display a message when a button was pressed
            String message = "";
            if (item.getItemId() == R.id.option1) {
                message = "You selected option 1!";
            }
            else if (item.getItemId() == R.id.option2) {
                message = "You selected option 2!";
            }
            else {
                message = "Why would you select that!?";
            }
    
            // show message via toast
            Toast toast = Toast.makeText(this, message, Toast.LENGTH_LONG);
            toast.show();
    
            return true;
        }
    }
    

    Get first letter of a string from column

    .str.get

    This is the simplest to specify string methods

    # Setup
    df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
    df
    
            A    B
    0     xyz  123
    1     abc  456
    2  foobar  789
    
    df.dtypes
    
    A    object
    B     int64
    dtype: object
    

    For string (read:object) type columns, use

    df['C'] = df['A'].str[0]
    # Similar to,
    df['C'] = df['A'].str.get(0)
    

    .str handles NaNs by returning NaN as the output.

    For non-numeric columns, an .astype conversion is required beforehand, as shown in @Ed Chum's answer.

    # Note that this won't work well if the data has NaNs. 
    # It'll return lowercase "n"
    df['D'] = df['B'].astype(str).str[0]
    

    df
            A    B  C  D
    0     xyz  123  x  1
    1     abc  456  a  4
    2  foobar  789  f  7
    

    List Comprehension and Indexing

    There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.

    # For string columns
    df['C'] = [x[0] for x in df['A']]
    
    # For numeric columns
    df['D'] = [str(x)[0] for x in df['B']]
    

    df
            A    B  C  D
    0     xyz  123  x  1
    1     abc  456  a  4
    2  foobar  789  f  7
    

    If your data has NaNs, then you will need to handle this appropriately with an if/else in the list comprehension,

    df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
    df2
    
            A      B
    0     xyz  123.0
    1     NaN  456.0
    2  foobar    NaN
    
    # For string columns
    df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]
    
    # For numeric columns
    df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]
    
            A      B    C    D
    0     xyz  123.0    x    1
    1     NaN  456.0  NaN    4
    2  foobar    NaN    f  NaN
    

    Let's do some timeit tests on some larger data.

    df_ = df.copy()
    df = pd.concat([df_] * 5000, ignore_index=True) 
    
    %timeit df.assign(C=df['A'].str[0])
    %timeit df.assign(D=df['B'].astype(str).str[0])
    
    %timeit df.assign(C=[x[0] for x in df['A']])
    %timeit df.assign(D=[str(x)[0] for x in df['B']])
    

    12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
    
    3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    

    List comprehensions are 4x faster.

    How to change XML Attribute

    Here's the beginnings of a parser class to get you started. This ended up being my solution to a similar problem:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml.Linq;
    
    namespace XML
    {
        public class Parser
        {
    
            private string _FilePath = string.Empty;
    
            private XDocument _XML_Doc = null;
    
    
            public Parser(string filePath)
            {
                _FilePath = filePath;
                _XML_Doc = XDocument.Load(_FilePath);
            }
    
    
            /// <summary>
            /// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in all elements.
            /// </summary>
            /// <param name="attributeName"></param>
            /// <param name="newValue"></param>
            public void ReplaceAtrribute(string attributeName, string newValue)
            {
                ReplaceAtrribute(string.Empty, attributeName, new List<string> { }, newValue);
            }
    
            /// <summary>
            /// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in elements with a given name (elementName).
            /// </summary>
            /// <param name="elementName"></param>
            /// <param name="attributeName"></param>
            /// <param name="newValue"></param>
            public void ReplaceAtrribute(string elementName, string attributeName, string newValue)
            {
                ReplaceAtrribute(elementName, attributeName, new List<string> { }, newValue);
            }
    
    
            /// <summary>
            /// Replaces values of all attributes of a given name (attributeName) and value (oldValue)  
            /// with the specified new value (newValue) in elements with a given name (elementName).
            /// </summary>
            /// <param name="elementName"></param>
            /// <param name="attributeName"></param>
            /// <param name="oldValue"></param>
            /// <param name="newValue"></param>
            public void ReplaceAtrribute(string elementName, string attributeName, string oldValue, string newValue)
            {
                ReplaceAtrribute(elementName, attributeName, new List<string> { oldValue }, newValue);              
            }
    
    
            /// <summary>
            /// Replaces values of all attributes of a given name (attributeName), which has one of a list of values (oldValues), 
            /// with the specified new value (newValue) in elements with a given name (elementName).
            /// If oldValues is empty then oldValues will be ignored.
            /// </summary>
            /// <param name="elementName"></param>
            /// <param name="attributeName"></param>
            /// <param name="oldValues"></param>
            /// <param name="newValue"></param>
            public void ReplaceAtrribute(string elementName, string attributeName, List<string> oldValues, string newValue)
            {
                List<XElement> elements = _XML_Doc.Elements().Descendants().ToList();
    
                foreach (XElement element in elements)
                {
                    if (elementName == string.Empty | element.Name.LocalName.ToString() == elementName)
                    {
                        if (element.Attribute(attributeName) != null)
                        {
    
                            if (oldValues.Count == 0 || oldValues.Contains(element.Attribute(attributeName).Value))
                            { element.Attribute(attributeName).Value = newValue; }
                        }
                    }
                }
    
            }
    
            public void SaveChangesToFile()
            {
                _XML_Doc.Save(_FilePath);
            }
    
        }
    }
    

    Django MEDIA_URL and MEDIA_ROOT

    Please read the official Django DOC carefully and you will find the most fit answer.

    The best and easist way to solve this is like below.

    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns = patterns('',
        # ... the rest of your URLconf goes here ...
    ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    Execute PHP scripts within Node.js web server

    Take a look here: https://github.com/davidcoallier/node-php

    From their read me:

    Inline PHP Server Running on Node.js

    Be worried, be very worried. The name NodePHP takes its name from the fact that we are effectively turning a nice Node.js server into a FastCGI interface that interacts with PHP-FPM.

    This is omega-alpha-super-beta-proof-of-concept but it already runs a few simple scripts. Mostly done for my talks on Node.js for PHP Developers this turns out to be quite an interesting project that we are most likely be going to use with Orchestra when we decide to release our Inline PHP server that allows people to run PHP without Apache, Nginx or any webserver.

    Yes this goes against all ideas and concepts of Node.js but the idea is to be able to create a web-server directly from any working directory to allow developers to get going even faster than it was before. No need to create vhosts or server blocks ore modify your /etc/hosts anymore.

    How to Update/Drop a Hive Partition?

    Alter table table_name drop partition (partition_name);
    

    How to sort alphabetically while ignoring case sensitive?

    Example using Collections and ArrayList:

    Develop an intern static class like the example "CompareStrings".

    Call the intern static class in the main method.

    Easy to understand and works fine!

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    
    public class MainClass {
        public static void main(String[] args) {
            ArrayList<String> myArray = new ArrayList<String>();
            myArray.add("zzz");
            myArray.add("xxx");
            myArray.add("Aaa");
            myArray.add("bb");
            myArray.add("BB");
            Collections.sort(myArray, new MainClass.CompareStrings());
            for(String s : myArray) {
                System.out.println(s);
            }
        }
    
        public static class CompareStrings implements Comparator<String> {
            @Override
            public int compare(String s1, String s2) {
               return s1.compareToIgnoreCase(s2);
            }
        }
    }
    

    How do I check out a specific version of a submodule using 'git submodule'?

    Submodule repositories stay in a detached HEAD state pointing to a specific commit. Changing that commit simply involves checking out a different tag or commit then adding the change to the parent repository.

    $ cd submodule
    $ git checkout v2.0
    Previous HEAD position was 5c1277e... bumped version to 2.0.5
    HEAD is now at f0a0036... version 2.0
    

    git-status on the parent repository will now report a dirty tree:

    # On branch dev [...]
    #
    #   modified:   submodule (new commits)
    

    Add the submodule directory and commit to store the new pointer.

    What is the difference between a heuristic and an algorithm?

    Heuristic, in a nutshell is an "Educated guess". Wikipedia explains it nicely. At the end, a "general acceptance" method is taken as an optimal solution to the specified problem.

    Heuristic is an adjective for experience-based techniques that help in problem solving, learning and discovery. A heuristic method is used to rapidly come to a solution that is hoped to be close to the best possible answer, or 'optimal solution'. Heuristics are "rules of thumb", educated guesses, intuitive judgments or simply common sense. A heuristic is a general way of solving a problem. Heuristics as a noun is another name for heuristic methods.

    In more precise terms, heuristics stand for strategies using readily accessible, though loosely applicable, information to control problem solving in human beings and machines.

    While an algorithm is a method containing finite set of instructions used to solving a problem. The method has been proven mathematically or scientifically to work for the problem. There are formal methods and proofs.

    Heuristic algorithm is an algorithm that is able to produce an acceptable solution to a problem in many practical scenarios, in the fashion of a general heuristic, but for which there is no formal proof of its correctness.

    Array.push() if does not exist?

    someArray = [{a: 'a1 value', b: {c: "c1 value"},
                 {a: 'a2 value', b: {c: "c2 value"}]
    newObject = {a: 'a2 value', b: {c: "c2 value"}}
    
    //New object which needs check for duplicity
    
    let isExists = checkForExists(newObject) {
        return someArray.some(function(el) {
            return el.a === newObject.a && el.b.c === newObject.b.c;
        });
    }
    // write your logic here 
    // if isExists is true then already object in an array else you can add
    

    How do I get a string format of the current date time, in python?

    #python3
    
    import datetime
    print(
        '1: test-{date:%Y-%m-%d_%H:%M:%S}.txt'.format( date=datetime.datetime.now() )
        )
    
    d = datetime.datetime.now()
    print( "2a: {:%B %d, %Y}".format(d))
    
    # see the f" to tell python this is a f string, no .format
    print(f"2b: {d:%B %d, %Y}")
    
    print(f"3: Today is {datetime.datetime.now():%Y-%m-%d} yay")
    

    1: test-2018-02-14_16:40:52.txt

    2a: March 04, 2018

    2b: March 04, 2018

    3: Today is 2018-11-11 yay


    Description:

    Using the new string format to inject value into a string at placeholder {}, value is the current time.

    Then rather than just displaying the raw value as {}, use formatting to obtain the correct date format.

    https://docs.python.org/3/library/string.html#formatexamples

    Setting up Gradle for api 26 (Android)

    you must add in your MODULE-LEVEL build.gradle file with:

    //module-level build.gradle file
    repositories {
        maven {
            url 'https://maven.google.com'
    
        }
    }
    

    see: Google's Maven repository

    I have observed that when I use Android Studio 2.3.3 I MUST add repositories{maven{url 'https://maven.google.com'}} in MODULE-LEVEL build.gradle. In the case of Android Studio 3.0.0 there is no need for the addition in module-level build.gradle. It is enough the addition in project-level build.gradle which has been referred to in the other posts here, namely:

    //project-level build.gradle file
    allprojects {
     repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
      }
    }
    

    UPDATE 11-14-2017: The solution, that I present, was valid when I did the post. Since then, there have been various updates (even with respect to the site I refer to), and I do not know if now is valid. For one month I did my work depending on the solution above, until I upgraded to Android Studio 3.0.0

    Execute script after specific delay using JavaScript

    Just to add to what everyone else have said about setTimeout: If you want to call a function with a parameter in the future, you need to set up some anonymous function calls.

    You need to pass the function as an argument for it to be called later. In effect this means without brackets behind the name. The following will call the alert at once, and it will display 'Hello world':

    var a = "world";
    setTimeout(alert("Hello " + a), 2000);
    

    To fix this you can either put the name of a function (as Flubba has done) or you can use an anonymous function. If you need to pass a parameter, then you have to use an anonymous function.

    var a = "world";
    setTimeout(function(){alert("Hello " + a)}, 2000);
    a = "Stack Overflow";
    

    But if you run that code you will notice that after 2 seconds the popup will say 'Hello Stack Overflow'. This is because the value of the variable a has changed in those two seconds. To get it to say 'Hello world' after two seconds, you need to use the following code snippet:

    function callback(a){
        return function(){
            alert("Hello " + a);
        }
    }
    var a = "world";
    setTimeout(callback(a), 2000);
    a = "Stack Overflow";
    

    It will wait 2 seconds and then popup 'Hello world'.

    How to Use Content-disposition for force a file to download to the hard drive?

    With recent browsers you can use the HTML5 download attribute as well:

    <a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a>
    

    It is supported by most of the recent browsers except MSIE11. You can use a polyfill, something like this (note that this is for data uri only, but it is a good start):

    (function (){
    
        addEvent(window, "load", function (){
            if (isInternetExplorer())
                polyfillDataUriDownload();
        });
    
        function polyfillDataUriDownload(){
            var links = document.querySelectorAll('a[download], area[download]');
            for (var index = 0, length = links.length; index<length; ++index) {
                (function (link){
                    var dataUri = link.getAttribute("href");
                    var fileName = link.getAttribute("download");
                    if (dataUri.slice(0,5) != "data:")
                        throw new Error("The XHR part is not implemented here.");
                    addEvent(link, "click", function (event){
                        cancelEvent(event);
                        try {
                            var dataBlob = dataUriToBlob(dataUri);
                            forceBlobDownload(dataBlob, fileName);
                        } catch (e) {
                            alert(e)
                        }
                    });
                })(links[index]);
            }
        }
    
        function forceBlobDownload(dataBlob, fileName){
            window.navigator.msSaveBlob(dataBlob, fileName);
        }
    
        function dataUriToBlob(dataUri) {
            if  (!(/base64/).test(dataUri))
                throw new Error("Supports only base64 encoding.");
            var parts = dataUri.split(/[:;,]/),
                type = parts[1],
                binData = atob(parts.pop()),
                mx = binData.length,
                uiArr = new Uint8Array(mx);
            for(var i = 0; i<mx; ++i)
                uiArr[i] = binData.charCodeAt(i);
            return new Blob([uiArr], {type: type});
        }
    
        function addEvent(subject, type, listener){
            if (window.addEventListener)
                subject.addEventListener(type, listener, false);
            else if (window.attachEvent)
                subject.attachEvent("on" + type, listener);
        }
    
        function cancelEvent(event){
            if (event.preventDefault)
                event.preventDefault();
            else
                event.returnValue = false;
        }
    
        function isInternetExplorer(){
            return /*@cc_on!@*/false || !!document.documentMode;
        }
        
    })();
    

    How to Convert an int to a String?

    You can use

    text_Rate.setText(""+sdRate);
    

    Easy way to concatenate two byte arrays

    For two or multiple arrays, this simple and clean utility method can be used:

    /**
     * Append the given byte arrays to one big array
     *
     * @param arrays The arrays to append
     * @return The complete array containing the appended data
     */
    public static final byte[] append(final byte[]... arrays) {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        if (arrays != null) {
            for (final byte[] array : arrays) {
                if (array != null) {
                    out.write(array, 0, array.length);
                }
            }
        }
        return out.toByteArray();
    }
    

    How to use localization in C#

    It's quite simple, actually. Create a new resource file, for example Strings.resx. Set Access Modifier to Public. Use the apprioriate file template, so Visual Studio will automatically generate an accessor class (the name will be Strings, in this case). This is your default language.

    Now, when you want to add, say, German localization, add a localized resx file. This will be typically Strings.de.resx in this case. If you want to add additional localization for, say, Austria, you'll additionally create a Strings.de-AT.resx.

    Now go create a string - let's say a string with the name HelloWorld. In your Strings.resx, add this string with the value "Hello, world!". In Strings.de.resx, add "Hallo, Welt!". And in Strings.de-AT.resx, add "Servus, Welt!". That's it so far.

    Now you have this generated Strings class, and it has a property with a getter HelloWorld. Getting this property will load "Servus, Welt!" when your locale is de-AT, "Hallo, Welt! when your locale is any other de locale (including de-DE and de-CH), and "Hello, World!" when your locale is anything else. If a string is missing in the localized version, the resource manager will automatically walk up the chain, from the most specialized to the invariant resource.

    You can use the ResourceManager class for more control about how exactly you are loading things. The generated Strings class uses it as well.

    Get current AUTO_INCREMENT value for any table

    If you just want to know the number, rather than get it in a query then you can use:

    SHOW CREATE TABLE tablename;
    

    You should see the auto_increment at the bottom

    Add new row to dataframe, at specific row-index, not appended?

    for example you want to add rows of variable 2 to variable 1 of a data named "edges" just do it like this

    allEdges <- data.frame(c(edges$V1,edges$V2))
    

    How do you upload a file to a document library in sharepoint?

    I used this article to allow to c# to access to a sharepoint site.

    http://www.thesharepointguide.com/access-office-365-using-a-console-application/

    Basically you create a ClientId and ClientSecret keys to access to the site with c#

    Hope this can help you!

    how do I change text in a label with swift?

    Swift uses the same cocoa-touch API. You can call all the same methods, but they will use Swift's syntax. In this example you can do something like this:

    self.simpleLabel.text = "message"
    

    Note the setText method isn't available. Setting the label's text with = will automatically call the setter in swift.

    In plain English, what does "git reset" do?

    Remember that in git you have:

    • the HEAD pointer, which tells you what commit you're working on
    • the working tree, which represents the state of the files on your system
    • the staging area (also called the index), which "stages" changes so that they can later be committed together

    Please include detailed explanations about:

    --hard, --soft and --merge;

    In increasing order of dangerous-ness:

    • --soft moves HEAD but doesn't touch the staging area or the working tree.
    • --mixed moves HEAD and updates the staging area, but not the working tree.
    • --merge moves HEAD, resets the staging area, and tries to move all the changes in your working tree into the new working tree.
    • --hard moves HEAD and adjusts your staging area and working tree to the new HEAD, throwing away everything.

    concrete use cases and workflows;

    • Use --soft when you want to move to another commit and patch things up without "losing your place". It's pretty rare that you need this.

    --

    # git reset --soft example
    touch foo                            // Add a file, make some changes.
    git add foo                          // 
    git commit -m "bad commit message"   // Commit... D'oh, that was a mistake!
    git reset --soft HEAD^               // Go back one commit and fix things.
    git commit -m "good commit"          // There, now it's right.
    

    --

    • Use --mixed (which is the default) when you want to see what things look like at another commit, but you don't want to lose any changes you already have.

    • Use --merge when you want to move to a new spot but incorporate the changes you already have into that the working tree.

    • Use --hard to wipe everything out and start a fresh slate at the new commit.

    How to view log output using docker-compose run?

    1. use the command to start containers in detached mode: docker-compose up -d
    2. to view the containers use: docker ps
    3. to view logs for a container: docker logs <containerid>

    Git Cherry-Pick and Conflicts

    Do, I need to resolve all the conflicts before proceeding to next cherry -pick

    Yes, at least with the standard git setup. You cannot cherry-pick while there are conflicts.

    Furthermore, in general conflicts get harder to resolve the more you have, so it's generally better to resolve them one by one.

    That said, you can cherry-pick multiple commits at once, which would do what you are asking for. See e.g. How to cherry-pick multiple commits . This is useful if for example some commits undo earlier commits. Then you'd want to cherry-pick all in one go, so you don't have to resolve conflicts for changes that are undone by later commits.

    Further, is it suggested to do cherry-pick or branch merge in this case?

    Generally, if you want to keep a feature branch up to date with main development, you just merge master -> feature branch. The main advantage is that a later merge feature branch -> master will be much less painful.

    Cherry-picking is only useful if you must exclude some changes in master from your feature branch. Still, this will be painful so I'd try to avoid it.

    Python regex for integer?

    I prefer ^[-+]?([1-9]\d*|0)$ because ^[-+]?[0-9]+$ allows the string starting with 0.

    RE_INT = re.compile(r'^[-+]?([1-9]\d*|0)$')
    
    
    class TestRE(unittest.TestCase):
        def test_int(self):
            self.assertFalse(RE_INT.match('+'))
            self.assertFalse(RE_INT.match('-'))
    
            self.assertTrue(RE_INT.match('1'))
            self.assertTrue(RE_INT.match('+1'))
            self.assertTrue(RE_INT.match('-1'))
            self.assertTrue(RE_INT.match('0'))
            self.assertTrue(RE_INT.match('+0'))
            self.assertTrue(RE_INT.match('-0'))
    
            self.assertTrue(RE_INT.match('11'))
            self.assertFalse(RE_INT.match('00'))
            self.assertFalse(RE_INT.match('01'))
            self.assertTrue(RE_INT.match('+11'))
            self.assertFalse(RE_INT.match('+00'))
            self.assertFalse(RE_INT.match('+01'))
            self.assertTrue(RE_INT.match('-11'))
            self.assertFalse(RE_INT.match('-00'))
            self.assertFalse(RE_INT.match('-01'))
    
            self.assertTrue(RE_INT.match('1234567890'))
            self.assertTrue(RE_INT.match('+1234567890'))
            self.assertTrue(RE_INT.match('-1234567890'))
    

    How to get the list of all database users

    Whenever you 'see' something in the GUI (SSMS) and you're like "that's what I need", you can always run Sql Profiler to fish for the query that was used.

    Run Sql Profiler. Attach it to your database of course.

    Then right click in the GUI (in SSMS) and click "Refresh".
    And then go see what Profiler "catches".

    I got the below when I was in MyDatabase / Security / Users and clicked "refresh" on the "Users".

    Again, I didn't come up with the WHERE clause and the LEFT OUTER JOIN, it was a part of the SSMS query. And this query is something that somebody at Microsoft has written (you know, the peeps who know the product inside and out, aka, the experts), so they are familiar with all the weird "flags" in the database.

    But the SSMS/GUI -> Sql Profiler tricks works in many scenarios.

    SELECT
    u.name AS [Name],
    'Server[@Name=' + quotename(CAST(
            serverproperty(N'Servername')
           AS sysname),'''') + ']' + '/Database[@Name=' + quotename(db_name(),'''') + ']' + '/User[@Name=' + quotename(u.name,'''') + ']' AS [Urn],
    u.create_date AS [CreateDate],
    u.principal_id AS [ID],
    CAST(CASE dp.state WHEN N'G' THEN 1 WHEN 'W' THEN 1 ELSE 0 END AS bit) AS [HasDBAccess]
    FROM
    sys.database_principals AS u
    LEFT OUTER JOIN sys.database_permissions AS dp ON dp.grantee_principal_id = u.principal_id and dp.type = 'CO'
    WHERE
    (u.type in ('U', 'S', 'G', 'C', 'K' ,'E', 'X'))
    ORDER BY
    [Name] ASC
    

    How to loop through a HashMap in JSP?

    Just the same way as you would do in normal Java code.

    for (Map.Entry<String, String> entry : countries.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        // ...
    }
    

    However, scriptlets (raw Java code in JSP files, those <% %> things) are considered a poor practice. I recommend to install JSTL (just drop the JAR file in /WEB-INF/lib and declare the needed taglibs in top of JSP). It has a <c:forEach> tag which can iterate over among others Maps. Every iteration will give you a Map.Entry back which in turn has getKey() and getValue() methods.

    Here's a basic example:

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <c:forEach items="${map}" var="entry">
        Key = ${entry.key}, value = ${entry.value}<br>
    </c:forEach>
    

    Thus your particular issue can be solved as follows:

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <select name="country">
        <c:forEach items="${countries}" var="country">
            <option value="${country.key}">${country.value}</option>
        </c:forEach>
    </select>
    

    You need a Servlet or a ServletContextListener to place the ${countries} in the desired scope. If this list is supposed to be request-based, then use the Servlet's doGet():

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> countries = MainUtils.getCountries();
        request.setAttribute("countries", countries);
        request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
    }
    

    Or if this list is supposed to be an application-wide constant, then use ServletContextListener's contextInitialized() so that it will be loaded only once and kept in memory:

    public void contextInitialized(ServletContextEvent event) {
        Map<String, String> countries = MainUtils.getCountries();
        event.getServletContext().setAttribute("countries", countries);
    }
    

    In both cases the countries will be available in EL by ${countries}.

    Hope this helps.

    See also:

    How to validate numeric values which may contain dots or commas?

    Shortest regexp I know (16 char)

    ^\d\d?[,.]\d\d?$
    

    The ^ and $ means begin and end of input string (without this part 23.45 of string like 123.45 will be matched). The \d means digit, the \d? means optional digit, the [,.] means dot or comma. Working example (when you click on left menu> tools> code generator you can gen code for one of 9 popular languages like c#, js, php, java, ...) here.

    _x000D_
    _x000D_
    // TEST
    [
      // valid
      '11,11',   
      '11.11',
      '1.1',
      '1,1',
      // nonvalid
      '111,1',
      '11.111',
      '11-11',
      ',11',
      '11.',
      'a.11',
      '11,a',
    ].forEach(n=> {
      let result = /^\d\d?[,.]\d\d?$/.test(n);
      console.log(`${n}`.padStart(6,' '), 'is valid:', result);
    })
    _x000D_
    _x000D_
    _x000D_

    How do I send a cross-domain POST request via JavaScript?

    I think the best way is to use XMLHttpRequest (e.g. $.ajax(), $.post() in jQuery) with one of Cross-Origin Resource Sharing polyfills https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#wiki-CORS

    How to get your Netbeans project into Eclipse

    There's a very easy way if you were using a web application just follow this link.

    just do in eclipse :

    File > import > web > war file
    

    Then select the war file of your app :)) very easy !!

    How to add data to DataGridView

    LINQ is a "query" language (thats the Q), so modifying data is outside its scope.

    That said, your DataGridView is presumably bound to an ItemsSource, perhaps of type ObservableCollection<T> or similar. In that case, just do something like X.ToList().ForEach(yourGridSource.Add) (this might have to be adapted based on the type of source in your grid).

    Regex to match words of a certain length

    I think you want \b\w{1,10}\b. The \b matches a word boundary.

    Of course, you could also replace the \b and do ^\w{1,10}$. This will match a word of at most 10 characters as long as its the only contents of the string. I think this is what you were doing before.

    Since it's Java, you'll actually have to escape the backslashes: "\\b\\w{1,10}\\b". You probably knew this already, but it's gotten me before.

    Compile to stand alone exe for C# app in Visual Studio 2010

    Press the start button in visual studio. Then go to the location where your solution is stored and open the folder of your main project then the bin folder. If your application was running in debug mode then go to the debug folder. If running in release mode then go to the release folder. You should find your exe there.

    Convert generator object to list for debugging

    Simply call list on the generator.

    lst = list(gen)
    lst
    

    Be aware that this affects the generator which will not return any further items.

    You also cannot directly call list in IPython, as it conflicts with a command for listing lines of code.

    Tested on this file:

    def gen():
        yield 1
        yield 2
        yield 3
        yield 4
        yield 5
    import ipdb
    ipdb.set_trace()
    
    g1 = gen()
    
    text = "aha" + "bebe"
    
    mylst = range(10, 20)
    

    which when run:

    $ python code.py 
    > /home/javl/sandbox/so/debug/code.py(10)<module>()
          9 
    ---> 10 g1 = gen()
         11 
    
    ipdb> n
    > /home/javl/sandbox/so/debug/code.py(12)<module>()
         11 
    ---> 12 text = "aha" + "bebe"
         13 
    
    ipdb> lst = list(g1)
    ipdb> lst
    [1, 2, 3, 4, 5]
    ipdb> q
    Exiting Debugger.
    

    General method for escaping function/variable/debugger name conflicts

    There are debugger commands p and pp that will print and prettyprint any expression following them.

    So you could use it as follows:

    $ python code.py 
    > /home/javl/sandbox/so/debug/code.py(10)<module>()
          9 
    ---> 10 g1 = gen()
         11 
    
    ipdb> n
    > /home/javl/sandbox/so/debug/code.py(12)<module>()
         11 
    ---> 12 text = "aha" + "bebe"
         13 
    
    ipdb> p list(g1)
    [1, 2, 3, 4, 5]
    ipdb> c
    

    There is also an exec command, called by prefixing your expression with !, which forces debugger to take your expression as Python one.

    ipdb> !list(g1)
    []
    

    For more details see help p, help pp and help exec when in debugger.

    ipdb> help exec
    (!) statement
    Execute the (one-line) statement in the context of
    the current stack frame.
    The exclamation point can be omitted unless the first word
    of the statement resembles a debugger command.
    To assign to a global variable you must always prefix the
    command with a 'global' command, e.g.:
    (Pdb) global list_options; list_options = ['-l']
    

    HQL "is null" And "!= null" on an Oracle column

    If you do want to use null values with '=' or '<>' operators you may find the

    answer from @egallardo hier

    very useful.

    Short example for '=': The expression

    WHERE t.field = :param
    

    you refactor like this

    WHERE ((:param is null and t.field is null) or t.field = :param)
    

    Now you can set the parameter param either to some non-null value or to null:

    query.setParameter("param", "Hello World"); // Works
    query.setParameter("param", null);          // Works also
    

    program cant start because php5.dll is missing

    Download php5.dll (http://windows.php.net/download/) and copy it to apache/bin folder. That solved it for me (Win 7 64 bit apache 32 bit)

    EDIT: Start with the non-thread safe version.

    state machines tutorials

    State machines are not something that inherently needs a tutorial to be explained or even used. What I suggest is that you take a look at the data and how it needs to be parsed.

    For example, I had to parse the data protocol for a Near Space balloon flight computer, it stored data on the SD card in a specific format (binary) which needed to be parsed out into a comma seperated file. Using a state machine for this makes the most sense because depending on what the next bit of information is we need to change what we are parsing.

    The code is written using C++, and is available as ParseFCU. As you can see, it first detects what version we are parsing, and from there it enters two different state machines.

    It enters the state machine in a known-good state, at that point we start parsing and depending on what characters we encounter we either move on to the next state, or go back to a previous state. This basically allows the code to self-adapt to the way the data is stored and whether or not certain data exists at all even.

    In my example, the GPS string is not a requirement for the flight computer to log, so processing of the GPS string may be skipped over if the ending bytes for that single log write is found.

    State machines are simple to write, and in general I follow the rule that it should flow. Input going through the system should flow with certain ease from state to state.

    What is the difference between ndarray and array in numpy?

    numpy.ndarray() is a class, while numpy.array() is a method / function to create ndarray.

    In numpy docs if you want to create an array from ndarray class you can do it with 2 ways as quoted:

    1- using array(), zeros() or empty() methods: Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)) for instantiating an array.

    2- from ndarray class directly: There are two modes of creating an array using __new__: If buffer is None, then only shape, dtype, and order are used. If buffer is an object exposing the buffer interface, then all keywords are interpreted.

    The example below gives a random array because we didn't assign buffer value:

    np.ndarray(shape=(2,2), dtype=float, order='F', buffer=None)
    
    array([[ -1.13698227e+002,   4.25087011e-303],
           [  2.88528414e-306,   3.27025015e-309]])         #random
    

    another example is to assign array object to the buffer example:

    >>> np.ndarray((2,), buffer=np.array([1,2,3]),
    ...            offset=np.int_().itemsize,
    ...            dtype=int) # offset = 1*itemsize, i.e. skip first element
    array([2, 3])
    

    from above example we notice that we can't assign a list to "buffer" and we had to use numpy.array() to return ndarray object for the buffer

    Conclusion: use numpy.array() if you want to make a numpy.ndarray() object"

    assembly to compare two numbers

    input password program
    .modle small
    .stack 100h
    .data
    s pasword db 34
    input pasword db "enter pasword","$"
    valid db ?
    invalid db?
    .code
    mov ax, @ data 
    mov db, ax
    mov ah,09h
    mov dx, offest s pasword
    int 21h
    mov ah, 01h
    cmp al, s pasword
    je v
    jmp nv
    v:
    mov ah, 09h
    mov dx, offset valid 
    int 21h
    nv:
    mov ah, 09h
    mov dx, offset invalid 
    int 21h
    mov ah, 04ch 
    int 21
    end 
    

    Hiding user input on terminal in Linux script

    Just supply -s to your read call like so:

    $ read -s PASSWORD
    $ echo $PASSWORD
    

    How can I replace text with CSS?

    Example

    <!DOCTYPE html>
    <html> 
    <head> 
       <title>Devnote</title>
        <style>
            .replacedValue { 
                visibility: hidden; 
                position: relative; 
            } 
            .replacedValue:after { 
                visibility: visible; 
                position: absolute; 
                top: 0; 
                left: 0; 
                content: "Devnote is developer answer solve. devnote.in"; 
            } 
        </style> 
    </head>
    <body> 
        <p class="replacedValue">Old Text Here</p>
    </body> 
    </html>
    

    Output

    Devnote is developer answer solve. devnote.in
    

    Add items in array angular 4

    Yes there is a way to do it.

    First declare a class.

    //anyfile.ts
    export class Custom
    {
      name: string, 
      empoloyeeID: number
    }
    

    Then in your component import the class

    import {Custom} from '../path/to/anyfile.ts'
    .....
    export class FormComponent implements OnInit {
     name: string;
     empoloyeeID : number;
     empList: Array<Custom> = [];
     constructor() {
    
     }
    
     ngOnInit() {
     }
     onEmpCreate(){
       //console.log(this.name,this.empoloyeeID);
       let customObj = new Custom();
       customObj.name = "something";
       customObj.employeeId = 12; 
       this.empList.push(customObj);
       this.name ="";
       this.empoloyeeID = 0; 
     }
    }
    

    Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html

    Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2

    gnuplot : plotting data from multiple input files in a single graph

    You may find that gnuplot's for loops are useful in this case, if you adjust your filenames or graph titles appropriately.

    e.g.

    filenames = "first second third fourth fifth"
    plot for [file in filenames] file."dat" using 1:2 with lines
    

    and

    filename(n) = sprintf("file_%d", n)
    plot for [i=1:10] filename(i) using 1:2 with lines
    

    how to move elasticsearch data from one server to another

    The selected answer makes it sound slightly more complex than it is, the following is what you need (install npm first on your system).

    npm install -g elasticdump
    elasticdump --input=http://mysrc.com:9200/my_index --output=http://mydest.com:9200/my_index --type=mapping
    elasticdump --input=http://mysrc.com:9200/my_index --output=http://mydest.com:9200/my_index --type=data
    

    You can skip the first elasticdump command for subsequent copies if the mappings remain constant.

    I have just done a migration from AWS to Qbox.io with the above without any problems.

    More details over at:

    https://www.npmjs.com/package/elasticdump

    Help page (as of Feb 2016) included for completeness:

    elasticdump: Import and export tools for elasticsearch
    
    Usage: elasticdump --input SOURCE --output DESTINATION [OPTIONS]
    
    --input
                        Source location (required)
    --input-index
                        Source index and type
                        (default: all, example: index/type)
    --output
                        Destination location (required)
    --output-index
                        Destination index and type
                        (default: all, example: index/type)
    --limit
                        How many objects to move in bulk per operation
                        limit is approximate for file streams
                        (default: 100)
    --debug
                        Display the elasticsearch commands being used
                        (default: false)
    --type
                        What are we exporting?
                        (default: data, options: [data, mapping])
    --delete
                        Delete documents one-by-one from the input as they are
                        moved.  Will not delete the source index
                        (default: false)
    --searchBody
                        Preform a partial extract based on search results
                        (when ES is the input,
                        (default: '{"query": { "match_all": {} } }'))
    --sourceOnly
                        Output only the json contained within the document _source
                        Normal: {"_index":"","_type":"","_id":"", "_source":{SOURCE}}
                        sourceOnly: {SOURCE}
                        (default: false)
    --all
                        Load/store documents from ALL indexes
                        (default: false)
    --bulk
                        Leverage elasticsearch Bulk API when writing documents
                        (default: false)
    --ignore-errors
                        Will continue the read/write loop on write error
                        (default: false)
    --scrollTime
                        Time the nodes will hold the requested search in order.
                        (default: 10m)
    --maxSockets
                        How many simultaneous HTTP requests can we process make?
                        (default:
                          5 [node <= v0.10.x] /
                          Infinity [node >= v0.11.x] )
    --bulk-mode
                        The mode can be index, delete or update.
                        'index': Add or replace documents on the destination index.
                        'delete': Delete documents on destination index.
                        'update': Use 'doc_as_upsert' option with bulk update API to do partial update.
                        (default: index)
    --bulk-use-output-index-name
                        Force use of destination index name (the actual output URL)
                        as destination while bulk writing to ES. Allows
                        leveraging Bulk API copying data inside the same
                        elasticsearch instance.
                        (default: false)
    --timeout
                        Integer containing the number of milliseconds to wait for
                        a request to respond before aborting the request. Passed
                        directly to the request library. If used in bulk writing,
                        it will result in the entire batch not being written.
                        Mostly used when you don't care too much if you lose some
                        data when importing but rather have speed.
    --skip
                        Integer containing the number of rows you wish to skip
                        ahead from the input transport.  When importing a large
                        index, things can go wrong, be it connectivity, crashes,
                        someone forgetting to `screen`, etc.  This allows you
                        to start the dump again from the last known line written
                        (as logged by the `offset` in the output).  Please be
                        advised that since no sorting is specified when the
                        dump is initially created, there's no real way to
                        guarantee that the skipped rows have already been
                        written/parsed.  This is more of an option for when
                        you want to get most data as possible in the index
                        without concern for losing some rows in the process,
                        similar to the `timeout` option.
    --inputTransport
                        Provide a custom js file to us as the input transport
    --outputTransport
                        Provide a custom js file to us as the output transport
    --toLog
                        When using a custom outputTransport, should log lines
                        be appended to the output stream?
                        (default: true, except for `$`)
    --help
                        This page
    
    Examples:
    
    # Copy an index from production to staging with mappings:
    elasticdump \
      --input=http://production.es.com:9200/my_index \
      --output=http://staging.es.com:9200/my_index \
      --type=mapping
    elasticdump \
      --input=http://production.es.com:9200/my_index \
      --output=http://staging.es.com:9200/my_index \
      --type=data
    
    # Backup index data to a file:
    elasticdump \
      --input=http://production.es.com:9200/my_index \
      --output=/data/my_index_mapping.json \
      --type=mapping
    elasticdump \
      --input=http://production.es.com:9200/my_index \
      --output=/data/my_index.json \
      --type=data
    
    # Backup and index to a gzip using stdout:
    elasticdump \
      --input=http://production.es.com:9200/my_index \
      --output=$ \
      | gzip > /data/my_index.json.gz
    
    # Backup ALL indices, then use Bulk API to populate another ES cluster:
    elasticdump \
      --all=true \
      --input=http://production-a.es.com:9200/ \
      --output=/data/production.json
    elasticdump \
      --bulk=true \
      --input=/data/production.json \
      --output=http://production-b.es.com:9200/
    
    # Backup the results of a query to a file
    elasticdump \
      --input=http://production.es.com:9200/my_index \
      --output=query.json \
      --searchBody '{"query":{"term":{"username": "admin"}}}'
    
    ------------------------------------------------------------------------------
    Learn more @ https://github.com/taskrabbit/elasticsearch-dump`enter code here`
    

    Import XXX cannot be resolved for Java SE standard classes

    If by chance you have deleted JRE SYSTEM LIBRARY, then go to your JRE installation and add jars from there.

    Eg:- C:\Program Files (x86)\Java\jre7\lib ---add jars from here

    C:\Program Files (x86)\Java\jre7\lib\ext ---add jars from here

    How to iterate over a JavaScript object?

    With the new ES6/ES2015 features, you don't have to use an object anymore to iterate over a hash. You can use a Map. Javascript Maps keep keys in insertion order, meaning you can iterate over them without having to check the hasOwnProperty, which was always really a hack.

    Iterate over a map:

    var myMap = new Map();
    myMap.set(0, "zero");
    myMap.set(1, "one");
    for (var [key, value] of myMap) {
      console.log(key + " = " + value);
    }
    // Will show 2 logs; first with "0 = zero" and second with "1 = one"
    
    for (var key of myMap.keys()) {
      console.log(key);
    }
    // Will show 2 logs; first with "0" and second with "1"
    
    for (var value of myMap.values()) {
      console.log(value);
    }
    // Will show 2 logs; first with "zero" and second with "one"
    
    for (var [key, value] of myMap.entries()) {
      console.log(key + " = " + value);
    }
    // Will show 2 logs; first with "0 = zero" and second with "1 = one"
    

    or use forEach:

    myMap.forEach(function(value, key) {
      console.log(key + " = " + value);
    }, myMap)
    // Will show 2 logs; first with "0 = zero" and second with "1 = one"
    

    Reading in from System.in - Java

    class myFileReaderThatStarts with arguments
    {
    
     class MissingArgumentException extends Exception{      
          MissingArgumentException(String s)
      {
         super(s);
      }
    
       }    
    public static void main(String[] args) throws MissingArgumentException
    {
    //You can test args array for value 
    if(args.length>0)
    {
        // do something with args[0]
    }
    else
    {
    // default in a path 
    // or 
       throw new MissingArgumentException("You need to start this program with a path");
    }
    }
    

    if...else within JSP or JSTL

    If you want to do the following by using JSTL Tag Libe, please follow the following steps:

    [Requirement] if a number is a grater than equal 40 and lower than 50 then display "Two digit number starting with 4" otherwise "Other numbers".

    [Solutions]

    1. Please Add the JSTL tag lib on the top of the page.`
         <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>`
    
    2. Please Write the following code
    `
    <c:choose>
           <c:when test="${params.number >=40 && params.number <50}">
                  <p> Two digit number starting with 4. </p>
           </c:when>
           <c:otherwise>
                  <p> Other numbers. </p>
           </c:otherwise>
      </c:choose>`
    

    How to Replace dot (.) in a string in Java

    Use Apache Commons Lang:

    String a= "\\*\\";
    str = StringUtils.replace(xpath, ".", a);
    

    or with standalone JDK:

    String a = "\\*\\"; // or: String a = "/*/";
    String replacement = Matcher.quoteReplacement(a);
    String searchString = Pattern.quote(".");
    String str = xpath.replaceAll(searchString, replacement);
    

    new DateTime() vs default(DateTime)

    If you want to use default value for a DateTime parameter in a method, you can only use default(DateTime).

    The following line will not compile:

        private void MyMethod(DateTime syncedTime = DateTime.MinValue)
    

    This line will compile:

        private void MyMethod(DateTime syncedTime = default(DateTime))
    

    How can I disable a specific LI element inside a UL?

    I usualy use <li> to include <a> link. I disabled click action writing like this; You may not include <a> link, then you will ignore my post.

    _x000D_
    _x000D_
    a.noclick       {_x000D_
      pointer-events: none;_x000D_
    }
    _x000D_
    <a class="noclick" href="#">this is disabled</a>
    _x000D_
    _x000D_
    _x000D_

    JRE installation directory in Windows

    In the command line you can type java -version

    Long vs Integer, long vs int, what to use and when?

    a) object Class "Long" versus primitive type "long". (At least in Java)

    b) There are different (even unclear) memory-sizes of the primitive types:

    Java - all clear: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

    • byte, char .. 1B .. 8b
    • short int .. 2B .. 16b
    • int .. .. .. .. 4B .. 32b
    • long int .. 8B .. 64b

    C .. just mess: https://en.wikipedia.org/wiki/C_data_types

    • short .. .. 16b
    • int .. .. .. 16b ... wtf?!?!
    • long .. .. 32b
    • long long .. 64b .. mess! :-/

    Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

    if you are using pycharm platform it's very simple go into view=>tool windows==>python console after that you will see in the bottom the console with [1] : type this !pip install opencv-python

    Android Studio: Gradle: error: cannot find symbol variable

    You shouldn't be importing android.R. That should be automatically generated and recognized. This question contains a lot of helpful tips if you get some error referring to R after removing the import.

    Some basic steps after removing the import, if those errors appear:

    • Clean your build, then rebuild
    • Make sure there are no errors or typos in your XML files
    • Make sure your resource names consist of [a-z0-9.]. Capitals or symbols are not allowed for some reason.
    • Perform a Gradle sync (via Tools > Android > Sync Project with Gradle Files)

    Issue with adding common code as git submodule: "already exists in the index"

    This happens if the .git file is missing in the target path. It happend to me after I executed git clean -f -d.

    I had to delete all target folders showing in the message and then executing git submodule update --remote

    How to interpret "loss" and "accuracy" for a machine learning model

    They are two different metrics to evaluate your model's performance usually being used in different phases.

    Loss is often used in the training process to find the "best" parameter values for your model (e.g. weights in neural network). It is what you try to optimize in the training by updating weights.

    Accuracy is more from an applied perspective. Once you find the optimized parameters above, you use this metrics to evaluate how accurate your model's prediction is compared to the true data.

    Let us use a toy classification example. You want to predict gender from one's weight and height. You have 3 data, they are as follows:(0 stands for male, 1 stands for female)

    y1 = 0, x1_w = 50kg, x2_h = 160cm;

    y2 = 0, x2_w = 60kg, x2_h = 170cm;

    y3 = 1, x3_w = 55kg, x3_h = 175cm;

    You use a simple logistic regression model that is y = 1/(1+exp-(b1*x_w+b2*x_h))

    How do you find b1 and b2? you define a loss first and use optimization method to minimize the loss in an iterative way by updating b1 and b2.

    In our example, a typical loss for this binary classification problem can be: (a minus sign should be added in front of the summation sign)

    We don't know what b1 and b2 should be. Let us make a random guess say b1 = 0.1 and b2 = -0.03. Then what is our loss now?

    so the loss is

    Then you learning algorithm (e.g. gradient descent) will find a way to update b1 and b2 to decrease the loss.

    What if b1=0.1 and b2=-0.03 is the final b1 and b2 (output from gradient descent), what is the accuracy now?

    Let's assume if y_hat >= 0.5, we decide our prediction is female(1). otherwise it would be 0. Therefore, our algorithm predict y1 = 1, y2 = 1 and y3 = 1. What is our accuracy? We make wrong prediction on y1 and y2 and make correct one on y3. So now our accuracy is 1/3 = 33.33%

    PS: In Amir's answer, back-propagation is said to be an optimization method in NN. I think it would be treated as a way to find gradient for weights in NN. Common optimization method in NN are GradientDescent and Adam.

    Could not resolve this reference. Could not locate the assembly

    I had the same warning in VS 2017. As it turned out in my case I had added a unit test project and needed to set a dependency for the unit test on the DLL it was testing.

    How to create an empty R vector to add new items

    I pre-allocate a vector with

    > (a <- rep(NA, 10))
     [1] NA NA NA NA NA NA NA NA NA NA
    

    You can then use [] to insert values into it.

    Fixed position but relative to container

    2019 SOLUTION: You can use position: sticky property.

    Here is an example CODEPEN demonstrating the usage and also how it differs from position: fixed.

    How it behaves is explained below:

    1. An element with sticky position is positioned based on the user's scroll position. It basically acts like position: relative until an element is scrolled beyond a specific offset, in which case it turns into position: fixed. When it is scrolled back it gets back to its previous (relative) position.

    2. It effects the flow of other elements in the page ie occupies a specific space on the page(just like position: relative).

    3. If it is defined inside some container, it is positioned with respect to that container. If the container has some overflow(scroll), depending on the scroll offset it turns into position:fixed.

    So if you want to achieve the fixed functionality but inside a container, use sticky.

    How to make circular background using css?

    Keep it simple:

    .circle
      {
        border-radius: 50%;
        width: 200px;
        height: 200px; 
      }
    

    Width and height can be anything, as long as they're equal

    Comparison of C++ unit test frameworks

    Wikipedia has a comprehensive list of unit testing frameworks, with tables that identify features supported or not.

    Finding three elements in an array whose sum is closest to a given number

    Here is the Python3 code

    class Solution:
        def threeSumClosest(self, nums: List[int], target: int) -> int:
            result = set()
            nums.sort()
            L = len(nums)     
            for i in range(L):
                if i > 0 and nums[i] == nums[i-1]:
                    continue
                for j in range(i+1,L):
                    if j > i + 1 and nums[j] == nums[j-1]:
                        continue  
                    l = j+1
                    r = L -1
                    while l <= r:
                        sum = nums[i] + nums[j] + nums[l]
                        result.add(sum)
                        l = l + 1
                        while l<=r and nums[l] == nums[l-1]:
                            l = l + 1
            result = list(result)
            min = result[0]
            for i in range(1,len(result)):
                if abs(target - result[i]) < abs(target - min):
                    min = result[i]
            return min
    

    How to debug Lock wait timeout exceeded on MySQL?

    Due to the popularity of MySQL, there's no wonder Lock wait timeout exceeded; try restarting transaction exception gets so much attention on SO.

    The more contention you have, the greater the chance of deadlocks, which a DB engine will resolve by time-outing one of the deadlocked transactions.

    Also, long-running transactions that have modified (e.g. UPDATE or DELETE) a large number of entries are more likely to generate conflicts with other transactions.

    Although InnoDB MVCC, you can still request explicit locks using the FOR UPDATE clause. However, unlike other popular DBs (Oracle, MSSQL, PostgreSQL, DB2), MySQL uses REPEATABLE_READ as the default isolation level.

    Now, the locks that you acquired (either by modifying rows or using explicit locking), are held for the duration of the currently running transaction. If you want a good explanation of the difference between REPEATABLE_READ and READ COMMITTED in regards to locking, please read this Percona article.

    In REPEATABLE READ every lock acquired during a transaction is held for the duration of the transaction.

    In READ COMMITTED the locks that did not match the scan are released after the STATEMENT completes.

    ...

    This means that in READ COMMITTED other transactions are free to update rows that they would not have been able to update (in REPEATABLE READ) once the UPDATE statement completes.

    Therefore: The more restrictive the isolation level (REPEATABLE_READ, SERIALIZABLE) the greater the chance of deadlock. This is not an issue "per se", it's a trade-off.

    You can get very good results with READ_COMMITED, as you need application-level lost update prevention when using logical transactions that span over multiple HTTP requests. The optimistic locking approach targets lost updates that might happen even if you use the SERIALIZABLE isolation level while reducing the lock contention by allowing you to use READ_COMMITED.

    Writing numerical values on the plot with Matplotlib

    You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

    import numpy
    from matplotlib import pyplot
    
    x = numpy.arange(10)
    y = numpy.array([5,3,4,2,7,5,4,6,3,2])
    
    fig = pyplot.figure()
    ax = fig.add_subplot(111)
    ax.set_ylim(0,10)
    pyplot.plot(x,y)
    for i,j in zip(x,y):
        ax.annotate(str(j),xy=(i,j))
    
    pyplot.show()
    

    If you want the annotations offset a little, you could change the annotate line to something like

    ax.annotate(str(j),xy=(i,j+0.5))
    

    Use of String.Format in JavaScript?

    Adapt the code from MsAjax string.

    Just remove all of the _validateParams code and you are most of the way to a full fledged .NET string class in JavaScript.

    Okay, I liberated the msajax string class, removing all the msajax dependencies. It Works great, just like the .NET string class, including trim functions, endsWith/startsWith, etc.

    P.S. - I left all of the Visual Studio JavaScript IntelliSense helpers and XmlDocs in place. They are innocuous if you don't use Visual Studio, but you can remove them if you like.

    <script src="script/string.js" type="text/javascript"></script>
    <script type="text/javascript">
        var a = String.format("Hello {0}!", "world");
        alert(a);
    
    </script>
    

    String.js

    // String.js - liberated from MicrosoftAjax.js on 03/28/10 by Sky Sanders
    // permalink: http://stackoverflow.com/a/2534834/2343
    
    /*
        Copyright (c) 2009, CodePlex Foundation
        All rights reserved.
    
        Redistribution and use in source and binary forms, with or without modification, are permitted
        provided that the following conditions are met:
    
        *   Redistributions of source code must retain the above copyright notice, this list of conditions
            and the following disclaimer.
    
        *   Redistributions in binary form must reproduce the above copyright notice, this list of conditions
            and the following disclaimer in the documentation and/or other materials provided with the distribution.
    
        *   Neither the name of CodePlex Foundation nor the names of its contributors may be used to endorse or
            promote products derived from this software without specific prior written permission.
    
        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED
        WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
        A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
        FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
        LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
        INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
        OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
        IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</textarea>
    */
    
    (function(window) {
    
        $type = String;
        $type.__typeName = 'String';
        $type.__class = true;
    
        $prototype = $type.prototype;
        $prototype.endsWith = function String$endsWith(suffix) {
            /// <summary>Determines whether the end of this instance matches the specified string.</summary>
            /// <param name="suffix" type="String">A string to compare to.</param>
            /// <returns type="Boolean">true if suffix matches the end of this instance; otherwise, false.</returns>
            return (this.substr(this.length - suffix.length) === suffix);
        }
    
        $prototype.startsWith = function String$startsWith(prefix) {
            /// <summary >Determines whether the beginning of this instance matches the specified string.</summary>
            /// <param name="prefix" type="String">The String to compare.</param>
            /// <returns type="Boolean">true if prefix matches the beginning of this string; otherwise, false.</returns>
            return (this.substr(0, prefix.length) === prefix);
        }
    
        $prototype.trim = function String$trim() {
            /// <summary >Removes all leading and trailing white-space characters from the current String object.</summary>
            /// <returns type="String">The string that remains after all white-space characters are removed from the start and end of the current String object.</returns>
            return this.replace(/^\s+|\s+$/g, '');
        }
    
        $prototype.trimEnd = function String$trimEnd() {
            /// <summary >Removes all trailing white spaces from the current String object.</summary>
            /// <returns type="String">The string that remains after all white-space characters are removed from the end of the current String object.</returns>
            return this.replace(/\s+$/, '');
        }
    
        $prototype.trimStart = function String$trimStart() {
            /// <summary >Removes all leading white spaces from the current String object.</summary>
            /// <returns type="String">The string that remains after all white-space characters are removed from the start of the current String object.</returns>
            return this.replace(/^\s+/, '');
        }
    
        $type.format = function String$format(format, args) {
            /// <summary>Replaces the format items in a specified String with the text equivalents of the values of   corresponding object instances. The invariant culture will be used to format dates and numbers.</summary>
            /// <param name="format" type="String">A format string.</param>
            /// <param name="args" parameterArray="true" mayBeNull="true">The objects to format.</param>
            /// <returns type="String">A copy of format in which the format items have been replaced by the   string equivalent of the corresponding instances of object arguments.</returns>
            return String._toFormattedString(false, arguments);
        }
    
        $type._toFormattedString = function String$_toFormattedString(useLocale, args) {
            var result = '';
            var format = args[0];
    
            for (var i = 0; ; ) {
                // Find the next opening or closing brace
                var open = format.indexOf('{', i);
                var close = format.indexOf('}', i);
                if ((open < 0) && (close < 0)) {
                    // Not found: copy the end of the string and break
                    result += format.slice(i);
                    break;
                }
                if ((close > 0) && ((close < open) || (open < 0))) {
    
                    if (format.charAt(close + 1) !== '}') {
                        throw new Error('format stringFormatBraceMismatch');
                    }
    
                    result += format.slice(i, close + 1);
                    i = close + 2;
                    continue;
                }
    
                // Copy the string before the brace
                result += format.slice(i, open);
                i = open + 1;
    
                // Check for double braces (which display as one and are not arguments)
                if (format.charAt(i) === '{') {
                    result += '{';
                    i++;
                    continue;
                }
    
                if (close < 0) throw new Error('format stringFormatBraceMismatch');
    
    
                // Find the closing brace
    
                // Get the string between the braces, and split it around the ':' (if any)
                var brace = format.substring(i, close);
                var colonIndex = brace.indexOf(':');
                var argNumber = parseInt((colonIndex < 0) ? brace : brace.substring(0, colonIndex), 10) + 1;
    
                if (isNaN(argNumber)) throw new Error('format stringFormatInvalid');
    
                var argFormat = (colonIndex < 0) ? '' : brace.substring(colonIndex + 1);
    
                var arg = args[argNumber];
                if (typeof (arg) === "undefined" || arg === null) {
                    arg = '';
                }
    
                // If it has a toFormattedString method, call it.  Otherwise, call toString()
                if (arg.toFormattedString) {
                    result += arg.toFormattedString(argFormat);
                }
                else if (useLocale && arg.localeFormat) {
                    result += arg.localeFormat(argFormat);
                }
                else if (arg.format) {
                    result += arg.format(argFormat);
                }
                else
                    result += arg.toString();
    
                i = close + 1;
            }
    
            return result;
        }
    
    })(window);
    

    How to access the elements of a function's return array?

    I think the best way to do it is to create a global var array. Then do whatever you want to it inside the function data by passing it as a reference. No need to return anything too.

    $array = array("white", "black", "yellow");
    echo $array[0]; //this echo white
    data($array);
    
    function data(&$passArray){ //<<notice &
        $passArray[0] = "orange"; 
    }
    echo $array[0]; //this now echo orange
    

    Terminal Commands: For loop with echo

    jot would work too (in bash shell)

    for i in `jot 1000 1`; do echo "http://example.com/$i.jpg"; done
    

    Why do we use arrays instead of other data structures?

    For O(1) random access, which can not be beaten.

    Explain the "setUp" and "tearDown" Python methods used in test cases

    You can use these to factor out code common to all tests in the test suite.

    If you have a lot of repeated code in your tests, you can make them shorter by moving this code to setUp/tearDown.

    You might use this for creating test data (e.g. setting up fakes/mocks), or stubbing out functions with fakes.

    If you're doing integration testing, you can use check environmental pre-conditions in setUp, and skip the test if something isn't set up properly.

    For example:

    class TurretTest(unittest.TestCase):
    
        def setUp(self):
            self.turret_factory = TurretFactory()
            self.turret = self.turret_factory.CreateTurret()
    
        def test_turret_is_on_by_default(self):
            self.assertEquals(True, self.turret.is_on())
    
        def test_turret_turns_can_be_turned_off(self):
            self.turret.turn_off()
            self.assertEquals(False, self.turret.is_on())
    

    How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

    tv_nsec is the sleep time in nanoseconds. 500000us = 500000000ns, so you want:

    nanosleep((const struct timespec[]){{0, 500000000L}}, NULL);
    

    Error: Could not create the Java Virtual Machine Mac OSX Mavericks

    Unrecognized option: - Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit.

    I was getting this Error due to incorrect syntax using in the terminal. I was using java - version. But its actually is java -version. there is no space between - and version. you can also cross check by using java -help.

    i hope this will help.

    /bin/sh: apt-get: not found

    The image you're using is Alpine based, so you can't use apt-get because it's Ubuntu's package manager.

    To fix this just use:

    apk update and apk add

    Best way to compare 2 XML documents in Java

    The latest version of XMLUnit can help the job of asserting two XML are equal. Also XMLUnit.setIgnoreWhitespace() and XMLUnit.setIgnoreAttributeOrder() may be necessary to the case in question.

    See working code of a simple example of XML Unit use below.

    import org.custommonkey.xmlunit.DetailedDiff;
    import org.custommonkey.xmlunit.XMLUnit;
    import org.junit.Assert;
    
    public class TestXml {
    
        public static void main(String[] args) throws Exception {
            String result = "<abc             attr=\"value1\"                title=\"something\">            </abc>";
            // will be ok
            assertXMLEquals("<abc attr=\"value1\" title=\"something\"></abc>", result);
        }
    
        public static void assertXMLEquals(String expectedXML, String actualXML) throws Exception {
            XMLUnit.setIgnoreWhitespace(true);
            XMLUnit.setIgnoreAttributeOrder(true);
    
            DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expectedXML, actualXML));
    
            List<?> allDifferences = diff.getAllDifferences();
            Assert.assertEquals("Differences found: "+ diff.toString(), 0, allDifferences.size());
        }
    
    }
    

    If using Maven, add this to your pom.xml:

    <dependency>
        <groupId>xmlunit</groupId>
        <artifactId>xmlunit</artifactId>
        <version>1.4</version>
    </dependency>
    

    How to generate a random String in Java

    This is very nice:

    http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RandomStringUtils.html - something like RandomStringUtils.randomNumeric(7).

    There are 10^7 equiprobable (if java.util.Random is not broken) distinct values so uniqueness may be a concern.

    Android: How to rotate a bitmap on a center point

    You can use something like following:

    
    Matrix matrix = new Matrix();
    matrix.setRotate(mRotation,source.getWidth()/2,source.getHeight()/2);
    RectF rectF = new RectF(0, 0, source.getWidth(), source.getHeight());
    matrix.mapRect(rectF);
    Bitmap targetBitmap = Bitmap.createBitmap(rectF.width(), rectF.height(), config);
    Canvas canvas = new Canvas(targetBitmap);
    canvas.drawBitmap(source, matrix, new Paint());
    

    How to add a constant column in a Spark DataFrame?

    In spark 2.2 there are two ways to add constant value in a column in DataFrame:

    1) Using lit

    2) Using typedLit.

    The difference between the two is that typedLit can also handle parameterized scala types e.g. List, Seq, and Map

    Sample DataFrame:

    val df = spark.createDataFrame(Seq((0,"a"),(1,"b"),(2,"c"))).toDF("id", "col1")
    
    +---+----+
    | id|col1|
    +---+----+
    |  0|   a|
    |  1|   b|
    +---+----+
    

    1) Using lit: Adding constant string value in new column named newcol:

    import org.apache.spark.sql.functions.lit
    val newdf = df.withColumn("newcol",lit("myval"))
    

    Result:

    +---+----+------+
    | id|col1|newcol|
    +---+----+------+
    |  0|   a| myval|
    |  1|   b| myval|
    +---+----+------+
    

    2) Using typedLit:

    import org.apache.spark.sql.functions.typedLit
    df.withColumn("newcol", typedLit(("sample", 10, .044)))
    

    Result:

    +---+----+-----------------+
    | id|col1|           newcol|
    +---+----+-----------------+
    |  0|   a|[sample,10,0.044]|
    |  1|   b|[sample,10,0.044]|
    |  2|   c|[sample,10,0.044]|
    +---+----+-----------------+
    

    Android Studio shortcuts like Eclipse

    You can use Eclipse Short-cut key in Android Studio too.

    File -> Settings -> Keymap -> <Choose Eclipse from Keymaps dropdown> 
    

    For Mac OS :

    File -> Preferences or Properties -> Keymap -> <Choose Eclipse from Keymaps dropdown> 
    

    how to change the default positioning of modal in bootstrap?

    Add the following css to your html and try changing the top, right, bottom, left values.

    .modal {
       position: absolute;
       top: 10px;
       right: 100px;
       bottom: 0;
       left: 0;
       z-index: 10040;
       overflow: auto;
       overflow-y: auto;
    }
    

    What is the difference between a Docker image and a container?

    An instance of an image is called a container. You have an image, which is a set of layers as you describe. If you start this image, you have a running container of this image. You can have many running containers of the same image.

    You can see all your images with docker images whereas you can see your running containers with docker ps (and you can see all containers with docker ps -a).

    So a running instance of an image is a container.

    Show DataFrame as table in iPython Notebook

    This answer is based on the 2nd tip from this blog post: 28 Jupyter Notebook tips, tricks and shortcuts

    You can add the following code to the top of your notebook

    from IPython.core.interactiveshell import InteractiveShell
    InteractiveShell.ast_node_interactivity = "all"
    

    This tells Jupyter to print the results for any variable or statement on it’s own line. So you can then execute a cell solely containing

    df1
    df2
    

    and it will "print out the beautiful tables for both datasets".

    JavaScript closure inside loops – simple practical example

    Another way of saying it is that the i in your function is bound at the time of executing the function, not the time of creating the function.

    When you create the closure, i is a reference to the variable defined in the outside scope, not a copy of it as it was when you created the closure. It will be evaluated at the time of execution.

    Most of the other answers provide ways to work around by creating another variable that won't change the value for you.

    Just thought I'd add an explanation for clarity. For a solution, personally, I'd go with Harto's since it is the most self-explanatory way of doing it from the answers here. Any of the code posted will work, but I'd opt for a closure factory over having to write a pile of comments to explain why I'm declaring a new variable(Freddy and 1800's) or have weird embedded closure syntax(apphacker).

    Wrap a text within only two lines inside div

    Try something like this: http://jsfiddle.net/6jdj3pcL/1/

    <p>Here is a paragraph with a lot of text ...</p>
    
    p {
        line-height: 1.5em;
        height: 3em;
        overflow: hidden;
        width: 300px;
    }
    
    p::before {
       content: '...';
       float: right;
       margin-top: 1.5em;
    }