Programs & Examples On #Spyware

Spyware is software that is installed without user permission and sends personal data to an unauthorized server without user awareness.

Ignore 'Security Warning' running script from command line

To avoid warnings, you can:

Set-ExecutionPolicy bypass

How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?

Configure webpack (in webpack.config.js) with:

devServer: {
  // ...
  host: '0.0.0.0',
  port: 80,
  // ...
}

Why doesn't calling a Python string method do anything unless you assign its output?

Example for String Methods

Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list comprehension.

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
newfilenames = []
for i in filenames:
    if i.endswith(".hpp"):
        x = i.replace("hpp", "h")
        newfilenames.append(x)
    else:
        newfilenames.append(i)


print(newfilenames)
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]

Why is this error, 'Sequence contains no elements', happening?

If this is the offending line:

db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

Then it's because there is no object in Responses for which the ResponseId == item.ResponseId, and you can't get the First() record if there are no matches.

Try this instead:

var response
  = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).FirstOrDefault();

if (response != null)
{
    // take some alternative action
}
else
    temp.Response = response;

The FirstOrDefault() extension returns an objects default value if no match is found. For most objects (other than primitive types), this is null.

.Net: How do I find the .NET version?

If you open a command prompt and type the following two commands, all framework versions that are installed on the current machine will be listed (each one is stored in a separate directory within this directory).

cd %systemroot%\Microsoft.NET\Framework

dir /A:D

Creating a generic method in C#

What if you specified the default value to return, instead of using default(T)?

public static T GetQueryString<T>(string key, T defaultValue) {...}

It makes calling it easier too:

var intValue = GetQueryString("intParm", Int32.MinValue);
var strValue = GetQueryString("strParm", "");
var dtmValue = GetQueryString("dtmPatm", DateTime.Now); // eg use today's date if not specified

The downside being you need magic values to denote invalid/missing querystring values.

how to convert object into string in php

In your case, you should simply use

$firstapiOutput->document_number

as the input for the second api.

Remove all the children DOM elements in div

First of all you need to create a surface once and keep it somewhere handy. Example:

var surface = dojox.gfx.createSurface(domNode, widthInPx, heightInPx);

domNode is usually an unadorned <div>, which is used as a placeholder for a surface.

You can clear everything on the surface in one go (all existing shape objects will be invalidated, don't use them after that):

surface.clear();

All surface-related functions and methods can be found in the official documentation on dojox.gfx.Surface. Examples of use can be found in dojox/gfx/tests/.

grep without showing path/file:line

From the man page:

-h, --no-filename
    Suppress the prefixing of file names on output. This is the default when there
    is only one file (or only standard input) to search.

How do I copy a hash in Ruby?

As mentioned in Security Considerations section of Marshal documentation,

If you need to deserialize untrusted data, use JSON or another serialization format that is only able to load simple, ‘primitive’ types such as String, Array, Hash, etc.

Here is an example on how to do cloning using JSON in Ruby:

require "json"

original = {"John"=>"Adams","Thomas"=>"Jefferson","Johny"=>"Appleseed"}
cloned = JSON.parse(JSON.generate(original))

# Modify original hash
original["John"] << ' Sandler'
p original 
#=> {"John"=>"Adams Sandler", "Thomas"=>"Jefferson", "Johny"=>"Appleseed"}

# cloned remains intact as it was deep copied
p cloned  
#=> {"John"=>"Adams", "Thomas"=>"Jefferson", "Johny"=>"Appleseed"}

Read and write a text file in typescript

First you will need to install node definitions for Typescript. You can find the definitions file here:

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts

Once you've got file, just add the reference to your .ts file like this:

/// <reference path="path/to/node.d.ts" />

Then you can code your typescript class that read/writes, using the Node File System module. Your typescript class myClass.ts can look like this:

/// <reference path="path/to/node.d.ts" />

class MyClass {

    // Here we import the File System module of node
    private fs = require('fs');

    constructor() { }

    createFile() {

        this.fs.writeFile('file.txt', 'I am cool!',  function(err) {
            if (err) {
                return console.error(err);
            }
            console.log("File created!");
        });
    }

    showFile() {

        this.fs.readFile('file.txt', function (err, data) {
            if (err) {
                return console.error(err);
            }
            console.log("Asynchronous read: " + data.toString());
        });
    }
}

// Usage
// var obj = new MyClass();
// obj.createFile();
// obj.showFile();

Once you transpile your .ts file to a javascript (check out here if you don't know how to do it), you can run your javascript file with node and let the magic work:

> node myClass.js

Is Secure.ANDROID_ID unique for each device?

I've read a few things about this and unfortunately the ANDROID_ID should not be relied on for uniquely identifying an individual device.

It doesn't seem to be enforced in Android compliance requirements and so manufacturers seem to implement it the way they choose including some using it more as a 'model' ID etc.

Also, be aware that even if a manufacturer has written a generator to make it a UUID (for example), it's not guaranteed to survive a factory reset.

Dynamic loading of images in WPF

In code to load resource in the executing assembly where my image 'Freq.png' was in the folder "Icons" and defined as "Resource".

        this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/" 
             + Assembly.GetExecutingAssembly().GetName().Name 
             + ";component/" 
             + "Icons/Freq.png", UriKind.Absolute)); 

I also made a function if anybody would like it...

/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
    if (assembly == null)
    {
        assembly = Assembly.GetCallingAssembly();
    }

    if (pathInApplication[0] == '/')
    {
        pathInApplication = pathInApplication.Substring(1);
    }
    return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute)); 
}

Usage:

        this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");

Default value of function parameter

On thing to remember here is that the default param must be the last param in the function definition.

Following code will not compile:

void fun(int first, int second = 10, int third);

Following code will compile:

void fun(int first, int second, int third = 10);

How to install Anaconda on RaspBerry Pi 3 Model B

On Raspberry Pi 3 Model B - Installation of Miniconda (bundled with Python 3)

Go and get the latest version of miniconda for Raspberry Pi - made for armv7l processor and bundled with Python 3 (eg.: uname -m)

wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
md5sum Miniconda3-latest-Linux-armv7l.sh
bash Miniconda3-latest-Linux-armv7l.sh

After installation, source your updated .bashrc file with source ~/.bashrc. Then enter the command python --version, which should give you:

Python 3.4.3 :: Continuum Analytics, Inc.

Can't bind to 'ngIf' since it isn't a known property of 'div'

Just for anyone who still has an issue, I also had an issue where I typed ngif rather than ngIf (notice the capital 'I').

How to compare two dates along with time in java

An alternative is Joda-Time.

Use DateTime

DateTime date = new DateTime(new Date());
date.isBeforeNow();
or
date.isAfterNow();

Get DOS path instead of Windows path

use this link, it will automatically convert any path you give to any format https://pathconverter-pp.azurewebsites.net

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

If you are using a certificate signed by a Certificate Authority that is not included in the Java cacerts file by default, you need to complete the following configuration for HTTPS connections. To import certificates into cacerts:

  1. Open Windows Explorer and navigate to the cacerts file, which is located in the jre\lib\security subfolder where AX Core Client is installed. The default location is C:\Program Files\ACL Software\AX Core Client\jre\lib\security
  2. Create a backup copy of the file before making any changes.
  3. Depending on the certificates you receive from the Certificate Authority you are using, you may need to import an intermediate certificate and/or root certificate into the cacerts file. Use the following syntax to import certificates: keytool -import -alias -keystore -trustcacerts -file
  4. If you are importing both certificates the alias specified for each certificate should be unique.
  5. Type the password for the keystore at the “Password” prompt and press Enter. The default Java password for the cacerts file is “changeit”. Type ‘y’ at the “Trust this certificate?” prompt and press Enter.

Postgresql Select rows where column = array

   $array[0] = 1;
   $array[2] = 2;
   $arrayTxt = implode( ',', $array);
   $sql = "SELECT * FROM table WHERE some_id in ($arrayTxt)"

JavaScript - cannot set property of undefined

you never set d[a] to any value.

Because of this, d[a] evaluates to undefined, and you can't set properties on undefined.

If you add d[a] = {} right after d = {} things should work as expected.

Alternatively, you could use an object initializer:

d[a] = {
    greetings: b,
    data: c
};

Or you could set all the properties of d in an anonymous function instance:

d = new function () {
    this[a] = {
        greetings: b,
        data: c
    };
};

If you're in an environment that supports ES2015 features, you can use computed property names:

d = {
  [a]: {
    greetings: b,
    data: c
  }
};

conflicting types for 'outchar'

In C, the order that you define things often matters. Either move the definition of outchar to the top, or provide a prototype at the top, like this:

#include <stdio.h> #include <stdlib.h>  void outchar(char ch);  int main() {     outchar('A');     outchar('B');     outchar('C');     return 0; }  void outchar(char ch) {     printf("%c", ch); } 

Also, you should be specifying the return type of every function. I added that for you.

Laravel $q->where() between dates

@Tom : Instead of using 'now' or 'addWeek' if we provide date in following format, it does not give correct records

$projects = Project::whereBetween('recur_at', array(new DateTime('2015-10-16'), new DateTime('2015-10-23')))
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();

it gives records having date form 2015-10-16 to less than 2015-10-23. If value of recur_at is 2015-10-23 00:00:00 then only it shows that record else if it is 2015-10-23 12:00:45 then it is not shown.

How to resolve ORA 00936 Missing Expression Error?

This happens every time you insert/ update and you don't use single quotes. When the variable is empty it will result in that error. Fix it by using ''

Assuming the first parameter is an empty variable here is a simple example:

Wrong

nvl( ,0)

Fix

nvl('' ,0)

Put your query into your database software and check it for that error. Generally this is an easy fix

ng is not recognized as an internal or external command

I don't have a global Angular install, only project level. One of my projects kept throwing this error while others with same setup worked fine! I just

  1. Removed the node_modules folder from the project
  2. Ran npm i in the project

Works fine now.

Replacing accented characters php

I know, that question has been asked a long long time ago...

I was looking for a short and elegant solution, but couldn't find satisfaction for two reasons:

First, most of the existing solutions replace a list of characters by a list of other characters. Unfortunately, it require to use a specific encoding for the php script file itself which might be unwanted.

Second, using iconv seems to be a good way, but it's not enough as the result of a converted character could be one or two characters, or a Fatal Exception.

So I wrote that small function which does the job :

function replaceAccent($string, $replacement = '_')
{
    $alnumPattern = '/^[a-zA-Z0-9 ]+$/';

    if (preg_match($alnumPattern, $string)) {
        return $string;
    }

    $ret = array_map(
        function ($chr) use ($alnumPattern, $replacement) {
            if (preg_match($alnumPattern, $chr)) {
                return $chr;
            } else {
                $chr = @iconv('ISO-8859-1', 'ASCII//TRANSLIT', $chr);
                if (strlen($chr) == 1) {
                    return $chr;
                } elseif (strlen($chr) > 1) {
                    $ret = '';
                    foreach (str_split($chr) as $char2) {
                        if (preg_match($alnumPattern, $char2)) {
                            $ret .= $char2;
                        }
                    }
                    return $ret;
                } else {
                    // replace whatever iconv fail to convert by something else
                    return $replacement;
                }
            }
        },
        str_split($string)
    );

    return implode($ret);
}

Set div height to fit to the browser using CSS

You could also use viewport percentages if you don't care about old school IE.

height: 100vh;

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

import codecs
import shutil
import sys

s = sys.stdin.read(3)
if s != codecs.BOM_UTF8:
    sys.stdout.write(s)

shutil.copyfileobj(sys.stdin, sys.stdout)

Javascript to Select Multiple options

This type of thing should be done server-side, so as to limit the amount of resources used on the client for such trivial tasks. That being said, if you were to do it on the front-end, I would encourage you to consider using something like underscore.js to keep the code clean and concise:

var values = ["Red", "Green"],
    colors = document.getElementById("colors");

_.each(colors.options, function (option) {
    option.selected = ~_.indexOf(values, option.text);
});

If you're using jQuery, it could be even more terse:

var values = ["Red", "Green"];

$("#colors option").prop("selected", function () {
    return ~$.inArray(this.text, values);
});

If you were to do this without a tool like underscore.js or jQuery, you would have a bit more to write, and may find it to be a bit more complicated:

var color, i, j,
    values = ["Red", "Green"],
    options = document.getElementById("colors").options;

for ( i = 0; i < values.length; i++ ) {
    for ( j = 0, color = values[i]; j < options.length; j++ ) {
        options[j].selected = options[j].selected || color === options[j].text;
    }
}

Converting a Java Keystore into PEM Format

The keytool command will not allow you to export the private key from a key store. You have to write some Java code to do this. Open the key store, get the key you need, and save it to a file in PKCS #8 format. Save the associated certificate too.

KeyStore ks = KeyStore.getInstance("jks");
/* Load the key store. */
...
char[] password = ...;
/* Save the private key. */
FileOutputStream kos = new FileOutputStream("tmpkey.der");
Key pvt = ks.getKey("your_alias", password);
kos.write(pvt.getEncoded());
kos.flush();
kos.close();
/* Save the certificate. */
FileOutputStream cos = new FileOutputStream("tmpcert.der");
Certificate pub = ks.getCertificate("your_alias");
cos.write(pub.getEncoded());
cos.flush();
cos.close();

Use OpenSSL utilities to convert these files (which are in binary format) to PEM format.

openssl pkcs8 -inform der -nocrypt < tmpkey.der > tmpkey.pem
openssl x509 -inform der < tmpcert.der > tmpcert.pem

SSL peer shut down incorrectly in Java

I had mutual SSL enabled on my Spring Boot app and my Jenkins pipeline was re-building the dockers, bringing the compose up and then running integration tests which failed every time with this error. I was able to test the running dockers without this SSL error every time in a standalone test on the same Jenkins machine. It turned out that server was not completely up when the tests started executing. Putting a sleep of few seconds in my bash script to allow Spring boot application to be up and running completely resolved the issue.

Difference between \w and \b regular expression meta characters

\w matches a word character. \b is a zero-width match that matches a position character that has a word character on one side, and something that's not a word character on the other. (Examples of things that aren't word characters include whitespace, beginning and end of the string, etc.)

\w matches a, b, c, d, e, and f in "abc def"
\b matches the (zero-width) position before a, after c, before d, and after f in "abc def"

See: http://www.regular-expressions.info/reference.html/

How to add elements to an empty array in PHP?

$cart = array();
$cart[] = 11;
$cart[] = 15;

// etc

//Above is correct. but below one is for further understanding

$cart = array();
for($i = 0; $i <= 5; $i++){
          $cart[] = $i;  

//if you write $cart = [$i]; you will only take last $i value as first element in array.

}
echo "<pre>";
print_r($cart);
echo "</pre>";

How to print bytes in hexadecimal using System.out.println?

for (int j=0; j<test.length; j++) {
   System.out.format("%02X ", test[j]);
}
System.out.println();

Cannot read property length of undefined

The id of the input seems is not WallSearch. Maybe you're confusing that name and id. They are two different properties. name is used to define the name by which the value is posted, while id is the unique identification of the element inside the DOM.

Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value property.

Why use multiple columns as primary keys (composite primary key)

Your understanding is correct.

You would do this in many cases. One example is in a relationship like OrderHeader and OrderDetail. The PK in OrderHeader might be OrderNumber. The PK in OrderDetail might be OrderNumber AND LineNumber. If it was either of those two, it would not be unique, but the combination of the two is guaranteed unique.

The alternative is to use a generated (non-intelligent) primary key, for example in this case OrderDetailId. But then you would not always see the relationship as easily. Some folks prefer one way; some prefer the other way.

Unable to start the mysql server in ubuntu

Yes, should try reinstall mysql, but use the --reinstall flag to force a package reconfiguration. So the operating system service configuration is not skipped:

sudo apt --reinstall install mysql-server

UPDATE and REPLACE part of a string

Try to remove % chars as below

UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <=4

Is there any way to do HTTP PUT in python

You can of course roll your own with the existing standard libraries at any level from sockets up to tweaking urllib.

http://pycurl.sourceforge.net/

"PyCurl is a Python interface to libcurl."

"libcurl is a free and easy-to-use client-side URL transfer library, ... supports ... HTTP PUT"

"The main drawback with PycURL is that it is a relative thin layer over libcurl without any of those nice Pythonic class hierarchies. This means it has a somewhat steep learning curve unless you are already familiar with libcurl's C API. "

Which is the fastest algorithm to find prime numbers?

I will let you decide if it's the fastest or not.

using System;
namespace PrimeNumbers
{

public static class Program
{
    static int primesCount = 0;


    public static void Main()
    {
        DateTime startingTime = DateTime.Now;

        RangePrime(1,1000000);   

        DateTime endingTime = DateTime.Now;

        TimeSpan span = endingTime - startingTime;

        Console.WriteLine("span = {0}", span.TotalSeconds);

    }


    public static void RangePrime(int start, int end)
    {
        for (int i = start; i != end+1; i++)
        {
            bool isPrime = IsPrime(i);
            if(isPrime)
            {
                primesCount++;
                Console.WriteLine("number = {0}", i);
            }
        }
        Console.WriteLine("primes count = {0}",primesCount);
    }



    public static bool IsPrime(int ToCheck)
    {

        if (ToCheck == 2) return true;
        if (ToCheck < 2) return false;


        if (IsOdd(ToCheck))
        {
            for (int i = 3; i <= (ToCheck / 3); i += 2)
            {
                if (ToCheck % i == 0) return false;
            }
            return true;
        }
        else return false; // even numbers(excluding 2) are composite
    }

    public static bool IsOdd(int ToCheck)
    {
        return ((ToCheck % 2 != 0) ? true : false);
    }
}
}

It takes approximately 82 seconds to find and print prime numbers within a range of 1 to 1,000,000, on my Core 2 Duo laptop with a 2.40 GHz processor. And it found 78,498 prime numbers.

Renaming files using node.js

For linux/unix OS, you can use the shell syntax

const shell = require('child_process').execSync ; 

const currentPath= `/path/to/name.png`;
const newPath= `/path/to/another_name.png`;

shell(`mv ${currentPath} ${newPath}`);

That's it!

Send POST request with JSON data using Volley

You can also send data by overriding getBody() method of JsonObjectRequest class. As shown below.

    @Override
    public byte[] getBody()
    {

        JSONObject jsonObject = new JSONObject();
        String body = null;
        try
        {
            jsonObject.put("username", "user123");
            jsonObject.put("password", "Pass123");

            body = jsonObject.toString();
        } catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try
        {
            return body.toString().getBytes("utf-8");
        } catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

startsWith() and endsWith() functions in PHP

No-copy and no-intern-loop:

function startsWith(string $string, string $start): bool
{
    return strrpos($string, $start, - strlen($string)) !== false;
}

function endsWith(string $string, string $end): bool
{
    return ($offset = strlen($string) - strlen($end)) >= 0 
    && strpos($string, $end, $offset) !== false;
}

Gson library in Android Studio

There is no need of adding JAR to your project by yourself, just add dependency in build.gradle (Module lavel). ALSO always try to use the upgraded version, as of now is

dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}

As every incremental version has some bugs fixes or up-gradations as mentioned here

How to check if a variable is empty in python?

Yes, bool. It's not exactly the same -- '0' is True, but None, False, [], 0, 0.0, and "" are all False.

bool is used implicitly when you evaluate an object in a condition like an if or while statement, conditional expression, or with a boolean operator.

If you wanted to handle strings containing numbers as PHP does, you could do something like:

def empty(value):
    try:
        value = float(value)
    except ValueError:
        pass
    return bool(value)

Errors in pom.xml with dependencies (Missing artifact...)

I know it is an old question. But I hope my answer will help somebody. I had the same issue and I think the problem is that it cannot find those .jar files in your local repository. So what I did is I added the following code to my pom.xml and it worked.

<repositories>
  <repository>
      <id>spring-milestones</id>
      <name>Spring Milestones</name>
      <url>https://repo.spring.io/libs-milestone</url>
      <snapshots>
          <enabled>false</enabled>
      </snapshots>
  </repository>
</repositories>

How to export and import environment variables in windows?

You can get access to the environment variables in either the command line or in the registry.

Command Line

If you want a specific environment variable, then just type the name of it (e.g. PATH), followed by a >, and the filename to write to. The following will dump the PATH environment variable to a file named path.txt.

C:\> PATH > path.txt

Registry Method

The Windows Registry holds all the environment variables, in different places depending on which set you are after. You can use the registry Import/Export commands to shift them into the other PC.

For System Variables:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

For User Variables:

HKEY_CURRENT_USER\Environment

Attach a body onload event with JS

There are several different methods you have to use for different browsers. Libraries like jQuery give you a cross-browser interface that handles it all for you, though.

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

If you know from which commit issue started, you can reset your branch to that commit and then merge them.

Check if character is number?

You can use this:

function isDigit(n) {
    return Boolean([true, true, true, true, true, true, true, true, true, true][n]);
}

Here, I compared it to the accepted method: http://jsperf.com/isdigittest/5 . I didn't expect much, so I was pretty suprised, when I found out that accepted method was much slower.

Interesting thing is, that while accepted method is faster correct input (eg. '5') and slower for incorrect (eg. 'a'), my method is exact opposite (fast for incorrect and slower for correct).

Still, in worst case, my method is 2 times faster than accepted solution for correct input and over 5 times faster for incorrect input.

Returning multiple objects in an R function

Unlike many other languages, R functions don't return multiple objects in the strict sense. The most general way to handle this is to return a list object. So if you have an integer foo and a vector of strings bar in your function, you could create a list that combines these items:

foo <- 12
bar <- c("a", "b", "e")
newList <- list("integer" = foo, "names" = bar)

Then return this list.

After calling your function, you can then access each of these with newList$integer or newList$names.

Other object types might work better for various purposes, but the list object is a good way to get started.

number several equations with only one number

How about something like:

\documentclass{article}

\usepackage{amssymb,amsmath}

\begin{document}

\begin{equation}\label{A_Label}
  \begin{split}
    w^T x_i + b \geqslant 1-\xi_i \text{ if } y_i &= 1, \\
    w^T x_i + b \leqslant -1+\xi_i \text{ if } y_i &= -1
  \end{split}
\end{equation}

\end{document}

which produces:

enter image description here

Return number of rows affected by UPDATE statements

CREATE PROCEDURE UpdateTables
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @RowCount1 INTEGER
    DECLARE @RowCount2 INTEGER
    DECLARE @RowCount3 INTEGER
    DECLARE @RowCount4 INTEGER

    UPDATE Table1 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount1 = @@ROWCOUNT
    UPDATE Table2 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount2 = @@ROWCOUNT
    UPDATE Table3 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount3 = @@ROWCOUNT
    UPDATE Table4 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount4 = @@ROWCOUNT

    SELECT @RowCount1 AS Table1, @RowCount2 AS Table2, @RowCount3 AS Table3, @RowCount4 AS Table4
END

Differences between ConstraintLayout and RelativeLayout

A big difference is that ConstraintLayout respects constraints even if the view is gone. So it won't break the layout if you have a chain and you want to make a view disappear in the middle.

ADB Driver and Windows 8.1

If all other solutions did not work for your device try this guide how to make a truly universal adb and fastboot driver out of Google USB driver. The resulting driver works for adb, recovery and fastboot modes in all versions of Windows.

How to enter a formula into a cell using VBA?

You aren't building your formula right.

Worksheets("EmployeeCosts").Range("B" & var1a).Formula =  "=SUM(H5:H" & var1a & ")"

This does the same as the following lines do:

Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"

which is what you are trying to do.

Also, you want to have the = at the beginning of the formala.

MySQL match() against() - order by relevance and column?

I have never done so, but it seems like

MATCH (head, head, body) AGAINST ('some words' IN BOOLEAN MODE)

Should give a double weight to matches found in the head.


Just read this comment on the docs page, Thought it might be of value to you:

Posted by Patrick O'Lone on December 9 2002 6:51am

It should be noted in the documentation that IN BOOLEAN MODE will almost always return a relevance of 1.0. In order to get a relevance that is meaningful, you'll need to:

SELECT MATCH('Content') AGAINST ('keyword1 keyword2') as Relevance 
FROM table 
WHERE MATCH ('Content') AGAINST('+keyword1+keyword2' IN BOOLEAN MODE) 
HAVING Relevance > 0.2 
ORDER BY Relevance DESC 

Notice that you are doing a regular relevance query to obtain relevance factors combined with a WHERE clause that uses BOOLEAN MODE. The BOOLEAN MODE gives you the subset that fulfills the requirements of the BOOLEAN search, the relevance query fulfills the relevance factor, and the HAVING clause (in this case) ensures that the document is relevant to the search (i.e. documents that score less than 0.2 are considered irrelevant). This also allows you to order by relevance.

This may or may not be a bug in the way that IN BOOLEAN MODE operates, although the comments I've read on the mailing list suggest that IN BOOLEAN MODE's relevance ranking is not very complicated, thus lending itself poorly for actually providing relevant documents. BTW - I didn't notice a performance loss for doing this, since it appears MySQL only performs the FULLTEXT search once, even though the two MATCH clauses are different. Use EXPLAIN to prove this.

So it would seem you may not need to worry about calling the fulltext search twice, though you still should "use EXPLAIN to prove this"

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

Restarting cron after changing crontab file?

I had a similar issue on 16.04 VPS Digital Ocean. If you are changing crontabs, make sure to run

sudo service cron restart 

Regular expression \p{L} and \p{N}

\p{L} matches a single code point in the category "letter".
\p{N} matches any kind of numeric character in any script.

Source: regular-expressions.info

If you're going to work with regular expressions a lot, I'd suggest bookmarking that site, it's very useful.

"The system cannot find the file specified"

I had this error and I found that the name of one of my connection strings was wrong. Check the names as well as the actual string.

How can I get file extensions with JavaScript?

var filetypeArray = (file.type).split("/");
var filetype = filetypeArray[1];

This is a better approach imo.

How to get class object's name as a string in Javascript?

Some time ago, I used this.

Perhaps you could try:

+function(){
    var my_var = function get_this_name(){
        alert("I " + this.init());
    };
    my_var.prototype.init = function(){
        return my_var.name;
    }
    new my_var();
}();

Pop an Alert: "I get_this_name".

Calculate rolling / moving average in C++

You could implement a ring buffer. Make an array of 1000 elements, and some fields to store the start and end indexes and total size. Then just store the last 1000 elements in the ring buffer, and recalculate the average as needed.

How to search for rows containing a substring?

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

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

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

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

Updated answer to reflect question update:

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

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

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

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

WPF loading spinner

Here's an example of an all-xaml solution. It binds to an "IsWorking" boolean in the viewmodel to show the control and start the animation.

<UserControl x:Class="MainApp.Views.SpinnerView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">

    <UserControl.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVisConverter"/>
    </UserControl.Resources>

    <StackPanel Orientation="Horizontal" Margin="5"
                     Visibility="{Binding IsWorking, Converter={StaticResource BoolToVisConverter}}">
        <Label>Wait...</Label>
        <Ellipse x:Name="spinnerEllipse" 
                     Width="20" Height="20">
            <Ellipse.Fill>
                <LinearGradientBrush StartPoint="1,1" EndPoint="0,0" >
                    <GradientStop Color="White" Offset="0"/>
                    <GradientStop Color="CornflowerBlue" Offset="1"/>
                </LinearGradientBrush>
            </Ellipse.Fill>
            <Ellipse.RenderTransform>
                <RotateTransform x:Name="SpinnerRotate" CenterX="10" CenterY="10"/>
            </Ellipse.RenderTransform>
            <Ellipse.Style>
                <Style TargetType="Ellipse">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsWorking}" Value="True">
                            <DataTrigger.EnterActions>
                                <BeginStoryboard x:Name="SpinStoryboard">
                                    <Storyboard TargetProperty="RenderTransform.Angle" >
                                        <DoubleAnimation
                                            From="0" To="360" Duration="0:0:01"
                                            RepeatBehavior="Forever" />
                                    </Storyboard>
                                </BeginStoryboard>
                            </DataTrigger.EnterActions>
                            <DataTrigger.ExitActions>
                                <StopStoryboard BeginStoryboardName="SpinStoryboard"></StopStoryboard>
                            </DataTrigger.ExitActions>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Ellipse.Style>
        </Ellipse>
    </StackPanel>
</UserControl>  

How to call a method in MainActivity from another class?

You have to pass instance of MainActivity into another class, then you can call everything public (in MainActivity) from everywhere.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    // Instance of AnotherClass for future use
    private AnotherClass anotherClass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Create new instance of AnotherClass and
        // pass instance of MainActivity by "this"
        anotherClass = new AnotherClass(this);
    }

    // Method you want to call from another class
    public void startChronometer(){
        ...
    }
}

AnotherClass.java

public class AnotherClass {

    // Main class instance
    private MainActivity mainActivity;  

    // Constructor
    public AnotherClass(MainActivity activity) {

        // Save instance of main class for future use
        mainActivity = activity;  

        // Call method in MainActivity
        mainActivity.startChronometer();
    }
}

Git credential helper - update password

First find the version you are using with the Git command git --version. If you have a newer version than 1.7.10, then simply use this command:

git config --global credential.helper wincred

Then do the git fetch , then it prompts for the password update.

Now, it won't prompt for the password for multiple times in Git.

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

AJB's "Option B" can be made to work by using the base Ubuntu image and setting up nginx on your own. (It didn't work when I used the Nginx image from Docker Hub.)

Here is the Docker file I used:

FROM ubuntu
RUN apt-get update && apt-get install -y nginx
RUN ln -sf /dev/stdout /var/log/nginx/access.log
RUN ln -sf /dev/stderr /var/log/nginx/error.log
RUN rm -rf /etc/nginx/sites-enabled/default
EXPOSE 80 443
COPY conf/mysite.com /etc/nginx/sites-enabled/mysite.com
CMD ["nginx", "-g", "daemon off;"]

My nginx config (aka: conf/mysite.com):

server {
    listen 80 default;
    server_name mysite.com;

    location / {
        proxy_pass http://website;
    }
}

upstream website {
    server website:3000;
}

And finally, how I start my containers:

$ docker run -dP --name website website
$ docker run -dP --name nginx --link website:website nginx

This got me up and running so my nginx pointed the upstream to the second docker container which exposed port 3000.

How to determine whether a substring is in a different string

def find_substring():
    s = 'bobobnnnnbobmmmbosssbob'
    cnt = 0
    for i in range(len(s)):
        if s[i:i+3] == 'bob':
            cnt += 1
    print 'bob found: ' + str(cnt)
    return cnt

def main():
    print(find_substring())

main()

Git undo changes in some files

git add B # Add it to the index
git reset A # Remove it from the index
git commit # Commit the index

jQuery returning "parsererror" for ajax request

incase of Get operation from web .net mvc/api, make sure you are allow get

     return Json(data,JsonRequestBehavior.AllowGet);

Repeat a task with a time delay?

Using kotlin and its Coroutine its quite easy, first declare a job in your class (better in your viewModel) like this:

private var repeatableJob: Job? = null

then when you want to create and start it do this:

repeatableJob = viewModelScope.launch {
    while (isActive) {
         delay(5_000)
         loadAlbums(iImageAPI, titleHeader, true)
    }
}
repeatableJob?.start()

and if you want to finish it:

repeatableJob?.cancel()

PS: viewModelScope is only available in view models, you can use other Coroutine scopes such as withContext(Dispatchers.IO)

More information: Here

DropdownList DataSource

Refer to example at this link. It may be help to you.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.aspx

void Page_Load(Object sender, EventArgs e)
  {

     // Load data for the DropDownList control only once, when the 
     // page is first loaded.
     if(!IsPostBack)
     {

        // Specify the data source and field names for the Text 
        // and Value properties of the items (ListItem objects) 
        // in the DropDownList control.
        ColorList.DataSource = CreateDataSource();
        ColorList.DataTextField = "ColorTextField";
        ColorList.DataValueField = "ColorValueField";

        // Bind the data to the control.
        ColorList.DataBind();

        // Set the default selected item, if desired.
        ColorList.SelectedIndex = 0;

     }

  }

void Selection_Change(Object sender, EventArgs e)
  {

     // Set the background color for days in the Calendar control
     // based on the value selected by the user from the 
     // DropDownList control.
     Calendar1.DayStyle.BackColor = 
         System.Drawing.Color.FromName(ColorList.SelectedItem.Value);

  }

What is the difference between CSS and SCSS?

CSS is the styling language that any browser understands to style webpages.

SCSS is a special type of file for SASS, a program written in Ruby that assembles CSS style sheets for a browser, and for information, SASS adds lots of additional functionality to CSS like variables, nesting and more which can make writing CSS easier and faster.
SCSS files are processed by the server running a web app to output a traditional CSS that your browser can understand.

Java output formatting for Strings

To answer your updated question you can do

String[] lines = ("Name =              Bob\n" +
        "Age =               27\n" +
        "Occupation =        Student\n" +
        "Status =            Single").split("\n");

for (String line : lines) {
    String[] parts = line.split(" = +");
    System.out.printf("%-19s %s%n", parts[0] + " =", parts[1]);
}

prints

Name =              Bob
Age =               27
Occupation =        Student
Status =            Single

Run php function on button click

You can use isset().

<form method="post">
    <input type="submit" name="test" id="test" value="RUN" />

</form>

<?php

function testfun()
{
   echo "Your test function on button click is working";
}

if(isset($_POST('submit')))
{
   testfun();
}

?>

convert json ipython notebook(.ipynb) to .py file

From the notebook menu you can save the file directly as a python script. Go to the 'File' option of the menu, then select 'Download as' and there you would see a 'Python (.py)' option.

enter image description here

Another option would be to use nbconvert from the command line:

jupyter nbconvert --to script 'my-notebook.ipynb'

Have a look here.

INSERT INTO vs SELECT INTO

The other answers are all great/correct (the main difference is whether the DestTable exists already (INSERT), or doesn't exist yet (SELECT ... INTO))

You may prefer to use INSERT (instead of SELECT ... INTO), if you want to be able to COUNT(*) the rows that have been inserted so far.

Using SELECT COUNT(*) ... WITH NOLOCK is a simple/crude technique that may help you check the "progress" of the INSERT; helpful if it's a long-running insert, as seen in this answer).

[If you use...] INSERT DestTable SELECT ... FROM SrcTable ...then your SELECT COUNT(*) from DestTable WITH (NOLOCK) query would work.

How to lose margin/padding in UITextView?

For iOS 7.0, I've found that the contentInset trick no longer works. This is the code I used to get rid of the margin/padding in iOS 7.

This brings the left edge of the text to the left edge of the container:

textView.textContainer.lineFragmentPadding = 0

This causes the top of the text to align with the top of the container

textView.textContainerInset = .zero

Both Lines are needed to completely remove the margin/padding.

Java Try and Catch IOException Problem

The reason you are getting the the IOException is because you are not catching the IOException of your countLines method. You'll want to do something like this:

public static void main(String[] args) {
  int lines = 0;  

  // TODO - Need to get the filename to populate sFileName.  Could
  // come from the command line arguments.

   try {
       lines = LineCounter.countLines(sFileName);
    }
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);
    }

   if(lines > 0) {
     // Do rest of program.
   }
}

How to show current user name in a cell?

The simplest way is to create a VBA macro that wraps that function, like so:

Function UserNameWindows() As String
    UserName = Environ("USERNAME")
End Function

Then call it from the cell:

=UserNameWindows()

See this article for more details, and other ways.

How do Python functions handle the types of the parameters that you pass in?

Many languages have variables, which are of a specific type and have a value. Python does not have variables; it has objects, and you use names to refer to these objects.

In other languages, when you say:

a = 1

then a (typically integer) variable changes its contents to the value 1.

In Python,

a = 1

means “use the name a to refer to the object 1”. You can do the following in an interactive Python session:

>>> type(1)
<type 'int'>

The function type is called with the object 1; since every object knows its type, it's easy for type to find out said type and return it.

Likewise, whenever you define a function

def funcname(param1, param2):

the function receives two objects, and names them param1 and param2, regardless of their types. If you want to make sure the objects received are of a specific type, code your function as if they are of the needed type(s) and catch the exceptions that are thrown if they aren't. The exceptions thrown are typically TypeError (you used an invalid operation) and AttributeError (you tried to access an inexistent member (methods are members too) ).

BigDecimal setScale and round

One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.

The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.

setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.

If you move the decimal point one place to the right, the difference will become clear:

// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456

What is the copy-and-swap idiom?

This answer is more like an addition and a slight modification to the answers above.

In some versions of Visual Studio (and possibly other compilers) there is a bug that is really annoying and doesn't make sense. So if you declare/define your swap function like this:

friend void swap(A& first, A& second) {

    std::swap(first.size, second.size);
    std::swap(first.arr, second.arr);

}

... the compiler will yell at you when you call the swap function:

enter image description here

This has something to do with a friend function being called and this object being passed as a parameter.


A way around this is to not use friend keyword and redefine the swap function:

void swap(A& other) {

    std::swap(size, other.size);
    std::swap(arr, other.arr);

}

This time, you can just call swap and pass in other, thus making the compiler happy:

enter image description here


After all, you don't need to use a friend function to swap 2 objects. It makes just as much sense to make swap a member function that has one other object as a parameter.

You already have access to this object, so passing it in as a parameter is technically redundant.

Clear a terminal screen for real

echo -e "\e[3J"

This works in Linux Machines

python date of the previous month

Its very easy and simple. Do this

from dateutil.relativedelta import relativedelta
from datetime import datetime

today_date = datetime.today()
print "todays date time: %s" %today_date

one_month_ago = today_date - relativedelta(months=1)
print "one month ago date time: %s" % one_month_ago
print "one month ago date: %s" % one_month_ago.date()

Here is the output: $python2.7 main.py

todays date time: 2016-09-06 02:13:01.937121
one month ago date time: 2016-08-06 02:13:01.937121
one month ago date: 2016-08-06

How to customize <input type="file">?

to show path of selected file you can try this on html :

<div class="fileinputs">
    <input type="file" class="file">
</div>

and in javascript :

        var fakeFileUpload = document.createElement('div');
        fakeFileUpload.className = 'fakefile';
        var image = document.createElement('div');
        image.className='fakebtn';
        image.innerHTML = 'browse';
        fakeFileUpload.appendChild(image);
        fakeFileUpload.appendChild(document.createElement('input'));
        var x = document.getElementsByTagName('input');
        for (var i=0;i<x.length;i++) {
            if (x[i].type != 'file') continue;
            if (x[i].parentNode.className != 'fileinputs') continue;
            x[i].className = 'file hidden';
            var clone = fakeFileUpload.cloneNode(true);
            x[i].parentNode.appendChild(clone);
            x[i].relatedElement = clone.getElementsByTagName('input')[0];
            x[i].onchange = x[i].onmouseout = function () {
                this.relatedElement.value = this.value;
            }
        }

and style :

div.fileinputs {
    position: relative;
    height: 30px;
    width: 370px;
}
input.file.hidden {
    position: relative;
    text-align: right;
    -moz-opacity: 0;
    filter: alpha(opacity: 0);
    opacity: 0;
    z-index: 2;
}
div.fakefile {
    position: absolute;
    top: 0px;
    left: 0px;
    right: 0;
    width: 370px;
    padding: 0;
    margin: 0;
    z-index: 1;
    line-height: 90%;
}
div.fakefile input {
    margin-bottom: 5px;
    margin-left: 0;
    border: none;
    box-shadow: 0px 0px 2px 1px #ccc;
    padding: 4px;
    width: 241px;
    height: 20px;
}
div.fakefile .fakebtn{
    width: 150px;
    background: #eb5a41;
    z-index: 10;
    font-family: roya-bold;
    border: none;
    padding: 5px 15px;
    font-size: 18px;
    text-align: center;
    cursor: pointer;
    -webkit-transition: all 0.4s ease;
    -moz-transition: all 0.4s ease;
    -o-transition: all 0.4s ease;
    -ms-transition: all 0.4s ease;
    transition: all 0.4s ease;
    display: inline;
    margin-left: 3px;
}
div.fileinputs input[type="file"]:hover + div .fakebtn{
    background: #DA472E;
}

div.fileinputs input[type="file"] {
    opacity: 0;
    position: absolute;
    top: -6px;
    right: 0px;
    z-index: 20;
    width: 102px;
    height: 40px;
    cursor: pointer;
}

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module

What I would do is use this tool and step through where you are getting the exception

http://www.reflector.net/

Read this it will tell you how to create PDB's so you do not have to have all your references setup.

http://www.cplotts.com/2011/01/14/net-reflector-pro-debugging-the-net-framework-source-code/

It is a trial and I am not related to redgate at all I just use there software.

Move the mouse pointer to a specific position?

I would imagine you could accomplish placing the mouse cursor to a given area of the screen if you didn't use the real (system) mouse cursor.

For instance, you could create an image to act in place of your cursor, handle an event which upon detecting mouseenter into your scene, set the style on the system cursor to 'none' (sceneElement.style.cursor = 'none'), then would bring up a hidden image element acting as a cursor to be anywhere you like with in the scene based on a predefined axis/bounding box translation.

This way no matter how you moved the real cursor your translation method would keep your image cursor wherever you needed it.

edit: an example in jsFiddle using an image representation and forced mouse movement

Setting user agent of a java URLConnection

HTTP Servers tend to reject old browsers and systems.

The page Tech Blog (wh): Most Common User Agents reflects the user-agent property of your current browser in section "Your user agent is:", which can be applied to set the request property "User-Agent" of a java.net.URLConnection or the system property "http.agent".

Scrolling to an Anchor using Transition/CSS3

If anybody is just like me willing to use jQuery, but still found himself looking to this question then this may help you guys:

https://html-online.com/articles/animated-scroll-anchorid-function-jquery/

_x000D_
_x000D_
$(document).ready(function () {_x000D_
            $("a.scrollLink").click(function (event) {_x000D_
                event.preventDefault();_x000D_
                $("html, body").animate({ scrollTop: $($(this).attr("href")).offset().top }, 500);_x000D_
            });_x000D_
        });
_x000D_
<a href="#anchor1" class="scrollLink">Scroll to anchor 1</a>_x000D_
<a href="#anchor2" class="scrollLink">Scroll to anchor 2</a>_x000D_
<p id="anchor1"><strong>Anchor 1</strong> - Lorem ipsum dolor sit amet, nonumes voluptatum mel ea.</p>_x000D_
<p id="anchor2"><strong>Anchor 2</strong> - Ex ignota epicurei quo, his ex doctus delenit fabellas.</p>
_x000D_
_x000D_
_x000D_

Java 8 stream map to list of keys sorted by values

You say you want to sort by value, but you don't have that in your code. Pass a lambda (or method reference) to sorted to tell it how you want to sort.

And you want to get the keys; use map to transform entries to keys.

List<Type> types = countByType.entrySet().stream()
        .sorted(Comparator.comparing(Map.Entry::getValue))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

Get an object attribute

Use getattr if you have an attribute in string form:

>>> class User(object):
       name = 'John'

>>> u = User()
>>> param = 'name'
>>> getattr(u, param)
'John'

Otherwise use the dot .:

>>> class User(object):
       name = 'John'

>>> u = User()
>>> u.name
'John'

android start activity from service

If you need to recal an Activity that is in bacgrounde, from your service, I suggest the following link. Intent.FLAG_ACTIVITY_NEW_TASK is not the solution.

https://stackoverflow.com/a/8759867/1127429

How to use a variable inside a regular expression?

rx = r'\b(?<=\w){0}\b(?!\w)'.format(TEXTO)

Get unicode value of a character

You can do it for any Java char using the one liner here:

System.out.println( "\\u" + Integer.toHexString('÷' | 0x10000).substring(1) );

But it's only going to work for the Unicode characters up to Unicode 3.0, which is why I precised you could do it for any Java char.

Because Java was designed way before Unicode 3.1 came and hence Java's char primitive is inadequate to represent Unicode 3.1 and up: there's not a "one Unicode character to one Java char" mapping anymore (instead a monstrous hack is used).

So you really have to check your requirements here: do you need to support Java char or any possible Unicode character?

Tomcat view catalina.out log file

If you are in the home directory first move to apache tomcat use below command

cd apache-tomcat/

then move to logs

cd logs/

then open the catelina.out use the below command

tail -f catalina.out

How to restart a single container with docker-compose

Restart container

If you want to just restart your container:

docker-compose restart servicename

Think of this command as "just restart the container by its name", which is equivalent to docker restart command.

Note caveats:

  1. If you changed ENV variables they won't updated in container. You need to stop it and start again. Or, using single command docker-compose up will detect changes and recreate container.

  2. As many others mentioned, if you changed docker-compose.yml file itself, simple restart won't apply those changes.

  3. If you copy your code inside container at the build stage (in Dockerfile using ADD or COPY commands), every time the code changes you have to rebuild the container (docker-compose build).

Correlation to your code

docker-compose restart should work perfectly fine, if your code gets path mapped into the container by volume directive in docker-compose.yml like so:

services:

  servicename:
    volumes:
      - .:/code

But I'd recommend to use live code reloading, which is probably provided by your framework of choice in DEBUG mode (alternatively, you can search for auto-reload packages in your language of choice). Adding this should eliminate the need to restart container every time after your code changes, instead reloading the process inside.

Uint8Array to string in Javascript

Do what @Sudhir said, and then to get a String out of the comma seperated list of numbers use:

for (var i=0; i<unitArr.byteLength; i++) {
            myString += String.fromCharCode(unitArr[i])
        }

This will give you the string you want, if it's still relevant

OpenJDK availability for Windows OS

You may find OpenJDK 6 and 7 binaries for Windows in openjdk-unofficial-builds github project.

Update: OpenJDK 8 and 11 LTS binaries for Windows x86_64 can be found in ojdkbuild github project.

Disclaimer: I've built them myself.

Update (2019): OpenJDK Updates Project Builds for 8 and 11 are available now.

How do you get the current project directory from C# code when creating a custom MSBuild task?

If you really want to ensure you get the source project directory, no matter what the bin output path is set to:

  1. Add a pre-build event command line (Visual Studio: Project properties -> Build Events):

    echo $(MSBuildProjectDirectory) > $(MSBuildProjectDirectory)\Resources\ProjectDirectory.txt

  2. Add the ProjectDirectory.txt file to the Resources.resx of the project (If it doesn't exist yet, right click project -> Add new item -> Resources file)

  3. Access from code with Resources.ProjectDirectory.

repository element was not specified in the POM inside distributionManagement element or in -DaltDep loymentRepository=id::layout::url parameter

The issue is fixed by adding repository url under distributionManagement tab in main pom.xml.

Jenkin maven goal : clean deploy -U -Dmaven.test.skip=true

<distributionManagement>
    <repository>
        <id>releases</id>
        <url>http://domain:port/content/repositories/releases</url>
    </repository>
    <snapshotRepository>
        <id>snapshots</id>
        <url>http://domain:port/content/repositories/snapshots</url>
    </snapshotRepository>
</distributionManagement>

No Title Bar Android Theme

To Hide the Action Bar add the below code in Values/Styles

<style name="CustomActivityThemeNoActionBar" parent="@android:style/Theme.Holo.Light">
    <item name="android:windowActionBar">false</item>
    <item name="android:windowNoTitle">true</item>
</style>

Then in your AndroidManifest.xml file add the below code in the required activity

<activity
        android:name="com.newbelievers.android.NBMenu"
        android:label="@string/title_activity_nbmenu"
        android:theme="@style/CustomActivityThemeNoActionBar">
</activity>

Use multiple css stylesheets in the same html page

You can't control which you're referencing, given the same level of specificity in the rule (e.g. both are simply .banner) the stylesheet included last will win.

It's per-property, so if there's a combination going on (for example one has background, the other has color) then you'll get the combination...if a property is defined in both, whatever it is the last time it appears in stylesheet order wins.

Why doesn't os.path.join() work in this case?

I'd recommend to strip from the second and the following strings the string os.path.sep, preventing them to be interpreted as absolute paths:

first_path_str = '/home/build/test/sandboxes/'
original_other_path_to_append_ls = [todaystr, '/new_sandbox/']
other_path_to_append_ls = [
    i_path.strip(os.path.sep) for i_path in original_other_path_to_append_ls
]
output_path = os.path.join(first_path_str, *other_path_to_append_ls)

PHP : send mail in localhost

It is configured to use localhost:25 for the mail server.

The error message says that it can't connect to localhost:25.

Therefore you have two options:

  1. Install / Properly configure an SMTP server on localhost port 25
  2. Change the configuration to point to some other SMTP server that you can connect to

How to make parent wait for all child processes to finish?

pid_t child_pid, wpid;
int status = 0;

//Father code (before child processes start)

for (int id=0; id<n; id++) {
    if ((child_pid = fork()) == 0) {
        //child code
        exit(0);
    }
}

while ((wpid = wait(&status)) > 0); // this way, the father waits for all the child processes 

//Father code (After all child processes end)

wait waits for a child process to terminate, and returns that child process's pid. On error (eg when there are no child processes), -1 is returned. So, basically, the code keeps waiting for child processes to finish, until the waiting errors out, and then you know they are all finished.

Django REST Framework: adding additional field to ModelSerializer

This worked for me. If we want to just add an additional field in ModelSerializer, we can do it like below, and also the field can be assigned some val after some calculations of lookup. Or in some cases, if we want to send the parameters in API response.

In model.py

class Foo(models.Model):
    """Model Foo"""
    name = models.CharField(max_length=30, help_text="Customer Name")

In serializer.py

class FooSerializer(serializers.ModelSerializer):
    retrieved_time = serializers.SerializerMethodField()
    
    @classmethod
    def get_retrieved_time(self, object):
        """getter method to add field retrieved_time"""
        return None

  class Meta:
        model = Foo
        fields = ('id', 'name', 'retrieved_time ')

Hope this could help someone.

How to prevent line breaks in list items using CSS

Bootstrap 4 has a class named text-nowrap. It is just what you need.

Converting Varchar Value to Integer/Decimal Value in SQL Server

Table structure...very basic:

create table tabla(ID int, Stuff varchar (50));

insert into tabla values(1, '32.43');
insert into tabla values(2, '43.33');
insert into tabla values(3, '23.22');

Query:

SELECT SUM(cast(Stuff as decimal(4,2))) as result FROM tabla

Or, try this:

SELECT SUM(cast(isnull(Stuff,0) as decimal(12,2))) as result FROM tabla

Working on SQLServer 2008

How to use mongoimport to import csv

Just use this after executing mongoimport

It will return number of objects imported

use db
db.collectionname.find().count()

will return the number of objects.

What is the Maximum Size that an Array can hold?

Here is an answer to your question that goes into detail: http://www.velocityreviews.com/forums/t372598-maximum-size-of-byte-array.html

You may want to mention which version of .NET you are using and your memory size.

You will be stuck to a 2G, for your application, limit though, so it depends on what is in your array.

Set selected item in Android BottomNavigationView

Above API 25 you can use setSelectedItemId(menu_item_id) but under API 25 you must do differently, user Menu to get handle and then setChecked to Checked specific item

Best way of invoking getter by reflection

I think this should point you towards the right direction:

import java.beans.*

for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) {
  if (pd.getReadMethod() != null && !"class".equals(pd.getName()))
    System.out.println(pd.getReadMethod().invoke(foo));
}

Note that you could create BeanInfo or PropertyDescriptor instances yourself, i.e. without using Introspector. However, Introspector does some caching internally which is normally a Good Thing (tm). If you're happy without a cache, you can even go for

// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);

However, there are a lot of libraries that extend and simplify the java.beans API. Commons BeanUtils is a well known example. There, you'd simply do:

Object value = PropertyUtils.getProperty(person, "name");

BeanUtils comes with other handy stuff. i.e. on-the-fly value conversion (object to string, string to object) to simplify setting properties from user input.

Finding the length of a Character Array in C

Although the earlier answers are OK, here's my contribution.

//returns the size of a character array using a pointer to the first element of the character array
int size(char *ptr)
{
    //variable used to access the subsequent array elements.
    int offset = 0;
    //variable that counts the number of elements in your array
    int count = 0;

    //While loop that tests whether the end of the array has been reached
    while (*(ptr + offset) != '\0')
    {
        //increment the count variable
        ++count;
        //advance to the next element of the array
        ++offset;
    }
    //return the size of the array
    return count;
}

In your main function, you call the size function by passing the address of the first element of your array.

For example:

char myArray[] = {'h', 'e', 'l', 'l', 'o'};
printf("The size of my character array is: %d\n", size(&myArray[0]));

Find out how much memory is being used by an object in Python

Another approach is to use pickle. See this answer to a duplicate of this question.

How to right-align and justify-align in Markdown?

In a generic Markdown document, use:

<style>body {text-align: right}</style>

or

<style>body {text-align: justify}</style>

Does not seem to work with Jupyter though.

What is JavaScript's highest integer value that a number can go to without losing precision?

The short answer is “it depends.”

If you’re using bitwise operators anywhere (or if you’re referring to the length of an Array), the ranges are:

Unsigned: 0…(-1>>>0)

Signed: (-(-1>>>1)-1)…(-1>>>1)

(It so happens that the bitwise operators and the maximum length of an array are restricted to 32-bit integers.)

If you’re not using bitwise operators or working with array lengths:

Signed: (-Math.pow(2,53))…(+Math.pow(2,53))

These limitations are imposed by the internal representation of the “Number” type, which generally corresponds to IEEE 754 double-precision floating-point representation. (Note that unlike typical signed integers, the magnitude of the negative limit is the same as the magnitude of the positive limit, due to characteristics of the internal representation, which actually includes a negative 0!)

Can the "IN" operator use LIKE-wildcards (%) in Oracle?

Not 100% what you were looking for, but kind of an inside-out way of doing it:

SQL> CREATE TABLE mytable (id NUMBER, status VARCHAR2(50));

Table created.

SQL> INSERT INTO mytable VALUES (1,'Finished except pouring water on witch');

1 row created.

SQL> INSERT INTO mytable VALUES (2,'Finished except clicking ruby-slipper heels');

1 row created.

SQL> INSERT INTO mytable VALUES (3,'You shall (not?) pass');

1 row created.

SQL> INSERT INTO mytable VALUES (4,'Done');

1 row created.

SQL> INSERT INTO mytable VALUES (5,'Done with it.');

1 row created.

SQL> INSERT INTO mytable VALUES (6,'In Progress');

1 row created.

SQL> INSERT INTO mytable VALUES (7,'In progress, OK?');

1 row created.

SQL> INSERT INTO mytable VALUES (8,'In Progress Check Back In Three Days'' Time');

1 row created.

SQL> SELECT *
  2  FROM   mytable m
  3  WHERE  +1 NOT IN (INSTR(m.status,'Done')
  4            ,       INSTR(m.status,'Finished except')
  5            ,       INSTR(m.status,'In Progress'));

        ID STATUS
---------- --------------------------------------------------
         3 You shall (not?) pass
         7 In progress, OK?

SQL>

View tabular file such as CSV from command line

Using TxtSushi you can do:

csvtopretty filename.csv | less -S

Trying to get property of non-object - CodeIgniter

To access the elements in the array, use array notation: $product['prodname']

$product->prodname is object notation, which can only be used to access object attributes and methods.

What are Keycloak's OAuth2 / OpenID Connect endpoints?

For Keycloak 1.2 the above information can be retrieved via the url

http://keycloakhost:keycloakport/auth/realms/{realm}/.well-known/openid-configuration

For example, if the realm name is demo:

http://keycloakhost:keycloakport/auth/realms/demo/.well-known/openid-configuration

An example output from above url:

{
    "issuer": "http://localhost:8080/auth/realms/demo",
    "authorization_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/auth",
    "token_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/token",
    "userinfo_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/userinfo",
    "end_session_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/logout",
    "jwks_uri": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/certs",
    "grant_types_supported": [
        "authorization_code",
        "refresh_token",
        "password"
    ],
    "response_types_supported": [
        "code"
    ],
    "subject_types_supported": [
        "public"
    ],
    "id_token_signing_alg_values_supported": [
        "RS256"
    ],
    "response_modes_supported": [
        "query"
    ]
}

Found information at https://issues.jboss.org/browse/KEYCLOAK-571

Note: You might need to add your client to the Valid Redirect URI list

Accessing the web page's HTTP Headers in JavaScript

To get the headers as an object which is handier (improvement of Raja's answer):

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
headers = headers.split(/\n|\r|\r\n/g).reduce(function(a, b) {
    if (b.length) {
        var [ key, value ] = b.split(': ');
        a[key] = value;
    }
    return a;
}, {});
console.log(headers);

Concatenate strings from several rows using Pandas groupby

If you want to concatenate your "text" in a list:

df.groupby(['name', 'month'], as_index = False).agg({'text': list})

JavaScript for...in vs for

Douglas Crockford recommends in JavaScript: The Good Parts (page 24) to avoid using the for in statement.

If you use for in to loop over property names in an object, the results are not ordered. Worse: You might get unexpected results; it includes members inherited from the prototype chain and the name of methods.

Everything but the properties can be filtered out with .hasOwnProperty. This code sample does what you probably wanted originally:

for (var name in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, name)) {
        // DO STUFF
    }
}

Change language for bootstrap DateTimePicker

i think you have to set it in the options:

$(".form_datetime").datetimepicker({
    isRTL: false,
    format: 'dd.mm.yyyy hh:ii',
    autoclose:true,
    language: 'ru'
});

if its not working, be sure that:

$.fn.datetimepicker.dates['en'] = {
    days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
    daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
    months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
    monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    today: "Today"
};

is defined for 'ru'

Removing All Items From A ComboBox?

Psuedo code ahead (updated with actual code):

Do While ComboBox1.ListCount > 0
    ComboBox1.RemoveItem (0)
Loop

Basically, while you have items, remove the first item from the combobox. Once all the items have been removed (count = 0), your box is blank.

Method 2: Even better

ComboBox1.Clear

How to get current route in react-router 2.0.0-rc5

After reading some more document, I found the solution:

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md

I just need to access the injected property location of the instance of the component like:

var currentLocation = this.props.location.pathname

Dynamically create Bootstrap alerts box through JavaScript

FWIW I created a JavaScript class that can be used at run-time.
It's over on GitHub, here.

There is a readme there with a more in-depth explanation, but I'll do a quick example below:

var ba = new BootstrapAlert();
ba.addP("Some content here");
$("body").append(ba.render());

The above would create a simple primary alert with a paragraph element inside containing the text "Some content here".

There are also options that can be set on initialisation.
For your requirement you'd do:

var ba = new BootstrapAlert({
    dismissible: true,
    background: 'warning'
});
ba.addP("Invalid Credentials");
$("body").append(ba.render());

The render method will return an HTML element, which can then be inserted into the DOM. In this case, we append it to the bottom of the body tag.

This is a work in progress library, but it still is in a very good working order.

Java method: Finding object in array list given a known attribute value

I was interested to see that the original poster used a style that avoided early exits. Single Entry; Single Exit (SESE) is an interesting style that I've not really explored. It's late and I've got a bottle of cider, so I've written a solution (not tested) without an early exit.

I should have used an iterator. Unfortunately java.util.Iterator has a side-effect in the get method. (I don't like the Iterator design due to its exception ramifications.)

private Dog findDog(int id) {
    int i = 0;
    for (; i!=dogs.length() && dogs.get(i).getID()!=id; ++i) {
        ;
    }

    return i!=dogs.length() ? dogs.get(i) : null;
}

Note the duplication of the i!=dogs.length() expression (could have chosen dogs.get(i).getID()!=id).

Difference between request.getSession() and request.getSession(true)

They both return the same thing, as noted in the documentation you linked; an HttpSession object.

You can also look at a concrete implementation (e.g. Tomcat) and see what it's actually doing: Request.java class. In this case, basically they both call:

Session session = doGetSession(true);

How to store the hostname in a variable in a .bat file?

Why not so?:

set host=%COMPUTERNAME%
echo %host%

Laravel Eloquent - Get one Row

Using Laravel Eloquent you can get one row using first() method,

it returns first row of table if where() condition is not found otherwise it gives the first matched row of given criteria.

Syntax:

Model::where('fieldname',$value)->first();

Example:

$user = User::where('email',$email)->first(); 
//OR
//$user = User::whereEmail($email)->first();

Distinct pair of values SQL

if you want to filter the tuples you can use on this way:

select distinct (case a > b then (a,b) else (b,a) end) from pairs

the good stuff is you don't have to use group by.

drag drop files into standard html file input

Awesome work by @BjarkeCK. I made some modifications to his work, to use it as method in jquery:

$.fn.dropZone = function() {
  var buttonId = "clickHere";
  var mouseOverClass = "mouse-over";

  var dropZone = this[0];
  var $dropZone = $(dropZone);
  var ooleft = $dropZone.offset().left;
  var ooright = $dropZone.outerWidth() + ooleft;
  var ootop = $dropZone.offset().top;
  var oobottom = $dropZone.outerHeight() + ootop;
  var inputFile = $dropZone.find("input[type='file']");
  dropZone.addEventListener("dragleave", function() {
    this.classList.remove(mouseOverClass);
  });
  dropZone.addEventListener("dragover", function(e) {
    console.dir(e);
    e.preventDefault();
    e.stopPropagation();
    this.classList.add(mouseOverClass);
    var x = e.pageX;
    var y = e.pageY;

    if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {
      inputFile.offset({
        top: y - 15,
        left: x - 100
      });
    } else {
      inputFile.offset({
        top: -400,
        left: -400
      });
    }

  }, true);
  dropZone.addEventListener("drop", function(e) {
    this.classList.remove(mouseOverClass);
  }, true);
}

$('#drop-zone').dropZone();

Working Fiddle

How to test if a file is a directory in a batch script?

This is the code that I use in my BATCH files

```
@echo off
set param=%~1
set tempfile=__temp__.txt
dir /b/ad > %tempfile%
set isfolder=false
for /f "delims=" %%i in (temp.txt) do if /i  "%%i"=="%param%" set isfolder=true
del %tempfile%
echo %isfolder%
if %isfolder%==true echo %param% is a directory

```

Android - styling seek bar

LayerDrawable progressDrawable = (LayerDrawable) mSeekBar.getProgressDrawable();

// progress bar line *progress* color
Drawable processDrawable = progressDrawable.findDrawableByLayerId(android.R.id.progress);

// progress bar line *background* color
Drawable backgroundDrawable = progressDrawable.findDrawableByLayerId(android.R.id.background);

// progress bar line *secondaryProgress* color
Drawable secondaryProgressDrawable = progressDrawable.findDrawableByLayerId(android.R.id.secondaryProgress);
processDrawable.setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);

// progress bar line all color
mSeekBar.getProgressDrawable().setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_IN);

// progress circle color
mSeekBar.getThumb().setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN);

Pass values of checkBox to controller action in asp.net mvc4

try using form collection

<input id="responsable" value="True" name="checkResp" type="checkbox" /> 

[HttpPost]
public ActionResult Index(FormCollection collection)
{
     if(!string.IsNullOrEmpty(collection["checkResp"])
     {
        string checkResp=collection["checkResp"];
        bool checkRespB=Convert.ToBoolean(checkResp);
     }

}

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

You do not need to use substring at all since your format doesn't hold that info.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";  
Date fechaNueva = format.parse(fechaStr);

System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29

Func vs. Action vs. Predicate

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).

Func is probably most commonly used in LINQ - for example in projections:

 list.Select(x => x.SomeProperty)

or filtering:

 list.Where(x => x.SomeValue == someOtherValue)

or key selection:

 list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list. I use this less often than Func, although I do sometimes use the parameterless version for things like Control.BeginInvoke and Dispatcher.BeginInvoke.

Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we'd already had Func and Action in their various guises, Predicate wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.

Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.

Wampserver icon not going green fully, mysql services not starting up?

Basically this happens when you have not installed pre required software installed on your machine while installing Wampserver you might have got error bellow error at the time of installation.

program can't start because msvcr120.dll is missing OR

program can't start because msvcr120.dll is missing

If you fixed those issue after the installation of wampserver then you might get stuck at this problem.

Then You can simply uninstall and install wamp server again

And If you have not install pre required dependency then first of all uninstall wampserver . And then install pre requirement first and then finally you can install Wampserver and it should work now.

you can download Pre-required applications from following link

For x64 Machines

microsoft visual c++ 2010 redistributable package (x64) https://www.microsoft.com/en-in/download/details.aspx?id=14632

Visual C++ Redistributable for Visual Studio 2012 Update 4 https://www.microsoft.com/en-in/download/details.aspx?id=30679

Visual C++ Redistributable Packages for Visual Studio 2013 https://www.microsoft.com/en-in/download/details.aspx?id=40784

Visual C++ Redistributable for Visual Studio 2015 https://www.microsoft.com/en-in/download/details.aspx?id=48145

For x86 Machines

Microsoft Visual C++ 2010 Redistributable Package (x86) https://www.microsoft.com/en-in/download/details.aspx?id=14632

Visual C++ Redistributable for Visual Studio 2012 Update 4 https://www.microsoft.com/en-in/download/details.aspx?id=30679

Visual C++ Redistributable Packages for Visual Studio 2013 https://www.microsoft.com/en-in/download/details.aspx?id=40784

Visual C++ Redistributable for Visual Studio 2015 https://www.microsoft.com/en-in/download/details.aspx?id=48145

Note:- Take backup of your project files before uninstall

How to compare each item in a list with the rest, only once?

I think using enumerate on the outer loop and using the index to slice the list on the inner loop is pretty Pythonic:

for index, this in enumerate(mylist):
    for that in mylist[index+1:]:
        compare(this, that)

Cannot find firefox binary in PATH. Make sure firefox is installed

Another option is to configure the server rather than the test client.

Configure the slave node service so that it knows where the firefox is. Install location can change from node to node, or even need multiple services running on a node to support access to different versions of FF.

java -jar "selenium-server-standalone-2.2.0.jar"
 -Dwebdriver.firefox.bin="C:\FirefoxCollection\Mozilla Firefox 36.0\firefox.exe"

How to add a ScrollBar to a Stackpanel

If you mean, you want to scroll through multiple items in your stackpanel, try putting a grid around it. By definition, a stackpanel has infinite length.

So try something like this:

   <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <StackPanel Width="311">
              <TextBlock Text="{Binding A}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" FontStretch="Condensed" FontSize="28" />
              <TextBlock Text="{Binding B}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
        </StackPanel>
    </Grid>

You could even make this work with a ScrollViewer

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

Razor View Engine : An expression tree may not contain a dynamic operation

Seems like your view is typed dynamic. Set the right type on the view and you'll see the error go away.

C# how to change data in DataTable?

Try the SetField method:

table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);

This should get the job done and is a bit "cleaner" than using Rows[i][j].

HTML / CSS Popup div on text click

DEMO

In the content area you can provide whatever you want to display in it.

_x000D_
_x000D_
.black_overlay {_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 0%;_x000D_
  left: 0%;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background-color: black;_x000D_
  z-index: 1001;_x000D_
  -moz-opacity: 0.8;_x000D_
  opacity: .80;_x000D_
  filter: alpha(opacity=80);_x000D_
}_x000D_
.white_content {_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 25%;_x000D_
  left: 25%;_x000D_
  width: 50%;_x000D_
  height: 50%;_x000D_
  padding: 16px;_x000D_
  border: 16px solid orange;_x000D_
  background-color: white;_x000D_
  z-index: 1002;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>LIGHTBOX EXAMPLE</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <p>This is the main content. To display a lightbox click <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a>_x000D_
  </p>_x000D_
  <div id="light" class="white_content">This is the lightbox content. <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>_x000D_
  </div>_x000D_
  <div id="fade" class="black_overlay"></div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Declare and initialize a Dictionary in Typescript

Edit: This has since been fixed in the latest TS versions. Quoting @Simon_Weaver's comment on the OP's post:

Note: this has since been fixed (not sure which exact TS version). I get these errors in VS, as you would expect: Index signatures are incompatible. Type '{ firstName: string; }' is not assignable to type 'IPerson'. Property 'lastName' is missing in type '{ firstName: string; }'.


Apparently this doesn't work when passing the initial data at declaration. I guess this is a bug in TypeScript, so you should raise one at the project site.

You can make use of the typed dictionary by splitting your example up in declaration and initialization, like:

var persons: { [id: string] : IPerson; } = {};
persons["p1"] = { firstName: "F1", lastName: "L1" };
persons["p2"] = { firstName: "F2" }; // will result in an error

OnChange event using React JS for drop down

Thank you Felix Kling, but his answer need a little change:

var MySelect = React.createClass({
 getInitialState: function() {
     return {
         value: 'select'
     }
 },
 change: function(event){
     this.setState({value: event.target.value});
 },
 render: function(){
    return(
       <div>
           <select id="lang" onChange={this.change.bind(this)} value={this.state.value}>
              <option value="select">Select</option>
              <option value="Java">Java</option>
              <option value="C++">C++</option>
           </select>
           <p></p>
           <p>{this.state.value}</p>
       </div>
    );
 }
});
React.render(<MySelect />, document.body); 

Using async/await with a forEach loop

Similar to Antonio Val's p-iteration, an alternative npm module is async-af:

const AsyncAF = require('async-af');
const fs = require('fs-promise');

function printFiles() {
  // since AsyncAF accepts promises or non-promises, there's no need to await here
  const files = getFilePaths();

  AsyncAF(files).forEach(async file => {
    const contents = await fs.readFile(file, 'utf8');
    console.log(contents);
  });
}

printFiles();

Alternatively, async-af has a static method (log/logAF) that logs the results of promises:

const AsyncAF = require('async-af');
const fs = require('fs-promise');

function printFiles() {
  const files = getFilePaths();

  AsyncAF(files).forEach(file => {
    AsyncAF.log(fs.readFile(file, 'utf8'));
  });
}

printFiles();

However, the main advantage of the library is that you can chain asynchronous methods to do something like:

const aaf = require('async-af');
const fs = require('fs-promise');

const printFiles = () => aaf(getFilePaths())
  .map(file => fs.readFile(file, 'utf8'))
  .forEach(file => aaf.log(file));

printFiles();

async-af

C# Pass Lambda Expression as Method Parameter

Use a Func<T1, T2, TResult> delegate as the parameter type and pass it in to your Query:

public List<IJob> getJobs(Func<FullTimeJob, Student, FullTimeJob> lambda)
{
  using (SqlConnection connection = new SqlConnection(getConnectionString())) {
    connection.Open();
    return connection.Query<FullTimeJob, Student, FullTimeJob>(sql, 
        lambda,
        splitOn: "user_id",
        param: parameters).ToList<IJob>();   
  }  
}

You would call it:

getJobs((job, student) => {         
        job.Student = student;
        job.StudentId = student.Id;
        return job;
        });

Or assign the lambda to a variable and pass it in.

Sending images using Http Post

I struggled a lot trying to implement posting a image from Android client to servlet using httpclient-4.3.5.jar, httpcore-4.3.2.jar, httpmime-4.3.5.jar. I always got a runtime error. I found out that basically you cannot use these jars with Android as Google is using older version of HttpClient in Android. The explanation is here http://hc.apache.org/httpcomponents-client-4.3.x/android-port.html. You need to get the httpclientandroidlib-1.2.1 jar from android http-client library. Then change your imports from or.apache.http.client to ch.boye.httpclientandroidlib. Hope this helps.

Singleton with Arguments in Java

Singleton is, of course, an "anti-pattern" (assuming a definition of a static with variable state).

If you want a fixed set of immutable value objects, then enums are the way to go. For a large, possibly open-ended set of values, you can use a Repository of some form - usually based on a Map implementation. Of course, when you are dealing with statics be careful with threading (either synchronise sufficiently widely or use a ConcurrentMap either checking that another thread hasn't beaten you or use some form of futures).

Regular Expression to match string starting with a specific word

If you want to match anything after a word stop an not only at the start of the line you may use : \bstop.*\b - word followed by line

Word till the end of string

Or if you want to match the word in the string use \bstop[a-zA-Z]* - only the words starting with stop

Only the words starting with stop

Or the start of lines with stop ^stop[a-zA-Z]* for the word only - first word only
The whole line ^stop.* - first line of the string only

And if you want to match every string starting with stop including newlines use : /^stop.*/s - multiline string starting with stop

How to make exe files from a node.js app?

Try disclose: https://github.com/pmq20/disclose

disclose essentially makes a self-extracting exe out of your Node.js project and Node.js interpreter with the following characteristics,

  1. No GUI. Pure CLI.
  2. No run-time dependencies
  3. Supports both Windows and Unix
  4. Runs slowly for the first time (extracting to a cache dir), then fast forever

Try node-compiler: https://github.com/pmq20/node-compiler

I have made a new project called node-compiler to compile your Node.js project into one single executable.

It is better than disclose in that it never runs slowly for the first time, since your source code is compiled together with Node.js interpreter, just like the standard Node.js libraries.

Additionally, it redirect file and directory requests transparently to the memory instead of to the file system at runtime. So that no source code is required to run the compiled product.

How it works: https://speakerdeck.com/pmq20/node-dot-js-compiler-compiling-your-node-dot-js-application-into-a-single-executable

Comparing with Similar Projects,

  • pkg(https://github.com/zeit/pkg): Pkg hacked fs.* API's dynamically in order to access in-package files, whereas Node.js Compiler leaves them alone and instead works on a deeper level via libsquash. Pkg uses JSON to store in-package files while Node.js Compiler uses the more sophisticated and widely used SquashFS as its data structure.

  • EncloseJS(http://enclosejs.com/): EncloseJS restricts access to in-package files to only five fs.* API's, whereas Node.js Compiler supports all fs.* API's. EncloseJS is proprietary licensed and charges money when used while Node.js Compiler is MIT-licensed and users are both free to use it and free to modify it.

  • Nexe(https://github.com/nexe/nexe): Nexe does not support dynamic require because of its use of browserify, whereas Node.js Compiler supports all kinds of require including require.resolve.

  • asar(https://github.com/electron/asar): Asar uses JSON to store files' information while Node.js Compiler uses SquashFS. Asar keeps the code archive and the executable separate while Node.js Compiler links all JavaScript source code together with the Node.js virtual machine and generates a single executable as the final product.

  • AppImage(http://appimage.org/): AppImage supports only Linux with a kernel that supports SquashFS, while Node.js Compiler supports all three platforms of Linux, macOS and Windows, meanwhile without any special feature requirements from the kernel.

Request is not available in this context

Please see IIS7 Integrated mode: Request is not available in this context exception in Application_Start:

The “Request is not available in this context” exception is one of the more common errors you may receive on when moving ASP.NET applications to Integrated mode on IIS 7.0. This exception happens in your implementation of the Application_Start method in the global.asax file if you attempt to access the HttpContext of the request that started the application.

SQLite table constraint - unique on multiple columns

Be careful how you define the table for you will get different results on insert. Consider the following



CREATE TABLE IF NOT EXISTS t1 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT);
INSERT INTO t1 (a, b) VALUES
    ('Alice', 'Some title'),
    ('Bob', 'Palindromic guy'),
    ('Charles', 'chucky cheese'),
    ('Alice', 'Some other title') 
    ON CONFLICT(a) DO UPDATE SET b=excluded.b;
CREATE TABLE IF NOT EXISTS t2 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT, UNIQUE(a) ON CONFLICT REPLACE);
INSERT INTO t2 (a, b) VALUES
    ('Alice', 'Some title'),
    ('Bob', 'Palindromic guy'),
    ('Charles', 'chucky cheese'),
    ('Alice', 'Some other title');

$ sqlite3 test.sqlite
SQLite version 3.28.0 2019-04-16 19:49:53
Enter ".help" for usage hints.
sqlite> CREATE TABLE IF NOT EXISTS t1 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT);
sqlite> INSERT INTO t1 (a, b) VALUES
   ...>     ('Alice', 'Some title'),
   ...>     ('Bob', 'Palindromic guy'),
   ...>     ('Charles', 'chucky cheese'),
   ...>     ('Alice', 'Some other title') 
   ...>     ON CONFLICT(a) DO UPDATE SET b=excluded.b;
sqlite> CREATE TABLE IF NOT EXISTS t2 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT, UNIQUE(a) ON CONFLICT REPLACE);
sqlite> INSERT INTO t2 (a, b) VALUES
   ...>     ('Alice', 'Some title'),
   ...>     ('Bob', 'Palindromic guy'),
   ...>     ('Charles', 'chucky cheese'),
   ...>     ('Alice', 'Some other title');
sqlite> .mode col
sqlite> .headers on
sqlite> select * from t1;
id          a           b               
----------  ----------  ----------------
1           Alice       Some other title
2           Bob         Palindromic guy 
3           Charles     chucky cheese   
sqlite> select * from t2;
id          a           b              
----------  ----------  ---------------
2           Bob         Palindromic guy
3           Charles     chucky cheese  
4           Alice       Some other titl
sqlite> 

While the insert/update effect is the same, the id changes based on the table definition type (see the second table where 'Alice' now has id = 4; the first table is doing more of what I expect it to do, keep the PRIMARY KEY the same). Be aware of this effect.

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

Try changing server name to "localhost"

pymssql.connect(server="localhost", user="myusername", password="mypwd", database="temp",port="1433")

jQuery equivalent of JavaScript's addEventListener method

The closest thing would be the bind function:

http://api.jquery.com/bind/

$('#foo').bind('click', function() {
  alert('User clicked on "foo."');
});

MSSQL Error 'The underlying provider failed on Open'

This is common issue only. Even I have faced this issue. On the development machine, configured with Windows authentication, it is worked perfectly:

<add name="ShoppingCartAdminEntities" connectionString="metadata=res://*/ShoppingCartAPIModel.csdl|res://*/ShoppingCartAPIModel.ssdl|res://*/ShoppingCartAPIModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQlExpress;initial catalog=ShoppingCartAdmin;Integrated Security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />

Once hosted in IIS with the same configuration, I got this error:

The underlying provider failed on Open

It was solved changing connectionString in the configuration file:

<add name="MyEntities" connectionString="metadata=res://*/ShoppingCartAPIModel.csdl|res://*/ShoppingCartAPIModel.ssdl|res://*/ShoppingCartAPIModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MACHINE_Name\SQlExpress;initial catalog=ShoppingCartAdmin;persist security info=True;user id=sa;password=notmyrealpassword;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />

Other common mistakes could be:

  1. Database service could be stopped
  2. Data Source attributes pointing to a local database with Windows authentication and hosted in IIS
  3. Username and password could be wrong.

Android getting value from selected radiobutton

RadioGroup in XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Java"/>

    </RadioGroup>
</RelativeLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp"
        android:layout_marginLeft="100dp"
        android:textSize="18dp"
        android:text="Select Your Course"
        android:textStyle="bold"
        android:id="@+id/txtView"/>
<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/rdGroup"
    android:layout_below="@+id/txtView">
    <RadioButton
        android:id="@+id/rdbJava"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="Java"
        android:onClick="onRadioButtonClicked"/>
    <RadioButton
        android:id="@+id/rdbPython"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="Python"
        android:onClick="onRadioButtonClicked"/>
    <RadioButton
        android:id="@+id/rdbAndroid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="Android"
        android:onClick="onRadioButtonClicked"/>
    <RadioButton
        android:id="@+id/rdbAngular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="AngularJS"
        android:onClick="onRadioButtonClicked"/>
</RadioGroup>
    <Button
        android:id="@+id/getBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_below="@+id/rdGroup"
        android:text="Get Course" />
</RelativeLayout>

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    RadioButton android, java, angular, python;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        android = (RadioButton)findViewById(R.id.rdbAndroid);
        angular = (RadioButton)findViewById(R.id.rdbAngular);
        java = (RadioButton)findViewById(R.id.rdbJava);
        python = (RadioButton)findViewById(R.id.rdbPython);
        Button btn = (Button)findViewById(R.id.getBtn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String result = "Selected Course: ";
                result+= (android.isChecked())?"Android":(angular.isChecked())?"AngularJS":(java.isChecked())?"Java":(python.isChecked())?"Python":"";
                Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void onRadioButtonClicked(View view) {
        boolean checked = ((RadioButton) view).isChecked();
        String str="";
        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.rdbAndroid:
                if(checked)
                str = "Android Selected";
                break;
            case R.id.rdbAngular:
                if(checked)
                str = "AngularJS Selected";
                break;
            case R.id.rdbJava:
                if(checked)
                str = "Java Selected";
                break;
            case R.id.rdbPython:
                if(checked)
                str = "Python Selected";
                break;
        }
        Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
    }
}

How to remove indentation from an unordered list item?

Remove the padding:

padding-left: 0;

Get User's Current Location / Coordinates

@wonderwhy I have added my code screenshot. pls check it. You will have to add <code>NSLocationWhenInUseUsageDescription in the plist for authorisation.</code>

NSLocationWhenInUseUsageDescription = Request permission to use location service when the apps is in background. in your plist file.

If this works then please vote the answer.

How to convert minutes to hours/minutes and add various time values together using jQuery?

Not a jquery plugin, but the DateJS Library appears to do what you require. The Getting Started page has a number of examples.

What's the difference between a POST and a PUT HTTP REQUEST?

In simple words you can say:

1.HTTP Get:It is used to get one or more items

2.HTTP Post:It is used to create an item

3.HTTP Put:It is used to update an item

4.HTTP Patch:It is used to partially update an item

5.HTTP Delete:It is used to delete an item

Map a network drive to be used by a service

A better way would be to use a symbolic link using mklink.exe. You can just create a link in the file system that any app can use. See http://en.wikipedia.org/wiki/NTFS_symbolic_link.

What does %w(array) mean?

I was given a bunch of columns from a CSV spreadsheet of full names of users and I needed to keep the formatting, with spaces. The easiest way I found to get them in while using ruby was to do:

names = %( Porter Smith
Jimmy Jones
Ronald Jackson).split('\n')

This highlights that %() creates a string like "Porter Smith\nJimmyJones\nRonald Jackson" and to get the array you split the string on the "\n" ["Porter Smith", "Jimmy Jones", "Ronald Jackson"]

So to answer the OP's original question too, they could have wrote %(cgi\ spaeinfilename.rb;complex.rb;date.rb).split(';') if there happened to be space when you want the space to exist in the final array output.

How do I get out of 'screen' without typing 'exit'?

In addition to the previous answers, you can also do Ctrl + A, and then enter colon (:), and you will notice a little input box at the bottom left. Type 'quit' and Enter to leave the current screen session. Note that this will remove your screen session.

Ctrl + A and then K will only kill the current window in the current session, not the whole session. A screen session consists of windows, which can be created using subsequent Ctrl + A followed by C. These windows can be viewed in a list using Ctrl + A + ".

How can I convert ticks to a date format?

Answers so far helped me come up with mine. I'm wary of UTC vs local time; ticks should always be UTC IMO.

public class Time
{
    public static void Timestamps()
    {
        OutputTimestamp();
        Thread.Sleep(1000);
        OutputTimestamp();
    }

    private static void OutputTimestamp()
    {
        var timestamp = DateTime.UtcNow.Ticks;
        var localTicks = DateTime.Now.Ticks;
        var localTime = new DateTime(timestamp, DateTimeKind.Utc).ToLocalTime();
        Console.Out.WriteLine("Timestamp = {0}.  Local ticks = {1}.  Local time = {2}.", timestamp, localTicks, localTime);
    }
}

Output:

Timestamp = 636988286338754530.  Local ticks = 636988034338754530.  Local time = 2019-07-15 4:03:53 PM.
Timestamp = 636988286348878736.  Local ticks = 636988034348878736.  Local time = 2019-07-15 4:03:54 PM.

Bootstrap Align Image with text

use the grid-system of boostrap , more information here

for example

<div class="row">
  <div class="col-md-4">here img</div>
  <div class="col-md-4">here text</div>
</div>

in this way when the page will shrink the second div(the text) will be found under the first(the image)

Side-by-side list items as icons within a div (css)

give the LI float: left (or right)

They will all be in the same line until there will be no more room in the container (your case, a ul). (forgot): If you have a block element after the floating elements, he will also stick to them, unless you give him a clear:both, OR put an empty div before it with clear:both

How do I check/uncheck all checkboxes with a button using jQuery?

Try This One:

HTML

<input type="checkbox" name="all" id="checkall" />

JavaScript

$('#checkall:checkbox').change(function () {
   if($(this).attr("checked")) $('input:checkbox').attr('checked','checked');
   else $('input:checkbox').removeAttr('checked');
});?

DEMO

Negate if condition in bash script

Since you're comparing numbers, you can use an arithmetic expression, which allows for simpler handling of parameters and comparison:

wget -q --tries=10 --timeout=20 --spider http://google.com
if (( $? != 0 )); then
    echo "Sorry you are Offline"
    exit 1
fi

Notice how instead of -ne, you can just use !=. In an arithmetic context, we don't even have to prepend $ to parameters, i.e.,

var_a=1
var_b=2
(( var_a < var_b )) && echo "a is smaller"

works perfectly fine. This doesn't appply to the $? special parameter, though.

Further, since (( ... )) evaluates non-zero values to true, i.e., has a return status of 0 for non-zero values and a return status of 1 otherwise, we could shorten to

if (( $? )); then

but this might confuse more people than the keystrokes saved are worth.

The (( ... )) construct is available in Bash, but not required by the POSIX shell specification (mentioned as possible extension, though).

This all being said, it's better to avoid $? altogether in my opinion, as in Cole's answer and Steven's answer.

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

Unstaged changes left after git reset --hard

As other answers have pointed out, the problem is because of line-end auto correcting. I encountered this issue with *.svg files. I used svg file for icons in my project.

To solve this issue, I let git know that svg files should be treated as binary instead of text by adding the below line to .gitattributes

*.svg binary

How to make a checkbox checked with jQuery?

You don't need to control your checkBoxes with jQuery. You can do it with some simple JavaScript.

This JS snippet should work fine:

document.TheFormHere.test.Value = true;

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

Hi I found this link that helped me understand the issue. Hope it is useful. Version released so far are

  • Java SE 8 = 52,
  • Java SE 7 = 51,
  • Java SE 6.0 = 50,
  • Java SE 5.0 = 49,
  • JDK 1.4 = 48,
  • JDK 1.3 = 47,
  • JDK 1.2 = 46,
  • JDK 1.1 = 45

and from thata data it simply means

Many people think why do you get a version mismatch error if Java is backward compatible. Well, its true that Java is backward compatible, which means you can run a Java class file or Java binary (JAR file) compiled in lower version (java 6) into higher version e.g. Java 8, but it doesn't mean that you can run a class compiled using Java 7 into Java 5, Why? because higher version usually have features which are not supported by lower version.

Sometimes you may have more than one version of Java installed in you machine. Make sure the application you are running is pointing to the right or highest version available.

How to read input with multiple lines in Java

package pac001;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Entry_box{



    public static final String[] relationship = {"Marrid", "Unmarried"};


    public static void main(String[] args)
    {
         //TAKING USER ID NUMBER
            int a = Integer.parseInt(JOptionPane.showInputDialog("Enter ID no: "));
        // TAKING INPUT FOR RELATIONSHIP
        JFrame frame = new JFrame("Input Dialog Example #3");
        String Relationship =   (String) JOptionPane.showInputDialog(frame,"Select Your Relationship","Married",
                                JOptionPane.QUESTION_MESSAGE, null, relationship,relationship[0]);



        //PRINTING THE ID NUMBER
        System.out.println("ID no: "+a);
        // PRINTING RESULT FOR RELATIONSHIP INPUT
          System.out.printf("Mariitual Status: %s\n", Relationship);

        }
}

How to pass parameters to a Script tag?

It's better to Use feature in html5 5 data Attributes

<script src="http://path.to/widget.js" data-width="200" data-height="200">
</script>

Inside the script file http://path.to/widget.js you can get the paremeters in that way:

<script>
function getSyncScriptParams() {
         var scripts = document.getElementsByTagName('script');
         var lastScript = scripts[scripts.length-1];
         var scriptName = lastScript;
         return {
             width : scriptName.getAttribute('data-width'),
             height : scriptName.getAttribute('data-height')
         };
 }
</script>

NoClassDefFoundError - Eclipse and Android

By adding the external jar into your build path just adds the jar to your package, but it will not be available during runtime.

In order for the jar to be available at runtime, you need to:

  • Put the jar under your assets folder
  • Include this copy of the jar in your build path
  • Go to the export tab on the same popup window
  • Check the box against the newly added jar

Change GitHub Account username

Yes, it's possible. But first read, "What happens when I change my username?"

To change your username, click your profile picture in the top right corner, then click Settings. On the left side, click Account. Then click Change username.

Resizing an Image without losing any quality

As rcar says, you can't without losing some quality, the best you can do in c# is:

Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics gr = Graphics.FromImage(newImage))
{
    gr.SmoothingMode = SmoothingMode.HighQuality;
    gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
    gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
    gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
}

How to grant remote access permissions to mysql server for user?

Ubuntu 18.04

Install and ensure mysqld us running..

Go into database and setup root user:

sudo mysql -u root
SELECT User,Host FROM mysql.user;
DROP USER 'root'@'localhost';
CREATE USER 'root'@'%' IDENTIFIED BY 'obamathelongleggedmacdaddy';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
exit;

Edit mysqld permissions and restart:

sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf

# edit the line to be this:
bind-address=0.0.0.0

sudo systemctl stop mysql
sudo systemctl start mysql

From another machine, test.. Obvs port (3306) on mysqld machine must allow connection from test machine.

mysql -u root -p -h 123.456.789.666

All the additional "security" of MySql doesn't help security at all, it just complicates and obfuscates, it is now actually easier to screw it up than in the old days, where you just used a really long password.

Take nth column in a text file

If you are using structured data, this has the added benefit of not invoking an extra shell process to run tr and/or cut or something. ...

(Of course, you will want to guard against bad inputs with conditionals and sane alternatives.)

...
while read line ; 
do 
    lineCols=( $line ) ;
    echo "${lineCols[0]}"
    echo "${lineCols[1]}"
done < $myFQFileToRead ; 
...

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

You need to add the SID entry for XE in order to register the instance with the listener.

After installation of Oracle XE, everything looks good, but when you issue

C:\>sqlplus / as sysdba
SQL>shutdown immediate
SQL>startup

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

the instance will not register with the listener.

So please edit your listener.ora like this:

SID_LIST_LISTENER =
  (SID_LIST =
     (SID_DESC =
       (SID_NAME = XE)
       (ORACLE_HOME = C:\oraclexe\app\oracle\product\10.2.0\server)
     )
     (SID_DESC =
        (SID_NAME = PLSExtProc)
        (ORACLE_HOME = D:\oraclexe\app\oracle\product\10.2.0\server)
        (PROGRAM = extproc)
     )
     (SID_DESC =
       (SID_NAME = CLRExtProc)
       (ORACLE_HOME = D:\oraclexe\app\oracle\product\10.2.0\server)
       (PROGRAM = extproc)
     )
  )

This issue came up when I installed Oracle XE on Windows 7. I did not face this problem on Windows XP. In general, this entry should not be necessary, because the instance should register with the listener automatically. Running Oracle XE on Linux (Fedora), there is no need to add XE to the sid-list.

How to set a cookie to expire in 1 hour in Javascript?

You can write this in a more compact way:

var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000);
document.cookie = "name=value; expires=" + now.toUTCString() + "; path=/";

And for someone like me, who wasted an hour trying to figure out why the cookie with expiration is not set up (but without expiration can be set up) in Chrome, here is in answer:

For some strange reason Chrome team decided to ignore cookies from local pages. So if you do this on localhost, you will not be able to see your cookie in Chrome. So either upload it on the server or use another browser.

PHP check if date between two dates

The above methods are useful but they are not full-proof because it will give error if time is between 12:00 AM/PM and 01:00 AM/PM . It will return the "No Go" in-spite of being in between the timing . Here is the code for the same:

$time = '2019-03-27 12:00 PM';

$date_one = $time; 
$date_one = strtotime($date_one);
$date_one = strtotime("+60 minutes", $date_one);
$date_one =  date('Y-m-d h:i A', $date_one);

$date_ten = strtotime($time); 
$date_ten = strtotime("-12 minutes", $date_ten); 
$date_ten = date('Y-m-d h:i A', $date_ten);

$paymentDate='2019-03-27 12:45 AM';

$contractDateBegin = date('Y-m-d h:i A', strtotime($date_ten)); 
$contractDateEnd = date('Y-m-d h:i A', strtotime($date_one));

echo $paymentDate; 
echo "---------------"; 
echo $contractDateBegin; 
echo "---------------"; 
echo $contractDateEnd; 
echo "---------------";

$contractDateEnd='2019-03-27 01:45 AM';

if($paymentDate > $contractDateBegin && $paymentDate < $contractDateEnd)  
{  
 echo "is between";
} 
else
{  
  echo "NO GO!";  
}

Here you will get output "NO Go" because 12:45 > 01:45.

To get proper output date in between, make sure that for "AM" values from 01:00 AM to 12:00 AM will get converted to the 24-hour format. This little trick helped me.

Calculate a MD5 hash from a string

// given, a password in a string
string password = @"1234abcd";

// byte array representation of that string
byte[] encodedPassword = new UTF8Encoding().GetBytes(password);

// need MD5 to calculate the hash
byte[] hash = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedPassword);

// string representation (similar to UNIX format)
string encoded = BitConverter.ToString(hash)
   // without dashes
   .Replace("-", string.Empty)
   // make lowercase
   .ToLower();

// encoded contains the hash you want

How do I select an element in jQuery by using a variable for the ID?

The shortest way would be:

$("#" + row_id)

Limiting the search to the body doesn't have any benefit.

Also, you should consider renaming your ids to something more meaningful (and HTML compliant as per Paolo's answer), especially if you have another set of data that needs to be named as well.

What's the simplest way to extend a numpy array in 2 dimensions?

The shortest in terms of lines of code i can think of is for the first question.

>>> import numpy as np
>>> p = np.array([[1,2],[3,4]])

>>> p = np.append(p, [[5,6]], 0)
>>> p = np.append(p, [[7],[8],[9]],1)

>>> p
array([[1, 2, 7],
   [3, 4, 8],
   [5, 6, 9]])

And the for the second question

    p = np.array(range(20))
>>> p.shape = (4,5)
>>> p
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
>>> n = 2
>>> p = np.append(p[:n],p[n+1:],0)
>>> p = np.append(p[...,:n],p[...,n+1:],1)
>>> p
array([[ 0,  1,  3,  4],
       [ 5,  6,  8,  9],
       [15, 16, 18, 19]])

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

You can go to IE Tools -> Internet options -> Advanced Tab. Under Advanced, check for security and put a check on the 1st 2 options which says,"Allow active content from CDs to run on My Computer* and Allow active content to run in files on My Computer*"

Restart your browser and the ActiveX scripts will not be shown.

How can I run Tensorboard on a remote server?

This is not a proper answer but a troubleshooter, hopefully helps other less seasoned networkers like me.

In my case (firefox+ubuntu16) the browser was connecting, but showing a blank page (with the tensorboard logo on the tab), and no log activity at all was shown. I still don't know what could be the reason for that (didn't look much into it but if anybody knows please let know!), but I solved it switching to ubuntu's default browser. Here the exact steps, pretty much the same as in @Olivier Moindrot's answer:

  1. On the server, start tensorboard: tensorboard --logdir=. --host=localhost --port=6006
  2. On the client, open the ssh tunnel ssh -p 23 <USER>@<SERVER> -N -f -L localhost:16006:localhost:6006
  3. Open ubuntu's Browser and visit localhost:16006. The tensorboard page should load without much delay.

To check that the SSH tunnel is effectively working, a simple echo server like this python script can help:

  1. Put the script into an <ECHO>.py file in the server and run it with python <ECHO>.py. Now the server will have the echo script listening on 0.0.0.0:5555.
  2. On the client, open the ssh tunnel ssh -p <SSH_PORT> <USER>@<SERVER> -N -f -L localhost:12345:localhost:5555
  3. On the client, in the same terminal used to open the tunnel (step 2.), issuing telnet localhost 12345 will connect to the echo script running in the server. Typing hello and pressing enter should print hello back. If that is the case, your SSH tunnel is working. This was my case, and lead me to the conclusion that the problem involved the browser. Trying to connect from a different terminal caused the terminal to freeze.

As I said, hope it helps!
Cheers,
Andres

SOAP vs REST (differences)

Among many others already covered in the many answers, I would highlight that SOAP enables to define a contract, the WSDL, which define the operations supported, complex types, etc. SOAP is oriented to operations, but REST is oriented at resources. Personally I would select SOAP for complex interfaces between internal enterprise applications, and REST for public, simpler, stateless interfaces with the outside world.

enter image description here

How to set div width using ng-style

The syntax of ng-style is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:

<div ng-style="{ 'width' : width, 'background' : bgColor }"></div>

And then in your controller:

$scope.width = '900px';
$scope.bgColor = 'red';

This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.