Programs & Examples On #Ntp

Network Time Protocol is an application level network protocol that is used for synchronizing clocks of computer systems. The term also refers to the reference software implementation.

how to sync windows time from a ntp time server in command

Use net time net time \\timesrv /set /yes

after your comment try this one in evelated prompt :

w32tm /config /update /manualpeerlist:yourtimerserver

How to make sure docker's time syncs with that of the host?

Windows users:

The solution is very simple. Simply open a powershell prompt and enter:

docker run --privileged --rm alpine date -s "$(Get-Date ([datetime]::UtcNow) -UFormat "+%Y-%m-%d %H:%M:%S")"

To check that it works, run the command:

docker run --rm -it alpine date


My solution is inspired by something I found in docker forum thread. Anyways, it was the only solution that worked for me on docker desktop, except for restarting my machine (which also works). Here's a link to the original thread: https://forums.docker.com/t/syncing-clock-with-host/10432/23

The difference between the thread answer and mine is that mine converts the time to UTC time, which is necessary for e.g. AWS. Otherwise, the original answer from the forum looks like this:

docker run --privileged --rm alpine date -s "$(date -u "+%Y-%m-%d %H:%M:%S")"

How to Query an NTP Server using C#?

Since the old accepted answer got deleted (It was a link to a Google code search results that no longer exist), I figured I could answer this question for future reference :

public static DateTime GetNetworkTime()
{
    //default Windows time server
    const string ntpServer = "time.windows.com";

    // NTP message size - 16 bytes of the digest (RFC 2030)
    var ntpData = new byte[48];

    //Setting the Leap Indicator, Version Number and Mode values
    ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)

    var addresses = Dns.GetHostEntry(ntpServer).AddressList;

    //The UDP port number assigned to NTP is 123
    var ipEndPoint = new IPEndPoint(addresses[0], 123);
    //NTP uses UDP

    using(var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
    {
        socket.Connect(ipEndPoint);

        //Stops code hang if NTP is blocked
        socket.ReceiveTimeout = 3000;     

        socket.Send(ntpData);
        socket.Receive(ntpData);
        socket.Close();
    }

    //Offset to get to the "Transmit Timestamp" field (time at which the reply 
    //departed the server for the client, in 64-bit timestamp format."
    const byte serverReplyTime = 40;

    //Get the seconds part
    ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);

    //Get the seconds fraction
    ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);

    //Convert From big-endian to little-endian
    intPart = SwapEndianness(intPart);
    fractPart = SwapEndianness(fractPart);

    var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

    //**UTC** time
    var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);

    return networkDateTime.ToLocalTime();
}

// stackoverflow.com/a/3294698/162671
static uint SwapEndianness(ulong x)
{
    return (uint) (((x & 0x000000ff) << 24) +
                   ((x & 0x0000ff00) << 8) +
                   ((x & 0x00ff0000) >> 8) +
                   ((x & 0xff000000) >> 24));
}

Note: You will have to add the following namespaces

using System.Net;
using System.Net.Sockets;

Is Android using NTP to sync time?

Not an exact answer to your question, but a bit of information: if your device does use NTP for time (eg. if it is a tablet with no 3G or GPS capabilities), the server can be configured in /system/etc/gps.conf - obviously this file can only be edited with root access, but is viewable on non-rooted devices.

How to find length of digits in an integer?

As mentioned the dear user @Calvintwr, the function math.log10 has problem in a number outside of a range [-999999999999997, 999999999999997], where we get floating point errors. I had this problem with the JavaScript (the Google V8 and the NodeJS) and the C (the GNU GCC compiler), so a 'purely mathematically' solution is impossible here.


Based on this gist and the answer the dear user @Calvintwr

import math


def get_count_digits(number: int):
    """Return number of digits in a number."""

    if number == 0:
        return 1

    number = abs(number)

    if number <= 999999999999997:
        return math.floor(math.log10(number)) + 1

    count = 0
    while number:
        count += 1
        number //= 10
    return count

I tested it on numbers with length up to 20 (inclusive) and all right. It must be enough, because the length max integer number on a 64-bit system is 19 (len(str(sys.maxsize)) == 19).

assert get_count_digits(-99999999999999999999) == 20
assert get_count_digits(-10000000000000000000) == 20
assert get_count_digits(-9999999999999999999) == 19
assert get_count_digits(-1000000000000000000) == 19
assert get_count_digits(-999999999999999999) == 18
assert get_count_digits(-100000000000000000) == 18
assert get_count_digits(-99999999999999999) == 17
assert get_count_digits(-10000000000000000) == 17
assert get_count_digits(-9999999999999999) == 16
assert get_count_digits(-1000000000000000) == 16
assert get_count_digits(-999999999999999) == 15
assert get_count_digits(-100000000000000) == 15
assert get_count_digits(-99999999999999) == 14
assert get_count_digits(-10000000000000) == 14
assert get_count_digits(-9999999999999) == 13
assert get_count_digits(-1000000000000) == 13
assert get_count_digits(-999999999999) == 12
assert get_count_digits(-100000000000) == 12
assert get_count_digits(-99999999999) == 11
assert get_count_digits(-10000000000) == 11
assert get_count_digits(-9999999999) == 10
assert get_count_digits(-1000000000) == 10
assert get_count_digits(-999999999) == 9
assert get_count_digits(-100000000) == 9
assert get_count_digits(-99999999) == 8
assert get_count_digits(-10000000) == 8
assert get_count_digits(-9999999) == 7
assert get_count_digits(-1000000) == 7
assert get_count_digits(-999999) == 6
assert get_count_digits(-100000) == 6
assert get_count_digits(-99999) == 5
assert get_count_digits(-10000) == 5
assert get_count_digits(-9999) == 4
assert get_count_digits(-1000) == 4
assert get_count_digits(-999) == 3
assert get_count_digits(-100) == 3
assert get_count_digits(-99) == 2
assert get_count_digits(-10) == 2
assert get_count_digits(-9) == 1
assert get_count_digits(-1) == 1
assert get_count_digits(0) == 1
assert get_count_digits(1) == 1
assert get_count_digits(9) == 1
assert get_count_digits(10) == 2
assert get_count_digits(99) == 2
assert get_count_digits(100) == 3
assert get_count_digits(999) == 3
assert get_count_digits(1000) == 4
assert get_count_digits(9999) == 4
assert get_count_digits(10000) == 5
assert get_count_digits(99999) == 5
assert get_count_digits(100000) == 6
assert get_count_digits(999999) == 6
assert get_count_digits(1000000) == 7
assert get_count_digits(9999999) == 7
assert get_count_digits(10000000) == 8
assert get_count_digits(99999999) == 8
assert get_count_digits(100000000) == 9
assert get_count_digits(999999999) == 9
assert get_count_digits(1000000000) == 10
assert get_count_digits(9999999999) == 10
assert get_count_digits(10000000000) == 11
assert get_count_digits(99999999999) == 11
assert get_count_digits(100000000000) == 12
assert get_count_digits(999999999999) == 12
assert get_count_digits(1000000000000) == 13
assert get_count_digits(9999999999999) == 13
assert get_count_digits(10000000000000) == 14
assert get_count_digits(99999999999999) == 14
assert get_count_digits(100000000000000) == 15
assert get_count_digits(999999999999999) == 15
assert get_count_digits(1000000000000000) == 16
assert get_count_digits(9999999999999999) == 16
assert get_count_digits(10000000000000000) == 17
assert get_count_digits(99999999999999999) == 17
assert get_count_digits(100000000000000000) == 18
assert get_count_digits(999999999999999999) == 18
assert get_count_digits(1000000000000000000) == 19
assert get_count_digits(9999999999999999999) == 19
assert get_count_digits(10000000000000000000) == 20
assert get_count_digits(99999999999999999999) == 20

All example of codes tested with the Python 3.5

Remove old Fragment from fragment manager

You need to find reference of existing Fragment and remove that fragment using below code. You need add/commit fragment using one tag ex. "TAG_FRAGMENT".

Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if(fragment != null)
    getSupportFragmentManager().beginTransaction().remove(fragment).commit();

That is it.

How can I force component to re-render with hooks in React?

Generally, you can use any state handling approach you want to trigger an update.

With TypeScript

codesandbox example

useState

const forceUpdate: () => void = React.useState()[1].bind(null, {})  // see NOTE below

useReducer

const forceUpdate = React.useReducer(() => ({}), {})[1] as () => void

as custom hook

Just wrap whatever approach you prefer like this

function useForceUpdate(): () => void {
  return React.useReducer(() => ({}), {})[1] as () => void // <- paste here
}

How this works?

"To trigger an update" means to tell React engine that some value has changed and that it should rerender your component.

[, setState] from useState() requires a parameter. We get rid of it by binding a fresh object {}.
() => ({}) in useReducer is a dummy reducer that returns a fresh object each time an action is dispatched.
{} (fresh object) is required so that it triggers an update by changing a reference in the state.

PS: useState just wraps useReducer internally. source

NOTE: Using .bind with useState causes a change in function reference between renders. It is possible to wrap it inside useCallback as already explained here, but then it wouldn't be a sexy one-liner™. The Reducer version already keeps reference equality between renders. This is important if you want to pass the forceUpdate function in props.

plain JS

const forceUpdate = React.useState()[1].bind(null, {})  // see NOTE above
const forceUpdate = React.useReducer(() => ({}))[1]

How to set environment via `ng serve` in Angular 6

For Angular 2 - 5 refer the article Multiple Environment in angular

For Angular 6 use ng serve --configuration=dev

Note: Refer the same article for angular 6 as well. But wherever you find --env instead use --configuration. That's works well for angular 6.

Multi value Dictionary

You describe a multimap.

You can make the value a List object, to store more than one value (>2 for extensibility).

Override the dictionary object.

How to concatenate strings in twig

This should work fine:

{{ 'http://' ~ app.request.host }}

To add a filter - like 'trans' - in the same tag use

{{ ('http://' ~ app.request.host) | trans }}

As Adam Elsodaney points out, you can also use string interpolation, this does require double quoted strings:

{{ "http://#{app.request.host}" }}

.NET String.Format() to add commas in thousands place for a number

Note that the value that you're formatting should be numeric. It doesn't look like it will take a string representation of a number and format is with commas.

Simplest Way to Test ODBC on WIndows

It's been a while but since I precisely have the answer to the question, I'll share it and maybe someone will benefit from it.

Jaime de Los Hoyos wrote a very nice program to precisely do that: ODBC Query Tool.
Unfortunately, Jaime's website is defunct but you can still find the program and its source code at this location:
https://sourceforge.net/projects/odbc-query-tool/files/latest_release/

The program is GUI based and consists of a single executable file, no need to install anything on the machine.

Jaime's profile : https://stackoverflow.com/users/878998/jaime-de-los-hoyos-m
Jaime's posts on a forum talking about his program : https://forum.powerbasic.com/forum/user-to-user-discussions/source-code/48266-odbc-query-tool-retrieve-information-from-any-database-easily

Python argparse: default value or specified value

Actually, you only need to use the default argument to add_argument as in this test.py script:

import argparse

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('--example', default=1)
    args = parser.parse_args()
    print(args.example)

test.py --example
% 1
test.py --example 2
% 2

Details are here.

How to debug on a real device (using Eclipse/ADT)

With an Android-powered device, you can develop and debug your Android applications just as you would on the emulator.

1. Declare your application as "debuggable" in AndroidManifest.xml.

<application
    android:debuggable="true"
    ... >
    ...
</application>

2. On your handset, navigate to Settings > Security and check Unknown sources

enter image description here

3. Go to Settings > Developer Options and check USB debugging
Note that if Developer Options is invisible you will need to navigate to Settings > About Phone and tap on Build number several times until you are notified that it has been unlocked.

enter image description here

4. Set up your system to detect your device.
Follow the instructions below for your OS:


Windows Users

Install the Google USB Driver from the ADT SDK Manager
(Support for: ADP1, ADP2, Verizon Droid, Nexus One, Nexus S).

enter image description here

For devices not listed above, install an OEM driver for your device


Mac OS X

Your device should automatically work; Go to the next step


Ubuntu Linux

Add a udev rules file that contains a USB configuration for each type of device you want to use for development. In the rules file, each device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor} property. For a list of vendor IDs, click here. To set up device detection on Ubuntu Linux:

  1. Log in as root and create this file: /etc/udev/rules.d/51-android.rules.
  2. Use this format to add each vendor to the file:
    SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"
    In this example, the vendor ID is for HTC. The MODE assignment specifies read/write permissions, and GROUP defines which Unix group owns the device node.
  3. Now execute: chmod a+r /etc/udev/rules.d/51-android.rules

Note: The rule syntax may vary slightly depending on your environment. Consult the udev documentation for your system as needed. For an overview of rule syntax, see this guide to writing udev rules.


5. Run the project with your connected device.

With Eclipse/ADT: run or debug your application as usual. You will be presented with a Device Chooser dialog that lists the available emulator(s) and connected device(s).

With ADB: issue commands with the -d flag to target your connected device.

Still need help? Click here for the full guide.

Java command not found on Linux

I had these choices:

-----------------------------------------------
*  1           /usr/lib/jvm/jre-1.6.0-openjdk.x86_64/bin/java
 + 2           /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
   3           /home/ec2-user/local/java/jre1.7.0_25/bin/java

When I chose 3, it didn't work. When I chose 2, it did work.

Laravel Update Query

Try doing it like this.

User::where('email', $userEmail)
       ->update([
           'member_type' => $plan
        ]);

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

Common xlabel/ylabel for matplotlib subplots

Update:

This feature is now part of the proplot matplotlib package that I recently released on pypi. By default, when you make figures, the labels are "shared" between axes.


Original answer:

I discovered a more robust method:

If you know the bottom and top kwargs that went into a GridSpec initialization, or you otherwise know the edges positions of your axes in Figure coordinates, you can also specify the ylabel position in Figure coordinates with some fancy "transform" magic. For example:

import matplotlib.transforms as mtransforms
bottom, top = .1, .9
f, a = plt.subplots(nrows=2, ncols=1, bottom=bottom, top=top)
avepos = (bottom+top)/2
a[0].yaxis.label.set_transform(mtransforms.blended_transform_factory(
       mtransforms.IdentityTransform(), f.transFigure # specify x, y transform
       )) # changed from default blend (IdentityTransform(), a[0].transAxes)
a[0].yaxis.label.set_position((0, avepos))
a[0].set_ylabel('Hello, world!')

...and you should see that the label still appropriately adjusts left-right to keep from overlapping with ticklabels, just like normal -- but now it will adjust to be always exactly between the desired subplots.

Furthermore, if you don't even use set_position, the ylabel will show up by default exactly halfway up the figure. I'm guessing this is because when the label is finally drawn, matplotlib uses 0.5 for the y-coordinate without checking whether the underlying coordinate transform has changed.

What is the purpose of using -pedantic in GCC/G++ compiler?

If your code needs to be portable then you can test that it compiles without any gcc extensions or other non-standard features. If your code compiles with -pedantic -ansi then in theory it should compile OK with any other ANSI standard compiler.

Can´t run .bat file under windows 10

There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:

  • Add a pause to the batch file so that you can see what is happening before it exits.
    1. Right click on one of the .bat files and select "edit". This will open the file in notepad.
    2. Go to the very end of the file and add a new line by pressing "enter".
    3. type pause.
    4. Save the file.
    5. Run the file again using the same method you did before.

- OR -

  • Run the batch file from a static command prompt so the window does not close.
    1. In the folder where the .bat files are located, hold down the "shift" key and right click in the white space.
    2. Select "Open Command Window Here".
    3. You will now see a new command prompt. Type in the name of the batch file and press enter.

Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.

How to delete the top 1000 rows from a table using Sql Server 2008?

I agree with the Hamed elahi and Glorfindel.

My suggestion to add is you can delete and update using aliases

/* 
  given a table bi_customer_actions
  with a field bca_delete_flag of tinyint or bit
    and a field bca_add_date of datetime

  note: the *if 1=1* structure allows me to fold them and turn them on and off
 */
declare
        @Nrows int = 1000

if 1=1 /* testing the inner select */
begin
  select top (@Nrows) * 
    from bi_customer_actions
    where bca_delete_flag = 1
    order by bca_add_date
end

if 1=1 /* delete or update or select */
begin
  --select bca.*
  --update bca  set bca_delete_flag = 0
  delete bca
    from (
      select top (@Nrows) * 
        from bi_customer_actions
        where bca_delete_flag = 1
        order by bca_add_date
    ) as bca
end 

Encrypt and decrypt a string in C#?

using System;
using System.Data;
using System.Configuration;
using System.Text;
using System.Security.Cryptography;

namespace Encription
{
    class CryptorEngine
    {
        public static string Encrypt(string ToEncrypt, bool useHasing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(ToEncrypt);
            //System.Configuration.AppSettingsReader settingsReader = new     AppSettingsReader();
           string Key = "Bhagwati";
            if (useHasing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));
                hashmd5.Clear();  
            }
            else
            {
                keyArray = UTF8Encoding.UTF8.GetBytes(Key);
            }
            TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
            tDes.Key = keyArray;
            tDes.Mode = CipherMode.ECB;
            tDes.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = tDes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0,     toEncryptArray.Length);
            tDes.Clear();
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        public static string Decrypt(string cypherString, bool useHasing)
        {
            byte[] keyArray;
            byte[] toDecryptArray = Convert.FromBase64String(cypherString);
            //byte[] toEncryptArray = Convert.FromBase64String(cypherString);
            //System.Configuration.AppSettingsReader settingReader = new     AppSettingsReader();
            string key = "Bhagwati";
            if (useHasing)
            {
                MD5CryptoServiceProvider hashmd = new MD5CryptoServiceProvider();
                keyArray = hashmd.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd.Clear();
            }
            else
            {
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            }
            TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
            tDes.Key = keyArray;
            tDes.Mode = CipherMode.ECB;
            tDes.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = tDes.CreateDecryptor();
            try
            {
                byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0,         toDecryptArray.Length);

                tDes.Clear();
                return UTF8Encoding.UTF8.GetString(resultArray,0,resultArray.Length);
            }
            catch (Exception ex)
            {
                throw ex;
             }
        }
    }
}

case-insensitive matching in xpath?

matches() is an XPATH 2.0 function that allows for case-insensitive regex matching.

One of the flags is i for case-insensitive matching.

The following XPATH using the matches() function with the case-insensitive flag:

//CD[matches(@title,'empire burlesque','i')]

Computed / calculated / virtual / derived columns in PostgreSQL

PostgreSQL 12 supports generated columns:

PostgreSQL 12 Beta 1 Released!

Generated Columns

PostgreSQL 12 allows the creation of generated columns that compute their values with an expression using the contents of other columns. This feature provides stored generated columns, which are computed on inserts and updates and are saved on disk. Virtual generated columns, which are computed only when a column is read as part of a query, are not implemented yet.


Generated Columns

A generated column is a special column that is always computed from other columns. Thus, it is for columns what a view is for tables.

CREATE TABLE people (
    ...,
    height_cm numeric,
    height_in numeric GENERATED ALWAYS AS (height_cm * 2.54) STORED
);

db<>fiddle demo

How to extract public key using OpenSSL?

For those interested in the details - you can see what's inside the public key file (generated as explained above), by doing this:-

openssl rsa -noout -text -inform PEM -in key.pub -pubin

or for the private key file, this:-

openssl rsa -noout -text -in key.private

which outputs as text on the console the actual components of the key (modulus, exponents, primes, ...)

TypeError: p.easing[this.easing] is not a function

If you're using Bootstrap it's also possible that Bootstrap's jQuery, if included below your jQuery script tag, is overwriting your jQuery script tag with another version. Including jQuery's own CDN and deleting the jQuery script tag that Bootstrap provides was the only thing that worked for me.

Is there a W3C valid way to disable autocomplete in a HTML form?

How about setting it with JavaScript?

var e = document.getElementById('cardNumber');
e.autocomplete = 'off'; // Maybe should be false

It's not perfect, but your HTML will be valid.

Is there an "exists" function for jQuery?

Use the following syntax to check if the element actually exists using jQuery.

let oElement = $(".myElementClass");
if(oElement[0]) {
    // Do some jQuery operation here using oElement
}
else {
    // Unable to fetch the object
}

$(document).ready shorthand

This is not a shorthand for $(document).ready().

The code you posted boxes the inside code and makes jQuery available as $ without polluting the global namespace. This can be used when you want to use both prototype and jQuery on one page.

Documented here: http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/#use-an-immediately-invoked-function-expression

Calculate relative time in C#

// Calculate total days in current year
int daysInYear;

for (var i = 1; i <= 12; i++)
    daysInYear += DateTime.DaysInMonth(DateTime.Now.Year, i);

// Past date
DateTime dateToCompare = DateTime.Now.Subtract(TimeSpan.FromMinutes(582));

// Calculate difference between current date and past date
double diff = (DateTime.Now - dateToCompare).TotalMilliseconds;

TimeSpan ts = TimeSpan.FromMilliseconds(diff);

var years = ts.TotalDays / daysInYear; // Years
var months = ts.TotalDays / (daysInYear / (double)12); // Months
var weeks = ts.TotalDays / 7; // Weeks
var days = ts.TotalDays; // Days
var hours = ts.TotalHours; // Hours
var minutes = ts.TotalMinutes; // Minutes
var seconds = ts.TotalSeconds; // Seconds

if (years >= 1)
    Console.WriteLine(Math.Round(years, 0) + " year(s) ago");
else if (months >= 1)
    Console.WriteLine(Math.Round(months, 0) + " month(s) ago");
else if (weeks >= 1)
    Console.WriteLine(Math.Round(weeks, 0) + " week(s) ago");
else if (days >= 1)
    Console.WriteLine(Math.Round(days, 0) + " days(s) ago");
else if (hours >= 1)
    Console.WriteLine(Math.Round(hours, 0) + " hour(s) ago");
else if (minutes >= 1)
    Console.WriteLine(Math.Round(minutes, 0) + " minute(s) ago");
else if (seconds >= 1)
    Console.WriteLine(Math.Round(seconds, 0) + " second(s) ago");

Console.ReadLine();

How can I remove all my changes in my SVN working directory?

I used a combination of other peoples' answers to come up with this solution:

Revert normal local SVN changes

svn revert -R .

Remove any other change and supports removing files/folders with spaces, etc.

svn status --no-ignore | grep -E '(^\?)|(^\I)' | sed -e 's/^. *//' | sed -e 's/\(.*\)/"\1"/' | xargs rm -rf

Don't forget to get the latest files from SVN

svn update --force

What is the --save option for npm install?

The easier (and more awesome) way to add dependencies to your package.json is to do so from the command line, flagging the npm install command with either --save or --save-dev, depending on how you'd like to use that dependency.

Output to the same line overwriting previous output?

I am using spyder 3.3.1 - windows 7 - python 3.6 although flush may not be needed. based on this posting - https://github.com/spyder-ide/spyder/issues/3437

   #works in spyder ipython console - \r at start of string , end=""
import time
import sys
    for i in range(20):
        time.sleep(0.5)
        print(f"\rnumber{i}",end="")
        sys.stdout.flush()

Correct use for angular-translate in controllers

EDIT: Please see the answer from PascalPrecht (the author of angular-translate) for a better solution.


The asynchronous nature of the loading causes the problem. You see, with {{ pageTitle | translate }}, Angular will watch the expression; when the localization data is loaded, the value of the expression changes and the screen is updated.

So, you can do that yourself:

.controller('FirstPageCtrl', ['$scope', '$filter', function ($scope, $filter) {
    $scope.$watch(
        function() { return $filter('translate')('HELLO_WORLD'); },
        function(newval) { $scope.pageTitle = newval; }
    );
});

However, this will run the watched expression on every digest cycle. This is suboptimal and may or may not cause a visible performance degradation. Anyway it is what Angular does, so it cant be that bad...

in angularjs how to access the element that triggered the event?

There is a solution using $element in the controller if you don't want to create another directive for this problem:

appControllers.controller('YourCtrl', ['$scope', '$timeout', '$element',
        function($scope, $timeout, $element) {

    $scope.updateTypeahead = function() {
       // ... some logic here
       $timeout(function() {
           $element[0].getElementsByClassName('search-query')[0].focus();
           // if you have unique id you can use $window instead of $element:
           // $window.document.getElementById('searchText').focus();
       });
    }
}]);

And this will work with ng-change:

<input id="searchText" type="text" class="search-query" ng-change="updateTypeahead()" ng-model="searchText" />

Cannot open include file 'afxres.h' in VC2010 Express

a similar issue is for Visual studio 2015 RC. Sometimes it loses the ability to open RC: you double click but editor do not one menus and dialogs.

Right click on the file *.rc, it will open:

enter image description here

And change as following:

enter image description here

Get class name of object as string in Swift

UPDATED TO SWIFT 5

We can get pretty descriptions of type names using the instance variable through the String initializer and create new objects of a certain class

Like, for example print(String(describing: type(of: object))). Where object can be an instance variable like array, a dictionary, an Int, a NSDate, etc.

Because NSObject is the root class of most Objective-C class hierarchies, you could try to make an extension for NSObject to get the class name of every subclass of NSObject. Like this:

extension NSObject {
    var theClassName: String {
        return NSStringFromClass(type(of: self))
    }
}

Or you could make a static funcion whose parameter is of type Any (The protocol to which all types implicitly conform) and returns the class name as String. Like this:

class Utility{
    class func classNameAsString(_ obj: Any) -> String {
        //prints more readable results for dictionaries, arrays, Int, etc
        return String(describing: type(of: obj))
    }
} 

Now you can do something like this:

class ClassOne : UIViewController{ /* some code here */ }
class ClassTwo : ClassOne{ /* some code here */ }

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Get the class name as String
        let dictionary: [String: CGFloat] = [:]
        let array: [Int] = []
        let int = 9
        let numFloat: CGFloat = 3.0
        let numDouble: Double = 1.0
        let classOne = ClassOne()
        let classTwo: ClassTwo? = ClassTwo()
        let now = NSDate()
        let lbl = UILabel()

        print("dictionary: [String: CGFloat] = [:] -> \(Utility.classNameAsString(dictionary))")
        print("array: [Int] = [] -> \(Utility.classNameAsString(array))")
        print("int = 9 -> \(Utility.classNameAsString(int))")
        print("numFloat: CGFloat = 3.0 -> \(Utility.classNameAsString(numFloat))")
        print("numDouble: Double = 1.0 -> \(Utility.classNameAsString(numDouble))")
        print("classOne = ClassOne() -> \((ClassOne).self)") //we use the Extension
        if classTwo != nil {
            print("classTwo: ClassTwo? = ClassTwo() -> \(Utility.classNameAsString(classTwo!))") //now we can use a Forced-Value Expression and unwrap the value
        }
        print("now = Date() -> \(Utility.classNameAsString(now))")
        print("lbl = UILabel() -> \(String(describing: type(of: lbl)))") // we use the String initializer directly

    }
}

Also, once we can get the class name as String, we can instantiate new objects of that class:

// Instantiate a class from a String
print("\nInstantiate a class from a String")
let aClassName = classOne.theClassName
let aClassType = NSClassFromString(aClassName) as! NSObject.Type
let instance = aClassType.init() // we create a new object
print(String(cString: class_getName(type(of: instance))))
print(instance.self is ClassOne)

Maybe this helps someone out there!.

Error: Unable to run mksdcard SDK tool

Here's what you need to do to fix the issue on Arch Linux :

  1. Enable the multilib repository on your system if you have not already done so by uncommenting the [multilib] section in /etc/pacman.conf :

    [multilib]
    Include = /etc/pacman.d/mirrorlist
    
  2. Update pacman :

    # pacman -Suy
    
  3. Install the 32 bit version of libstdc++5 :

    # pacman -S lib32-libstdc++5
    

Remove all classes that begin with a certain string

I know it's an old question, but I found out new solution and want to know if it has disadvantages?

$('#a')[0].className = $('#a')[0].className
                              .replace(/(^|\s)bg.*?(\s|$)/g, ' ')
                              .replace(/\s\s+/g, ' ')
                              .replace(/(^\s|\s$)/g, '');

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

Swift 3.X+ , Xcode 8.X + Tested working easy solution;

Use simple ;

let myString = "12.12.2017 12:34:45"
let newString = myString?[(myString?.startIndex)!..<(myString?.index((myString?.startIndex)!, offsetBy: 10))!]
print(newString) 

Output = 12.12.2017

For customization easily change;

offsetBy: 10 // Change 10 to endIndex.

When you change offsetBy: 10 to 15,20 etc. Will cut your string..

Thank you !

How do CSS triangles work?

Start with a basic square and borders. Each border will be given a different color so we can tell them apart:

_x000D_
_x000D_
.triangle {
    border-color: yellow blue red green;
    border-style: solid;
    border-width: 200px 200px 200px 200px;
    height: 0px;
    width: 0px;
}
_x000D_
<div class="triangle"></div>
_x000D_
_x000D_
_x000D_

which gives you this:

square with four borders

But there's no need for the top border, so set its width to 0px. Now our border-bottom of 200px will make our triangle 200px tall.

_x000D_
_x000D_
.triangle {
    border-color: yellow blue red green;
    border-style: solid;
    border-width: 0px 200px 200px 200px;
    height: 0px;
    width: 0px;
}
_x000D_
<div class="triangle"></div>
_x000D_
_x000D_
_x000D_

and we will get this:

bottom half of square with four borders

Then to hide the two side triangles, set the border-color to transparent. Since the top-border has been effectively deleted, we can set the border-top-color to transparent as well.

_x000D_
_x000D_
.triangle {
    border-color: transparent transparent red transparent;
    border-style: solid;
    border-width: 0px 200px 200px 200px;
    height: 0px;
    width: 0px;
}
_x000D_
<div class="triangle"></div>
_x000D_
_x000D_
_x000D_

finally we get this:

triangular bottom border

Path.Combine absolute with relative path strings

This will give you exactly what you need (path does NOT have to exist for this to work)

DirectoryInfo di = new DirectoryInfo(@"C:\blah\..\bling");
string cleanPath = di.FullName;

Uncaught TypeError: (intermediate value)(...) is not a function

When I create a root class, whose methods I defined using the arrow functions. When inheriting and overwriting the original function I noticed the same issue.

class C {
  x = () => 1; 
 };
 
class CC extends C {
  x = (foo) =>  super.x() + foo;
};

let add = new CC;
console.log(add.x(4));

this is solved by defining the method of the parent class without arrow functions

class C {
  x() { 
    return 1; 
  }; 
 };
 
class CC extends C {
  x = foo =>  super.x() + foo;
};

let add = new CC;
console.log(add.x(4));

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

Try to run Maven from the command line or type "-X" in the text field - you can't break anything this way, at the worst, you'll get an error (I don't have Netbeans; in Eclipse, there is a checkbox "Debug" for this).

When running with debug output enabled, you should see the paths which the exec-maven-plugin plugin uses.

The next step would then be to copy the command into a command prompt or terminal and execute it manually to see if you get a useful error message there.

How to write a confusion matrix in Python?

You should map from classes to a row in your confusion matrix.

Here the mapping is trivial:

def row_of_class(classe):
    return {1: 0, 2: 1}[classe]

In your loop, compute expected_row, correct_row, and increment conf_arr[expected_row][correct_row]. You'll even have less code than what you started with.

Why is <deny users="?" /> included in the following example?

Example 1 is for asp.net applications using forms authenication. This is common practice for internet applications because user is unauthenticated until it is authentcation against some security module.

Example 2 is for asp.net application using windows authenication. Windows Authentication uses Active Directory to authenticate users. The will prevent access to your application. I use this feature on intranet applications.

Getting value from a cell from a gridview on RowDataBound event

The above are good suggestions, but you can get at the text value of a cell in a grid view without wrapping it in a literal or label control. You just have to know what event to wire up. In this case, use the DataBound event instead, like so:

protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[0].Text.Contains("sometext"))
        {
            e.Row.Cells[0].Font.Bold = true;
        }
    }
}

When running a debugger, you will see the text appear in this method.

How can I make my string property nullable?

Strings are nullable in C# anyway because they are reference types. You can just use public string CMName { get; set; } and you'll be able to set it to null.

How do I find the mime-type of a file with php?

if you're only dealing with images you can use the [getimagesize()][1] function which contains all sorts of info about the image, including the type.

A more general approach would be to use the FileInfo extension from PECL. The PHP documentation for this extension can be found at: http://us.php.net/manual/en/ref.fileinfo.php

Some people have serious complaints about that extension... so if you run into serious issues or cannot install the extension for some reason you might want to check out the deprecated function mime_content_type()

Merge, update, and pull Git branches without using checkouts

I wrote a shell function for a similar use case I encounter daily on projects. This is basically a shortcut for keeping local branches up to date with a common branch like develop before opening a PR, etc.

Posting this even though you don't want to use checkout, in case others don't mind that constraint.

glmh ("git pull and merge here") will automatically checkout branchB, pull the latest, re-checkout branchA, and merge branchB.

Doesn't address the need to keep a local copy of branchA, but could easily be modified to do so by adding a step before checking out branchB. Something like...

git branch ${branchA}-no-branchB ${branchA}

For simple fast-forward merges, this skips to the commit message prompt.

For non fast-forward merges, this places your branch in the conflict resolution state (you likely need to intervene).

To setup, add to .bashrc or .zshrc, etc:

glmh() {
    branchB=$1
    [ $# -eq 0 ] && { branchB="develop" }
    branchA="$(git branch | grep '*' | sed 's/* //g')"
    git checkout ${branchB} && git pull
    git checkout ${branchA} && git merge ${branchB} 
}

Usage:

# No argument given, will assume "develop"
> glmh

# Pass an argument to pull and merge a specific branch
> glmh your-other-branch

Note: This is not robust enough to hand-off of args beyond branch name to git merge

What is the purpose of Android's <merge> tag in XML layouts?

blazeroni already made it pretty clear, I just want to add few points.

  • <merge> is used for optimizing layouts.It is used for reducing unnecessary nesting.
  • when a layout containing <merge> tag is added into another layout,the <merge> node is removed and its child view is added directly to the new parent.

How to connect to LocalDB in Visual Studio Server Explorer?

Scenario: Windows 8.1, VS2013 Ultimate, SQL Express Installed and running, SQL Server Browser Disabled. This worked for me:

  1. First I enabled SQL Server Browser under services.
  2. In Visual Studio: Open the Package Manager Console then type: Enable-Migrations; Then Type Enable-Migrations -ContextTypeName YourContextDbName that created the Migrations folder in VS.
  3. Inside the Migrations folder you will find the "Configuration.cs" file, turn on automatic migrations by: AutomaticMigrationsEnabled = true;
  4. Run your application again, the environment creates a DefaultConnection and you will see the new tables from your context. This new connection points to the localdb. The created connection string shows: Data Source=(LocalDb)\v11.0 ... (more parameters and path to the created mdf file)

You can now create a new connection with Server name: (LocalDb)\v11.0 (hit refresh) Connect to a database: Select your new database under the dropdown.

I hope it helps.

Laravel Request getting current path with query string

Similar to Yada's answer: $request->url() will also work if you are injecting Illuminate\Http\Request

Edit: The difference between fullUrl and url is the fullUrl includes your query parameters

How to represent a DateTime in Excel

Excel expects dates and times to be stored as a floating point number whose value depends on the Date1904 setting of the workbook, plus a number format such as "mm/dd/yyyy" or "hh:mm:ss" or "mm/dd/yyyy hh:mm:ss" so that the number is displayed to the user as a date / time.

Using SpreadsheetGear for .NET you can do this: worksheet.Cells["A1"].Value = DateTime.Now;

This will convert the DateTime to a double which is the underlying type which Excel uses for a Date / Time, and then format the cell with a default date and / or time number format automatically depending on the value.

SpreadsheetGear also has IWorkbook.DateTimeToNumber(DateTime) and NumberToDateTime(double) methods which convert from .NET DateTime objects to a double which Excel can use.

I would expect XlsIO to have something similar.

Disclaimer: I own SpreadsheetGear LLC

virtualenvwrapper and Python 3

virtualenvwrapper now lets you specify the python executable without the path.

So (on OSX at least)mkvirtualenv --python=python3 nameOfEnvironment will suffice.

How to check task status in Celery?

Answer of 2020:

#### tasks.py
@celery.task()
def mytask(arg1):
    print(arg1)

#### blueprint.py
@bp.route("/args/arg1=<arg1>")
def sleeper(arg1):
    process = mytask.apply_async(args=(arg1,)) #mytask.delay(arg1)
    state = process.state
    return f"Thanks for your patience, your job {process.task_id} \
             is being processed. Status {state}"

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

How do you disable browser Autocomplete on web form field / input tag?

To prevent browser auto fill with the user's saved site login credentials, place a text and password input field at the top of the form with non empty values and style "position: absolute; top: -999px; left:-999px" set to hide the fields.

<form>
  <input type="text" name="username_X" value="-" tabindex="-1" aria-hidden="true" style="position: absolute; top: -999px; left:-999px" />
  <input type="password" name="password_X" value="-" tabindex="-1" aria-hidden="true" style="position: absolute; top: -999px; left:-999px" />
  <!-- Place the form elements below here. -->
</form>

It is important that a text field precede the password field. Otherwise the auto fill may not be prevented in some cases.

It is important that the value of both the text and password fields not be empty, to prevent default values from being overwritten in some cases.

It is important that these two fields are before the "real" password type field(s) in the form.

For newer browsers that are html 5.3 compliant the autocomplete attribute value "new-password" should work.

<form>
  <input type="text" name="username" value="" />
  <input type="password" name="password" value="" autocomplete="new-password" />
</form>

A combination of the two methods can be used to support both older and newer browsers.

<form>
  <div style="display:none">
    <input type="text" readonly tabindex="-1" />
    <input type="password" readonly tabindex="-1" />
  </div>
  <!-- Place the form elements below here. -->
  <input type="text" name="username" value="" />
  <input type="password" name="password" value="" autocomplete="new-password" />
</form>

Converting unix timestamp string to readable date

>>> import time
>>> time.ctime(int("1284101485"))
'Fri Sep 10 16:51:25 2010'
>>> time.strftime("%D %H:%M", time.localtime(int("1284101485")))
'09/10/10 16:51'

Problems with entering Git commit message with Vim

If it is VIM for Windows, you can do the following:

  • enter your message following the presented guidelines
  • press Esc to make sure you are out of the insert mode
  • then type :wqEnter or ZZ.

Note that in VIM there are often several ways to do one thing. Here there is a slight difference though. :wqEnter always writes the current file before closing it, while ZZ, :xEnter, :xiEnter, :xitEnter, :exiEnter and :exitEnter only write it if the document is modified.
All these synonyms just have different numbers of keypresses.

Set up Python 3 build system with Sublime Text 3

Steps to Make Sublime Text a Python IDE (Windows)

Tested successfully on Sublime Text 3. Assuming Sublime Text and package control are already installed . . .

  1. Install Python (python.org) and pay attention to where it is installed or choose a simple location like the C drive, agreeing to remove character limit at the end of the installation.

  2. Install package SublimeREPL (Cntrl + Shift + P, Package Control - Install Package, SublimeREPL, Enter).

  3. Go to Preferences, Package Settings, SublimeREPL, Settings - User.

  4. Paste in the following, updating the file path to your python installation folder, as needed. You may customize these and choose whatever syntax you like (last line) but I prefer my output in plain text.

    {
      "default_extend_env": {"PATH":"C:\\Program Files\\Python36\\"},
      "repl_view_settings": {
      "translate_tabs_to_spaces": false,
      "auto_indent": false,
      "smart_indent": false,
      "spell_check": false,
      "indent_subsequent_lines": false,
      "detect_indentation": false,
      "auto_complete": true,
      "line_numbers": false,
      "gutter": false,
      "syntax": "Packages/Text/Plain text.tmLanguage"
      }
    }
    
  5. Save and close the file (SublimeREPL.sublime-settings).

  6. Go to Tools, Build System, New Build System.

  7. Replace all existing text with the following:

    {
    "target": "run_existing_window_command", 
    "id": "repl_python_run",
    "file": "config/Python/Main.sublime-menu"
    }
    
  8. Cntrl + S or save as "C:\Users[username]\AppData\Roaming\Sublime Text 3\Packages\User\SublimeREPL-python.sublime-build" updating username or path as needed. This should be wherever your settings and builds are stored by Sublime Text.

  9. Go to Tools, Build System, select SublimeREPL-python.

  10. All done--now to test. Open or create a simple python file, having a *.py extension and save it wherever desired.

  11. Make sure the file is open and selected in Sublime Text. Now, when you press Cntrl + B to build and run it, it will open another tab, titled "REPL [python]", executing and displaying the results of your python code.

If you would like to go a step further, I highly recommend making the follow changes, to allow Sublime to reload your executed python in the same window, when you press Cntrl+B (Build), instead of it opening a new tab each time:

Add the following line in the "repl_python_run" command in (Preferences, Browse Packages) SublimeREPL\config\Python\Main.sublime-menu, right before the "external_id": "python" argument:

"view_id": "*REPL* [python]",

and then to change the line:

if view.id() == view_id

into:

if view.name() == view_id

in SublimeREPL\sublimerepl.py.

Adding Only Untracked Files

To add all untracked files git command is

git add -A

Also if you want to get more details about various available options , you can type command

git add -i

instead of first command , with this you will get more options including option to add all untracked files as shown below :

$ git add -i warning: LF will be replaced by CRLF in README.txt. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in package.json.

* Commands * 1: status 2: update 3: revert 4: add untracked 5: patch 6: diff 7: quit 8: help What now> a

How to call Oracle MD5 hash function?

I would do:

select DBMS_CRYPTO.HASH(rawtohex('foo') ,2) from dual;

output:

DBMS_CRYPTO.HASH(RAWTOHEX('FOO'),2)
--------------------------------------------------------------------------------
ACBD18DB4CC2F85CEDEF654FCCC4A4D8

"Post Image data using POSTMAN"

Follow the below steps:

  1. No need to give any type of header.
  2. Select body > form-data and do same as shown in the image. 1

  3. Now in your Django view.py

def post(self, request, *args, **kwargs):
    image = request.FILES["image"]
    data = json.loads(request.data['data'])
    ...
    return Response(...)
  1. You can access all the keys (id, uid etc..) from the data variable.

Check if a string contains a string in C++

In the event if the functionality is critical to your system, it is actually beneficial to use an old strstr method. The std::search method within algorithm is the slowest possible. My guess would be that it takes a lot of time to create those iterators.

The code that i used to time the whole thing is

#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <random>
#include <chrono>

std::string randomString( size_t len );

int main(int argc, char* argv[])
{
        using namespace std::chrono;

        const size_t haystacksCount = 200000;
        std::string haystacks[haystacksCount];
        std::string needle = "hello";

        bool sink = true;

        high_resolution_clock::time_point start, end;
        duration<double> timespan;

        int sizes[10] = { 10, 20, 40, 80, 160, 320, 640, 1280, 5120, 10240 };

        for(int s=0; s<10; ++s)
        {
                std::cout << std::endl << "Generating " << haystacksCount << " random haystacks of size " << sizes[s] << std::endl;
                for(size_t i=0; i<haystacksCount; ++i)
                {
                        haystacks[i] = randomString(sizes[s]);
                }

                std::cout << "Starting std::string.find approach" << std::endl;
                start = high_resolution_clock::now();
                for(size_t i=0; i<haystacksCount; ++i)
                {
                        if(haystacks[i].find(needle) != std::string::npos)
                        {
                                sink = !sink; // useless action
                        }
                }
                end = high_resolution_clock::now();
                timespan = duration_cast<duration<double>>(end-start);
                std::cout << "Processing of " << haystacksCount << " elements took " << timespan.count() << " seconds." << std::endl;

                std::cout << "Starting strstr approach" << std::endl;
                start = high_resolution_clock::now();
                for(size_t i=0; i<haystacksCount; ++i)
                {
                        if(strstr(haystacks[i].c_str(), needle.c_str()))
                        {
                                sink = !sink; // useless action
                        }
                }
                end = high_resolution_clock::now();
                timespan = duration_cast<duration<double>>(end-start);
                std::cout << "Processing of " << haystacksCount << " elements took " << timespan.count() << " seconds." << std::endl;

                std::cout << "Starting std::search approach" << std::endl;
                start = high_resolution_clock::now();
                for(size_t i=0; i<haystacksCount; ++i)
                {
                        if(std::search(haystacks[i].begin(), haystacks[i].end(), needle.begin(), needle.end()) != haystacks[i].end())
                        {
                                sink = !sink; // useless action
                        }
                }
                end = high_resolution_clock::now();
                timespan = duration_cast<duration<double>>(end-start);
                std::cout << "Processing of " << haystacksCount << " elements took " << timespan.count() << " seconds." << std::endl;
        }

        return 0;
}

std::string randomString( size_t len)
{
        static const char charset[] = "abcdefghijklmnopqrstuvwxyz";
        static const int charsetLen = sizeof(charset) - 1;
        static std::default_random_engine rng(std::random_device{}());
        static std::uniform_int_distribution<> dist(0, charsetLen);
        auto randChar = [charset, &dist, &rng]() -> char
        {
                return charset[ dist(rng) ];
        };

        std::string result(len, 0);
        std::generate_n(result.begin(), len, randChar);
        return result;
}

Here i generate random haystacks and search in them the needle. The haystack count is set, but the length of strings within each haystack is increased from 10 in the beginning to 10240 in the end. Most of the time the program spends actually generating random strings, but that is to be expected.

The output is:

Generating 200000 random haystacks of size 10
Starting std::string.find approach
Processing of 200000 elements took 0.00358503 seconds.
Starting strstr approach
Processing of 200000 elements took 0.0022727 seconds.
Starting std::search approach
Processing of 200000 elements took 0.0346258 seconds.

Generating 200000 random haystacks of size 20
Starting std::string.find approach
Processing of 200000 elements took 0.00480959 seconds.
Starting strstr approach
Processing of 200000 elements took 0.00236199 seconds.
Starting std::search approach
Processing of 200000 elements took 0.0586416 seconds.

Generating 200000 random haystacks of size 40
Starting std::string.find approach
Processing of 200000 elements took 0.0082571 seconds.
Starting strstr approach
Processing of 200000 elements took 0.00341435 seconds.
Starting std::search approach
Processing of 200000 elements took 0.0952996 seconds.

Generating 200000 random haystacks of size 80
Starting std::string.find approach
Processing of 200000 elements took 0.0148288 seconds.
Starting strstr approach
Processing of 200000 elements took 0.00399263 seconds.
Starting std::search approach
Processing of 200000 elements took 0.175945 seconds.

Generating 200000 random haystacks of size 160
Starting std::string.find approach
Processing of 200000 elements took 0.0293496 seconds.
Starting strstr approach
Processing of 200000 elements took 0.00504251 seconds.
Starting std::search approach
Processing of 200000 elements took 0.343452 seconds.

Generating 200000 random haystacks of size 320
Starting std::string.find approach
Processing of 200000 elements took 0.0522893 seconds.
Starting strstr approach
Processing of 200000 elements took 0.00850485 seconds.
Starting std::search approach
Processing of 200000 elements took 0.64133 seconds.

Generating 200000 random haystacks of size 640
Starting std::string.find approach
Processing of 200000 elements took 0.102082 seconds.
Starting strstr approach
Processing of 200000 elements took 0.00925799 seconds.
Starting std::search approach
Processing of 200000 elements took 1.26321 seconds.

Generating 200000 random haystacks of size 1280
Starting std::string.find approach
Processing of 200000 elements took 0.208057 seconds.
Starting strstr approach
Processing of 200000 elements took 0.0105039 seconds.
Starting std::search approach
Processing of 200000 elements took 2.57404 seconds.

Generating 200000 random haystacks of size 5120
Starting std::string.find approach
Processing of 200000 elements took 0.798496 seconds.
Starting strstr approach
Processing of 200000 elements took 0.0137969 seconds.
Starting std::search approach
Processing of 200000 elements took 10.3573 seconds.

Generating 200000 random haystacks of size 10240
Starting std::string.find approach
Processing of 200000 elements took 1.58171 seconds.
Starting strstr approach
Processing of 200000 elements took 0.0143111 seconds.
Starting std::search approach
Processing of 200000 elements took 20.4163 seconds.

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

For whatever reason, TWO of my solutions have web projects that spontaneously uninstalled asp.net MVC somehow. I installed it from Nuget and now they both work again. This happened after a recent batch of windows updates that included .net framework updates for the version I was using (4.5.1).

Edit: From the .Net Web Development and Tools Blog:

Microsoft Asp.Net MVC Security Update MS14-059 broke my build!

Laravel 5.1 API Enable Cors

just use this as a middleware

<?php

namespace App\Http\Middleware;

use Closure;

class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->header('Access-Control-Allow-Origin', '*');
        $response->header('Access-Control-Allow-Methods', '*');

        return $response;
    }
}

and register the middleware in your kernel file on this path app/Http/Kernel.php in which group that you prefer and everything will be fine

How to cherry-pick multiple commits

To cherry pick from a commit id up to the tip of the branch, you can use:

git cherry-pick commit_id^..branch_name

Python read next()

next() does not work in your case because you first call readlines() which basically sets the file iterator to point to the end of file.

Since you are reading in all the lines anyway you can refer to the next line using an index:

filne = "in"
with open(filne, 'r+') as f:
    lines = f.readlines()
    for i in range(0, len(lines)):
        line = lines[i]
        print line
        if line[:5] == "anim ":
            ne = lines[i + 1] # you may want to check that i < len(lines)
            print ' ne ',ne,'\n'
            break

In Java, can you modify a List while iterating through it?

Java 8's stream() interface provides a great way to update a list in place.

To safely update items in the list, use map():

List<String> letters = new ArrayList<>();

// add stuff to list

letters = letters.stream().map(x -> "D").collect(Collectors.toList());

To safely remove items in place, use filter():


letters.stream().filter(x -> !x.equals("A")).collect(Collectors.toList());

Do copyright dates need to be updated?

It is important to recognize that the copyright laws have changed and that for non-US sources, especially after the USA joining the Berne Convention on March 1, 1989, copyright registration in not necessary for enforcement of a copyright notice.
Here is a resumé quoted from the Cornell University Law School (copied on March 4, 2015 from https://www.law.cornell.edu/wex/copyright:

"Copyright copyright: an overview

The U.S. Copyright Act, 17 U.S.C. §§ 101 - 810, is Federal legislation enacted by Congress under its Constitutional grant of authority to protect the writings of authors. See U.S. Constitution, Article I, Section 8. Changing technology has led to an ever expanding understanding of the word "writings." The Copyright Act now reaches architectural design, software, the graphic arts, motion pictures, and sound recordings. See § 106. As of January 1, 1978, all works of authorship fixed in a tangible medium of expression and within the subject matter of copyright were deemed to fall within the exclusive jurisdiction of the Copyright Act regardless of whether the work was created before or after that date and whether published or unpublished. See § 301. See also preemption.

The owner of a copyright has the exclusive right to reproduce, distribute, perform, display, license, and to prepare derivative works based on the copyrighted work. See § 106. The exclusive rights of the copyright owner are subject to limitation by the doctrine of "fair use." See § 107. Fair use of a copyrighted work for purposes such as criticism, comment, news reporting, teaching, scholarship, or research is not copyright infringement. To determine whether or not a particular use qualifies as fair use, courts apply a multi-factor balancing test. See § 107.

Copyright protection subsists in original works of authorship fixed in any tangible medium of expression from which they can be perceived, reproduced, or otherwise communicated, either directly or with the aid of a machine or device. See § 102. Copyright protection does not extend to any idea, procedure, process, system, method of operation, concept, principle, or discovery. For example, if a book is written describing a new system of bookkeeping, copyright protection only extends to the author's description of the bookkeeping system; it does not protect the system itself. See Baker v. Selden, 101 U.S. 99 (1879).

According to the Copyright Act of 1976, registration of copyright is voluntary and may take place at any time during the term of protection. See § 408. Although registration of a work with the Copyright Office is not a precondition for protection, an action for copyright infringement may not be commenced until the copyright has been formally registered with the Copyright Office. See § 411.

Deposit of copies with the Copyright Office for use by the Library of Congress is a separate requirement from registration. Failure to comply with the deposit requirement within three months of publication of the protected work may result in a civil fine. See § 407. The Register of Copyrights may exempt certain categories of material from the deposit requirement.

In 1989 the U.S. joined the Berne Convention for the Protection of Literary and Artistic Works. In accordance with the requirements of the Berne Convention, notice is no longer a condition of protection for works published after March 1, 1989. This change to the notice requirement applies only prospectively to copies of works publicly distributed after March 1, 1989.

The Berne Convention also modified the rule making copyright registration a precondition to commencing a lawsuit for infringement. For works originating from a Berne Convention country, an infringement action may be initiated without registering the work with the U.S. Copyright Office. However, for works of U.S. origin, registration prior to filing suit is still required.

The federal agency charged with administering the act is the Copyright Office of the Library of Congress. See § 701 of the act. Its regulations are found in Parts 201 - 204 of title 37 of the Code of Federal Regulations."

What is the equivalent of ngShow and ngHide in Angular 2+?

My issue was displaying/hiding a mat-table on a button click using <ng-container *ngIf="myVar">. The 'loading' of the table was very slow with 300 records at 2-3 seconds.

The data is loaded using a subscribe in ngOnInit(), and is available and ready to be used in the template, however the 'loading' of the table in the template became increasingly slower with the increase in number of rows.

My solution was to replace the *ngIf with:

_x000D_
_x000D_
<div [style.display]="activeSelected ? 'block' : 'none'">
_x000D_
_x000D_
_x000D_

. Now the table loads instantly when the button is clicked.

Is it possible to open developer tools console in Chrome on Android phone?

I you only want to see what was printed in the console you could simple add the "printed" part somewhere in your HTML so it will appear in on the webpage. You could do it for yourself, but there is a javascript file that does this for you. You can read about it here:

http://www.hnldesign.nl/work/code/mobileconsole-javascript-console-for-mobile-devices/

The code is available from Github; you can download it and paste it into a javascipt file and add it in to your HTML

PHP Fatal error: Cannot redeclare class

Another possible culprit is source control and unresolved conflicts. SVN may cause the same class to appear twice in the conflicted code file; two alternative versions of it ("mine" and "theirs").

Node.js - SyntaxError: Unexpected token import

I often use a github starter project, like this (it uses babel)

How to detect a mobile device with JavaScript?

Since it's now 2015, if you stumbled across this question then you should probably be using window.matchMedia (and, if it's still 2015, polyfilling for older browsers):

if (matchMedia('handheld').matches) {
    //...
} else {
    //...
}

How can I send an xml body using requests library?

Pass in the straight XML instead of a dictionary.

How can I save a base64-encoded image to disk?

Below function to save files, just pass your base64 file, it return filename save it in DB.

import fs from 'fs';
 const uuid = require('uuid/v1');

/*Download the base64 image in the server and returns the filename and path of image.*/
function saveImage(baseImage) {
    /*path of the folder where your project is saved. (In my case i got it from config file, root path of project).*/
    const uploadPath = "/home/documents/project";
    //path of folder where you want to save the image.
    const localPath = `${uploadPath}/uploads/images/`;
    //Find extension of file
    const ext = baseImage.substring(baseImage.indexOf("/")+1, baseImage.indexOf(";base64"));
    const fileType = baseImage.substring("data:".length,baseImage.indexOf("/"));
    //Forming regex to extract base64 data of file.
    const regex = new RegExp(`^data:${fileType}\/${ext};base64,`, 'gi');
    //Extract base64 data.
    const base64Data = baseImage.replace(regex, "");
    const filename = `${uuid()}.${ext}`;

    //Check that if directory is present or not.
    if(!fs.existsSync(`${uploadPath}/uploads/`)) {
        fs.mkdirSync(`${uploadPath}/uploads/`);
    }
    if (!fs.existsSync(localPath)) {
        fs.mkdirSync(localPath);
    }
    fs.writeFileSync(localPath+filename, base64Data, 'base64');
    return filename;
}

Web API Put Request generates an Http 405 Method Not Allowed error

Decorating one of the action params with [FromBody] solved the issue for me:

public async Task<IHttpActionResult> SetAmountOnEntry(string id, [FromBody]int amount)

However ASP.NET would infer it correctly if complex object was used in the method parameter:

public async Task<IHttpActionResult> UpdateEntry(string id, MyEntry entry)

How to create a Custom Dialog box in android?

I am posting the kotlin code that I am using and it works fine for me. you can also set click listener for dialog buttons.

this is my XML code:

layout_custom_alert_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layoutDirection="ltr"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <View
        android:id="@+id/view6"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:background="@color/colorPrimary" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/view6"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp">


        <TextView
            android:id="@+id/txt_alert_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            tools:text="are you sure?"
            android:textAlignment="center"
            android:textColor="@android:color/black"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />


        <Button
            android:id="@+id/btn_alert_positive"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/textView2"
            android:layout_marginTop="8dp"
            android:background="@android:color/transparent"
            tools:text="yes"
            android:textColor="@color/colorPrimaryDark"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toEndOf="@+id/btn_alert_negative"
            app:layout_constraintTop_toBottomOf="@+id/txt_alert_title" />

        <Button
            android:id="@+id/btn_alert_negative"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:background="@android:color/transparent"
            tools:text="no"
            android:textColor="@color/colorPrimaryDark"
            app:layout_constraintEnd_toStartOf="@+id/btn_alert_positive"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/txt_alert_title" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>

mAlertDialog.kt

class mAlertDialog(context: Context) {

    private val btn_positive : Button
    private val btn_negative : Button
    private val txt_alert_title : TextView
    private val dialog : AlertDialog
    init {
        val view = LayoutInflater.from(context).inflate(R.layout.layout_custom_alert_dialog,null)

        val dialog_builder = AlertDialog.Builder(context)
        dialog_builder.setView(view)

        btn_negative = view.findViewById(R.id.btn_alert_negative)
        btn_positive = view.findViewById(R.id.btn_alert_positive)
        txt_alert_title = view.findViewById(R.id.txt_alert_title)

        dialog = dialog_builder.create() 
    }

    fun show()
    {
        dialog.show()
    }

    fun setPositiveClickListener(listener :onClickListener)
    {
        btn_positive.setOnClickListener { v ->
            listener.onClick(btn_positive)
            dialog.dismiss()
        }
    }

    fun setNegativeClickListener(listener: onClickListener)
    {
        btn_negative.setOnClickListener { v ->
            listener.onClick(btn_negative)
            dialog.dismiss()
        }
    }

    fun setPoitiveButtonText(text : String)
    {
        btn_positive.text = text
    }


    fun setNegativeButtonText(text : String)
    {
        btn_negative.text = text
    }

    fun setAlertTitle(title : String)
    {
        txt_alert_title.text = title
    }
}

interface for click listeners:

onClickListener.kt

interface onClickListener{
    fun onClick(view : View)
}

Sample Usage

val dialog = mAlertDialog(context)
                dialog.setNegativeButtonText("no i dont")
                dialog.setPoitiveButtonText("yes is do")
                dialog.setAlertTitle("do you like this alert dialog?")

                dialog.setPositiveClickListener(object : onClickListener {
                    override fun onClick(view: View) {
                        Toast.makeText(context, "yes", Toast.LENGTH_SHORT).show()
                    }
                })

                dialog.setNegativeClickListener(object : onClickListener {
                    override fun onClick(view: View) {
                        Toast.makeText(context, "no", Toast.LENGTH_SHORT).show()
                    }
                })

                dialog.show()

I hope, this will help you!

How to get the latest file in a folder?

max(files, key = os.path.getctime)

is quite incomplete code. What is files? It probably is a list of file names, coming out of os.listdir().

But this list lists only the filename parts (a. k. a. "basenames"), because their path is common. In order to use it correctly, you have to combine it with the path leading to it (and used to obtain it).

Such as (untested):

def newest(path):
    files = os.listdir(path)
    paths = [os.path.join(path, basename) for basename in files]
    return max(paths, key=os.path.getctime)

How to empty a file using Python

Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:

open(filename, 'w').close()

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

How can I set size of a button?

The following bit of code does what you ask for. Just make sure that you assign enough space so that the text on the button becomes visible

JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4,4,4,4));

for(int i=0 ; i<16 ; i++){
    JButton btn = new JButton(String.valueOf(i));
    btn.setPreferredSize(new Dimension(40, 40));
    panel.add(btn);
}
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);

The X and Y (two first parameters of the GridLayout constructor) specify the number of rows and columns in the grid (respectively). You may leave one of them as 0 if you want that value to be unbounded.

Edit

I've modified the provided code and I believe it now conforms to what is desired:

JFrame frame = new JFrame("Colored Trails");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(4, 4));
firstPanel.setMaximumSize(new Dimension(400, 400));
JButton btn;
for (int i=1; i<=4; i++) {
    for (int j=1; j<=4; j++) {
        btn = new JButton();
        btn.setPreferredSize(new Dimension(100, 100));
        firstPanel.add(btn);
    }
}

JPanel secondPanel = new JPanel();
secondPanel.setLayout(new GridLayout(5, 13));
secondPanel.setMaximumSize(new Dimension(520, 200));
for (int i=1; i<=5; i++) {
    for (int j=1; j<=13; j++) {
        btn = new JButton();
        btn.setPreferredSize(new Dimension(40, 40));
        secondPanel.add(btn);
    }
}

mainPanel.add(firstPanel);
mainPanel.add(secondPanel);
frame.setContentPane(mainPanel);

frame.setSize(520,600);
frame.setMinimumSize(new Dimension(520,600));
frame.setVisible(true);

Basically I now set the preferred size of the panels and a minimum size for the frame.

How to get the day of week and the month of the year?

Using http://phrogz.net/JS/FormatDateTime_JS.txt you can just:

var now = new Date;
var prnDt = now.customFormat( "Printed on #DDDD#, #D# #MMMM# #YYYY# at #hhh#:#mm#:#ss#" );

Validating Phone Numbers Using Javascript

Having seen simply too many edge cases, I went for a simpler check:

^(([0-9\ \+\_\-\,\.\^\*\?\$\^\#\(\)])|(ext|x)){1,20}$

The first thing one may point out is allowing repetition of "ext", but the purpose of this regex is to prevent users from accidentally entering email ids etc. instead of phone numbers, which it does.

What is the C# equivalent of friend?

The closet equivalent is to create a nested class which will be able to access the outer class' private members. Something like this:

class Outer
{
    class Inner
    {
       // This class can access Outer's private members
    }
}

or if you prefer to put the Inner class in another file:

Outer.cs
partial class Outer
{
}


Inner.cs
partial class Outer
{
    class Inner
    {
       // This class can access Outer's private members
    }
}

How to check if another instance of the application is running

It's not sure what you mean with 'the program', but if you want to limit your application to one instance then you can use a Mutex to make sure that your application isn't already running.

[STAThread]
static void Main()
{
    Mutex mutex = new System.Threading.Mutex(false, "MyUniqueMutexName");
    try
    {
        if (mutex.WaitOne(0, false))
        {
            // Run the application
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
        else
        {
            MessageBox.Show("An instance of the application is already running.");
        }
    }
    finally
    {
        if (mutex != null)
        {
            mutex.Close();
            mutex = null;
        }
    }
}

JPA eager fetch does not join

to join you can do multiple things (using eclipselink)

  • in jpql you can do left join fetch

  • in named query you can specify query hint

  • in TypedQuery you can say something like

    query.setHint("eclipselink.join-fetch", "e.projects.milestones");

  • there is also batch fetch hint

    query.setHint("eclipselink.batch", "e.address");

see

http://java-persistence-performance.blogspot.com/2010/08/batch-fetching-optimizing-object-graph.html

How to capture multiple repeated groups?

I think you need something like this....

b="HELLO,THERE,WORLD"
re.findall('[\w]+',b)

Which in Python3 will return

['HELLO', 'THERE', 'WORLD']

How to convert a Collection to List?

Collections.sort( new ArrayList( coll ) );

How can I truncate a double to only two decimal places in Java?

Maybe following :

double roundTwoDecimals(double d) { 
      DecimalFormat twoDForm = new DecimalFormat("#.##"); 
      return Double.valueOf(twoDForm.format(d));
}  

Bootstrap modal z-index

I had this problem too. Problem is comming from html, created by bootstrap js:

<div class="modal-backdrop fade in"></div>

This line is created directly before end of <body> element. This cause "z-index stacked element problem." I believe that bootstrap .js do creation of this element wrong. If you have in mvc layout page, this script will cause still the same problem. Beter js idea cut be to get target modal id and inject this line to html before...

this.$backdrop = $(document.createElement('div'))
    .addClass('modal-backdrop ' + animate)
    .appendTo(this.$body)

SO SOLUTION IS repair bootstrap.js - part of modal:

.appendTo(this.$body)  
//REPLACE TO THIS:
 .insertBefore(this.$element) 

how to implement regions/code collapse in javascript

By marking a section of code (regardless of any logical blocks) and hitting CTRL + M + H you’ll define the selection as a region which is collapsible and expandable.

Box shadow for bottom side only

-webkit-box-shadow: 0 3px 5px -3px #000;
-moz-box-shadow: 0 3px 5px -3px #000;
box-shadow: 0 3px 5px -3px #000;

Appending a byte[] to the end of another byte[]

Using System.arraycopy(), something like the following should work:

// create a destination array that is the size of the two arrays
byte[] destination = new byte[ciphertext.length + mac.length];

// copy ciphertext into start of destination (from pos 0, copy ciphertext.length bytes)
System.arraycopy(ciphertext, 0, destination, 0, ciphertext.length);

// copy mac into end of destination (from pos ciphertext.length, copy mac.length bytes)
System.arraycopy(mac, 0, destination, ciphertext.length, mac.length);

How to update ruby on linux (ubuntu)?

First, which version of ubuntu are you using, it might be easiest to just upgrade to one that has it.

Next, enable backports (system menue, adminstration, software sources), and search for in in synaptic.

Last, look for a ppa for it.

Convert Enumeration to a Set/List

If you need Set rather than List, you can use EnumSet.allOf().

Set<EnumerationClass> set = EnumSet.allOf(EnumerationClass.class);

Update: JakeRobb is right. My answer is about java.lang.Enum instead of java.util.Enumeration. Sorry for unrelated answer.

Image encryption/decryption using AES256 symmetric block ciphers

Here is simple code snippet working for AES Encryption and Decryption.

import android.util.Base64;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class AESEncryptionClass {

    private static String INIT_VECTOR_PARAM = "#####";
    private static String PASSWORD = "#####";
    private static String SALT_KEY = "#####";

    private static SecretKeySpec generateAESKey() throws NoSuchAlgorithmException, InvalidKeySpecException {

        // Prepare password and salt key.
        char[] password = new String(Base64.decode(PASSWORD, Base64.DEFAULT)).toCharArray();
        byte[] salt = new String(Base64.decode(SALT_KEY, Base64.DEFAULT)).getBytes(StandardCharsets.UTF_8);

        // Create object of  [Password Based Encryption Key Specification] with required iteration count and key length.
        KeySpec spec = new PBEKeySpec(password, salt, 64, 256);

        // Now create AES Key using required hashing algorithm.
        SecretKey key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec);

        // Get encoded bytes of secret key.
        byte[] bytesSecretKey = key.getEncoded();

        // Create specification for AES Key.
        SecretKeySpec secretKeySpec = new SecretKeySpec(bytesSecretKey, "AES");
        return secretKeySpec;
    }

    /**
     * Call this method to encrypt the readable plain text and get Base64 of encrypted bytes.
     */
    public static String encryptMessage(String message) throws BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException {

        byte[] initVectorParamBytes = new String(Base64.decode(INIT_VECTOR_PARAM, Base64.DEFAULT)).getBytes(StandardCharsets.UTF_8);

        Cipher encryptionCipherBlock = Cipher.getInstance("AES/CBC/PKCS5Padding");
        encryptionCipherBlock.init(Cipher.ENCRYPT_MODE, generateAESKey(), new IvParameterSpec(initVectorParamBytes));

        byte[] messageBytes = message.getBytes();
        byte[] cipherTextBytes = encryptionCipherBlock.doFinal(messageBytes);
        String encryptedText = Base64.encodeToString(cipherTextBytes, Base64.DEFAULT);
        return encryptedText;
    }

    /**
     * Call this method to decrypt the Base64 of encrypted message and get readable plain text.
     */
    public static String decryptMessage(String base64Cipher) throws BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException {

        byte[] initVectorParamBytes = new String(Base64.decode(INIT_VECTOR_PARAM, Base64.DEFAULT)).getBytes(StandardCharsets.UTF_8);

        Cipher decryptionCipherBlock = Cipher.getInstance("AES/CBC/PKCS5Padding");
        decryptionCipherBlock.init(Cipher.DECRYPT_MODE, generateAESKey(), new IvParameterSpec(initVectorParamBytes));

        byte[] cipherBytes = Base64.decode(base64Cipher, Base64.DEFAULT);
        byte[] messageBytes = decryptionCipherBlock.doFinal(cipherBytes);
        String plainText = new String(messageBytes);
        return plainText;
    }
}

Now, call encryptMessage() or decryptMessage() for desired AES Operation with required parameters.

Also, handle the exceptions during AES operations.

Hope it helped...

What in layman's terms is a Recursive Function using PHP

Basically this. It keeps calling itself until its done

void print_folder(string root)
{
    Console.WriteLine(root);
    foreach(var folder in Directory.GetDirectories(root))
    {
        print_folder(folder);
    }
}

Also works with loops!

void pretend_loop(int c)
{
    if(c==0) return;
    print "hi";
    pretend_loop(c-);
}

You can also trying googling it. Note the "Did you mean" (click on it...). http://www.google.com/search?q=recursion&spell=1

What is the official name for a credit card's 3 digit code?

It is called the Card Security Code (CSC) according to Wikipedia, but has also been known as other things, such as the Card Verification Value (CVV) or Card Verfication Code (CVC).

The second code, and the most cited, is CVV2 or CVC2. This CSC (also known as a CCID or Credit Card ID) is often asked for by merchants for them to secure "card not present" transactions occurring over the Internet, by mail, fax or over the phone. In many countries in Western Europe, due to increased attempts at card fraud, it is now mandatory to provide this code when the cardholder is not present in person.

Because this seems to be known by multiple names, and its name doesn't seem to be printed on the card itself, you'll probably (unfortunately) still need to tell your users how to find the code - ie by describing it as the "3 digit code on back of card".


2018 update

The situation has not improved, and is now worse - there are even more different names now. However, you can if you like use different terms depending on the card type:

  • "CVC2" or "Card Validation Code" – MasterCard
  • "CVV2" or "Card Verification Value 2" – Visa
  • "CSC" or "Card Security Code" – American Express

Note that some American Express and Discover cards use a 4-digit code on the front of the card. See the above linked Wikipedia article for more.

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

use unicode-escape to solve problem

>>>import json
>>>json_string = json.dumps("??? ????")
>>>json_string.encode('ascii').decode('unicode-escape')
'"??? ????"'

explain

>>>s = '?  ?a?  ???'
>>>print('unicode: ' + s.encode('unicode-escape').decode('utf-8'))
unicode: \u6f22  \u03c7\u03b1\u03bd  \u0445\u0430\u043d

>>>u = s.encode('unicode-escape').decode('utf-8')
>>>print('original: ' + u.encode("utf-8").decode('unicode-escape'))
original: ?  ?a?  ???

original resource:https://blog.csdn.net/chuatony/article/details/72628868

What does java.lang.Thread.interrupt() do?

Thread.interrupt() sets the interrupted status/flag of the target thread to true which when checked using Thread.interrupted() can help in stopping the endless thread. Refer http://www.yegor256.com/2015/10/20/interrupted-exception.html

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

simple to fix you re is :

// example.d.ts
declare module 'foo';

if you want to declarate interface of object (Recommend for big project) you can use :

// example.d.ts
declare module 'foo'{
    // example
    export function getName(): string
}

How to use that? simple..

const x = require('foo') // or import x from 'foo'
x.getName() // intellisense can read this

PHP checkbox set to check based on database value

Extract the information from the database for the checkbox fields. Next change the above example line to: (this code assumes that you've retrieved the information for the user into an associative array called dbvalue and the DB field names match those on the HTML form)

<input type="checkbox" name="tag_1" id="tag_1" value="yes" <?php echo ($dbvalue['tag_1']==1 ? 'checked' : '');?>>

If you're looking for the code to do everything for you, you've come to the wrong place.

Way to create multiline comments in Bash?

what's your opinion on this one?

function giveitauniquename()
{
  so this is a comment
  echo "there's no need to further escape apostrophes/etc if you are commenting your code this way"
  the drawback is it will be stored in memory as a function as long as your script runs unless you explicitly unset it
  only valid-ish bash allowed inside for instance these would not work without the "pound" signs:
  1, for #((
  2, this #wouldn't work either
  function giveitadifferentuniquename()
  {
    echo nestable
  }
}

Undefined or null for AngularJS

Why not simply use angular.isObject with negation? e.g.

if (!angular.isObject(obj)) {
    return;
}

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a distributed version control system. It usually runs at the command line of your local machine. It keeps track of your files and modifications to those files in a "repository" (or "repo"), but only when you tell it to do so. (In other words, you decide which files to track and when to take a "snapshot" of any modifications.)

    In contrast, GitHub is a website that allows you to publish your Git repositories online, which can be useful for many reasons (see #3).

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    Git is known as a "distributed" (rather than "centralized") version control system because you can run it locally and disconnected from the Internet, and then "push" your changes to a remote system (such as GitHub) whenever you like. Thus, repo changes only appear on GitHub when you manually tell Git to push those changes.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, you can use Git without GitHub. Git is the "workhorse" program that actually tracks your changes, whereas GitHub is simply hosting your repositories (and provides additional functionality not available in Git). Here are some of the benefits of using GitHub:

    • It provides a backup of your files.
    • It gives you a visual interface for navigating your repos.
    • It gives other people a way to navigate your repos.
    • It makes repo collaboration easy (e.g., multiple people contributing to the same project).
    • It provides a lightweight issue tracking system.
  4. How does Git compare to a backup system such as Time Machine?

    Git does backup your files, though it gives you much more granular control than a traditional backup system over what and when you backup. Specifically, you "commit" every time you want to take a snapshot of changes, and that commit includes both a description of your changes and the line-by-line details of those changes. This is optimal for source code because you can easily see the change history for any given file at a line-by-line level.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, this is a manual process.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • Git employs a powerful branching system that allows you to work on multiple, independent lines of development simultaneously and then merge those branches together as needed.
    • Git allows you to view the line-by-line differences between different versions of your files, which makes troubleshooting easier.
    • Git forces you to describe each of your commits, which makes it significantly easier to track down a specific previous version of a given file (and potentially revert to that previous version).
    • If you ever need help with your code, having it tracked by Git and hosted on GitHub makes it much easier for someone else to look at your code.

For getting started with Git, I recommend the online book Pro Git as well as GitRef as a handy reference guide. For getting started with GitHub, I like the GitHub's Bootcamp and their GitHub Guides. Finally, I created a short videos series to introduce Git and GitHub to beginners.

Iframe positioning

you have to use this css property,

 position:relative;

use it for your #contentframe div tag

Assert a function/method was not called using Mock

With python >= 3.5 you can use mock_object.assert_not_called().

Inserting image into IPython notebook markdown

For those looking where to place the image file on the Jupyter machine so that it could be shown from the local file system.

I put my mypic.png into

/root/Images/mypic.png

(that is the Images folder that shows up in the Jupyter online file browser)

In that case I need to put the following line into the Markdown cell to make my pic showing in the notepad:

![My Title](Images/mypic.png)

How do I get a decimal value when using the division operator in Python?

You cant get a decimal value by dividing one integer with another, you'll allways get an integer that way (result truncated to integer). You need at least one value to be a decimal number.

JavaScript push to array

It's not an array.

var json = {"cool":"34.33","alsocool":"45454"};
json.coolness = 34.33;

or

var json = {"cool":"34.33","alsocool":"45454"};
json['coolness'] = 34.33;

you could do it as an array, but it would be a different syntax (and this is almost certainly not what you want)

var json = [{"cool":"34.33"},{"alsocool":"45454"}];
json.push({"coolness":"34.33"});

Note that this variable name is highly misleading, as there is no JSON here. I would name it something else.

Using sendmail from bash script for multiple recipients

Try doing this :

recipients="[email protected],[email protected],[email protected]"

And another approach, using shell here-doc :

/usr/sbin/sendmail "$recipients" <<EOF
subject:$subject
from:$from

Example Message
EOF

Be sure to separate the headers from the body with a blank line as per RFC 822.

Multidimensional Array [][] vs [,]

double[][] is an array of arrays and double[,] is a matrix. If you want to initialize an array of array, you will need to do this:

double[][] ServicePoint = new double[10][]
for(var i=0;i<ServicePoint.Length;i++)
    ServicePoint[i] = new double[9];

Take in account that using arrays of arrays will let you have arrays of different lengths:

ServicePoint[0] = new double[10];
ServicePoint[1] = new double[3];
ServicePoint[2] = new double[5];
//and so on...

How do you create an asynchronous method in C#?

I don't recommend StartNew unless you need that level of complexity.

If your async method is dependent on other async methods, the easiest approach is to use the async keyword:

private static async Task<DateTime> CountToAsync(int num = 10)
{
  for (int i = 0; i < num; i++)
  {
    await Task.Delay(TimeSpan.FromSeconds(1));
  }

  return DateTime.Now;
}

If your async method is doing CPU work, you should use Task.Run:

private static async Task<DateTime> CountToAsync(int num = 10)
{
  await Task.Run(() => ...);
  return DateTime.Now;
}

You may find my async/await intro helpful.

How to get every first element in 2 dimensional list

You can get the index [0] from each element in a list comprehension

>>> [i[0] for i in a]
[4.0, 3.0, 3.5]

Also just to be pedantic, you don't have a list of list, you have a tuple of tuple.

How do I mock an autowired @Value field in Spring with Mockito?

I used the below code and it worked for me:

@InjectMocks
private ClassABC classABC;

@Before
public void setUp() {
    ReflectionTestUtils.setField(classABC, "constantFromConfigFile", 3);
}

Reference: https://www.jeejava.com/mock-an-autowired-value-field-in-spring-with-junit-mockito/

JavaScript REST client Library

You can use this jQuery plugin I just made :) https://github.com/jpillora/jquery.rest/

Supports basic CRUD operations, nested resources, basic auth

  var client = new $.RestClient('/api/rest/');

  client.add('foo');
  client.foo.add('baz');
  client.add('bar');

  client.foo.create({a:21,b:42});
  // POST /api/rest/foo/ (with data a=21 and b=42)
  client.foo.read();
  // GET /api/rest/foo/
  client.foo.read("42");
  // GET /api/rest/foo/42/
  client.foo.update("42");
  // PUT /api/rest/foo/42/
  client.foo.delete("42");
  // DELETE /api/rest/foo/42/

  //RESULTS USE '$.Deferred'
  client.foo.read().success(function(foos) {
    alert('Hooray ! I have ' + foos.length + 'foos !' );
  });

If you find bugs or want new features, post them in the repositories 'Issues' page please

Set a default parameter value for a JavaScript function

_x000D_
_x000D_
function throwIfNoValue() {_x000D_
throw new Error('Missing argument');_x000D_
}_x000D_
function foo(argValue = throwIfNoValue()) {_x000D_
return argValue ;_x000D_
}
_x000D_
_x000D_
_x000D_

Here foo() is a function which has a parameter named argValue. If we don’t pass anything in the function call here, then the function throwIfNoValue() will be called and the returned result will be assigned to the only argument argValue. This is how a function call can be used as a default parameter. Which makes the code more simplified and readable.

This example has been taken from here

How do I check if I'm running on Windows in Python?

Python os module

Specifically for Python 3.6/3.7:

os.name: The name of the operating system dependent module imported. The following names have currently been registered: 'posix', 'nt', 'java'.

In your case, you want to check for 'nt' as os.name output:

import os

if os.name == 'nt':
     ...

There is also a note on os.name:

See also sys.platform has a finer granularity. os.uname() gives system-dependent version information.

The platform module provides detailed checks for the system’s identity.

How do I get the current location of an iframe?

document.getElementById('iframeID').contentWindow.location.href

You can't access cross-domain iframe location at all.

Why does the order in which libraries are linked sometimes cause errors in GCC?

The GNU ld linker is a so-called smart linker. It will keep track of the functions used by preceding static libraries, permanently tossing out those functions that are not used from its lookup tables. The result is that if you link a static library too early, then the functions in that library are no longer available to static libraries later on the link line.

The typical UNIX linker works from left to right, so put all your dependent libraries on the left, and the ones that satisfy those dependencies on the right of the link line. You may find that some libraries depend on others while at the same time other libraries depend on them. This is where it gets complicated. When it comes to circular references, fix your code!

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

Microsoft is releasing the "Microsoft Edge WebView2" WPF control that will get us a great, free option for embedding Chromium across Windows 10, Windows 8.1, or Windows 7. It is available via Nuget as the package Microsoft.Web.WebView2.

Delete a dictionary item if the key exists

There is also:

try:
    del mydict[key]
except KeyError:
    pass

This only does 1 lookup instead of 2. However, except clauses are expensive, so if you end up hitting the except clause frequently, this will probably be less efficient than what you already have.

How do I install a plugin for vim?

I think you should have a look at the Pathogen plugin. After you have this installed, you can keep all of your plugins in separate folders in ~/.vim/bundle/, and Pathogen will take care of loading them.

Or, alternatively, perhaps you would prefer Vundle, which provides similar functionality (with the added bonus of automatic updates from plugins in github).

How do I find the number of arguments passed to a Bash script?

to add the original reference:

You can get the number of arguments from the special parameter $#. Value of 0 means "no arguments". $# is read-only.

When used in conjunction with shift for argument processing, the special parameter $# is decremented each time Bash Builtin shift is executed.

see Bash Reference Manual in section 3.4.2 Special Parameters:

  • "The shell treats several parameters specially. These parameters may only be referenced"

  • and in this section for keyword $# "Expands to the number of positional parameters in decimal."

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Can't upvote so I'll repost @jfs comment cause I think it should be more visible.

@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02

How can I send large messages with Kafka (over 15MB)?

You need to adjust three (or four) properties:

  • Consumer side:fetch.message.max.bytes - this will determine the largest size of a message that can be fetched by the consumer.
  • Broker side: replica.fetch.max.bytes - this will allow for the replicas in the brokers to send messages within the cluster and make sure the messages are replicated correctly. If this is too small, then the message will never be replicated, and therefore, the consumer will never see the message because the message will never be committed (fully replicated).
  • Broker side: message.max.bytes - this is the largest size of the message that can be received by the broker from a producer.
  • Broker side (per topic): max.message.bytes - this is the largest size of the message the broker will allow to be appended to the topic. This size is validated pre-compression. (Defaults to broker's message.max.bytes.)

I found out the hard way about number 2 - you don't get ANY exceptions, messages, or warnings from Kafka, so be sure to consider this when you are sending large messages.

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

How to go from one page to another page using javascript?

To simply redirect a browser using javascript:

window.location.href = "http://example.com/new_url";

To redirect AND submit a form (i.e. login details), requires no javascript:

<form action="/new_url" method="POST">
   <input name="username">
   <input type="password" name="password">
   <button type="submit">Submit</button>
</form>

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

I find it useful, because when I didn't know about env, before I started to write script I was doing this:

type nodejs > scriptname.js #or any other environment

and then I was modifying that line in the file into shebang.
I was doing this, because I didn't always remember where is nodejs on my computer -- /usr/bin/ or /bin/, so for me env is very useful. Maybe there are details with this, but this is my reason

How do I know if jQuery has an Ajax request pending?

We have to utilize $.ajax.abort() method to abort request if the request is active. This promise object uses readyState property to check whether the request is active or not.

HTML

<h3>Cancel Ajax Request on Demand</h3>
<div id="test"></div>
<input type="button" id="btnCancel" value="Click to Cancel the Ajax Request" />

JS Code

//Initial Message
var ajaxRequestVariable;
$("#test").html("Please wait while request is being processed..");

//Event handler for Cancel Button
$("#btnCancel").on("click", function(){
if (ajaxRequestVariable !== undefined)

if (ajaxRequestVariable.readyState > 0 && ajaxRequestVariable.readyState < 4)
{
  ajaxRequestVariable.abort();
  $("#test").html("Ajax Request Cancelled.");
}
});

//Ajax Process Starts
ajaxRequestVariable = $.ajax({
            method: "POST",
            url: '/echo/json/',
            contentType: "application/json",
            cache: false,
            dataType: "json",
            data: {
        json: JSON.encode({
         data:
             [
                            {"prop1":"prop1Value"},
                    {"prop1":"prop2Value"}
                  ]         
        }),
        delay: 11
    },

            success: function (response) {
            $("#test").show();
            $("#test").html("Request is completed");           
            },
            error: function (error) {

            },
            complete: function () {

            }
        });

Should I use JSLint or JSHint JavaScript validation?

There is also an another actively developed alternative - JSCS — JavaScript Code Style:

JSCS is a code style linter for programmatically enforcing your style guide. You can configure JSCS for your project in detail using over 150 validation rules, including presets from popular style guides like jQuery, Airbnb, Google, and more.

It comes with multiple presets that you can choose from by simply specifying the preset in the .jscsrc configuration file and customize it - override, enable or disable any rules:

{
    "preset": "jquery",
    "requireCurlyBraces": null
}

There are also plugins and extensions built for popular editors.

Also see:

Exit from app when click button in android phonegap?

sorry i can't reply in comment. just FYI, these codes

if (navigator.app) {
navigator.app.exitApp();
}
else if (navigator.device) {
  navigator.device.exitApp();
}
else {
          window.close();
}

i confirm doesn't work. i use phonegap 6.0.5 and cordova 6.2.0

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

As a counter point to the general thrust of the other answers. See The Many Benefits of Money…Data Type! in SQLCAT's Guide to Relational Engine

Specifically I would point out the following

Working on customer implementations, we found some interesting performance numbers concerning the money data type. For example, when Analysis Services was set to the currency data type (from double) to match the SQL Server money data type, there was a 13% improvement in processing speed (rows/sec). To get faster performance within SQL Server Integration Services (SSIS) to load 1.18 TB in under thirty minutes, as noted in SSIS 2008 - world record ETL performance, it was observed that changing the four decimal(9,2) columns with a size of 5 bytes in the TPC-H LINEITEM table to money (8 bytes) improved bulk inserting speed by 20% ... The reason for the performance improvement is because of SQL Server’s Tabular Data Stream (TDS) protocol, which has the key design principle to transfer data in compact binary form and as close as possible to the internal storage format of SQL Server. Empirically, this was observed during the SSIS 2008 - world record ETL performance test using Kernrate; the protocol dropped significantly when the data type was switched to money from decimal. This makes the transfer of data as efficient as possible. A complex data type needs additional parsing and CPU cycles to handle than a fixed-width type.

So the answer to the question is "it depends". You need to be more careful with certain arithmetical operations to preserve precision but you may find that performance considerations make this worthwhile.

How to query for today's date and 7 days before data?

Query in Parado's answer is correct, if you want to use MySql too instead GETDATE() you must use (because you've tagged this question with Sql server and Mysql):

select * from tab
where DateCol between adddate(now(),-7) and now() 

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

"preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Decimal to Hexadecimal Converter in Java

Here's mine

public static String dec2Hex(int num)
{
    String hex = "";

    while (num != 0)
    {
        if (num % 16 < 10)
            hex = Integer.toString(num % 16) + hex;
        else
            hex = (char)((num % 16)+55) + hex;
        num = num / 16;
    }

    return hex;
}

XPath to get all child nodes (elements, comments, and text) without parent

Use this XPath expression:

/*/*/X/node()

This selects any node (element, text node, comment or processing instruction) that is a child of any X element that is a grand-child of the top element of the XML document.

To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>
 <xsl:template match="/">
  <xsl:copy-of select="/*/*/X/node()"/>
 </xsl:template>
</xsl:stylesheet>

and it produces exactly the wanted, correct result:

   First Text Node #1            
    <y> Y can Have Child Nodes #                
        <child> deep to it </child>
    </y>            Second Text Node #2 
    <z />

Explanation:

  1. As defined in the W3 XPath 1.0 Spec, "child::node() selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.

  2. node() is an abbreviation of child::node() (because child:: is the primary axis and is used when no axis is explicitly specified).

IE11 meta element Breaks SVG

I figured it out! The page was rendering using IE8 mode... had

<meta http-equiv="X-UA-Compatible" content="IE=8">

in the header... changed it to

<meta http-equiv="X-UA-Compatible" content="IE=9">

9 and it worked!

Check if a string matches a regex in Bash script

A good way to test if a string is a correct date is to use the command date:

if date -d "${DATE}" >/dev/null 2>&1
then
  # do what you need to do with your date
else
  echo "${DATE} incorrect date" >&2
  exit 1
fi

from comment: one can use formatting

if [ "2017-01-14" == $(date -d "2017-01-14" '+%Y-%m-%d') ] 

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

I had a somehow similar problem working with AFNetworking from a Swift codebase so I'm just leaving this here in the remote case someone is as unlucky as me having to work in such a setup. If you are, I feel you buddy, stay strong!

The operation was failing due to "unacceptable content-type", despite me actually setting the acceptableContentTypes with a Set containing the content type value in question.

The solution for me was to tweak the Swift code to be more Objective-C friendly, I guess:

serializer.acceptableContentTypes = NSSet(array: ["application/xml", "text/xml", "text/plain"]) as Set<NSObject>

How to preview an image before and after upload?

meVeekay's answer was good and am just making it more improvised by doing 2 things.

  1. Check whether browser supports HTML5 FileReader() or not.

  2. Allow only image file to be upload by checking its extension.

HTML :

<div id="wrapper">
    <input id="fileUpload" type="file" />
    <br />
    <div id="image-holder"></div>
</div> 

jQuery :

$("#fileUpload").on('change', function () {

    var imgPath = $(this)[0].value;
    var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();

    if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
        if (typeof (FileReader) != "undefined") {

            var image_holder = $("#image-holder");
            image_holder.empty();

            var reader = new FileReader();
            reader.onload = function (e) {
                $("<img />", {
                    "src": e.target.result,
                        "class": "thumb-image"
                }).appendTo(image_holder);

            }
            image_holder.show();
            reader.readAsDataURL($(this)[0].files[0]);
        } else {
            alert("This browser does not support FileReader.");
        }
    } else {
        alert("Pls select only images");
    }
});

For detail understanding of FileReader()

Check this Article : Using FileReader() preview image before uploading.

Vue.js img src concatenate variable and text

You can't use curlies (moustache tags) in attributes. Use the following to concat data:

<img v-bind:src="imgPreUrl + 'img/logo.png'">

Or the short version:

<img :src="imgPreUrl + 'img/logo.png'">

Read more on dynamic attributes in the Vue docs.

How to install latest version of Node using Brew

Just used this solution with Homebrew 0.9.5 and it seemed like a quick solution to upgrade to the latest stable version of node.

brew update

This will install the latest version

brew install node

Unlink your current version of node use, node -v, to find this

brew unlink node012

This will change to the most up to date version of node.

brew link node

Note: This solution worked as a result of me getting this error:

Error: No such keg: /usr/local/Cellar/node

Table with table-layout: fixed; and how to make one column wider

Are you creating a very large table (hundreds of rows and columns)? If so, table-layout: fixed; is a good idea, as the browser only needs to read the first row in order to compute and render the entire table, so it loads faster.

But if not, I would suggest dumping table-layout: fixed; and changing your css as follows:

table th, table td{
border: 1px solid #000;
width:20px;  //or something similar   
}

table td.wideRow, table th.wideRow{
width: 300px;
}

http://jsfiddle.net/6p9K3/1/

find all unchecked checkbox in jquery

$("input[type='checkbox']:not(:checked):not('\#chkAll\')").map(function () { 
   var a = ""; 
   if (this.name != "chkAll") { 
      a = this.name + "|off"; 
   } 
   return a; 
}).get().join();

This will retrieve all unchecked checkboxes and exclude the "chkAll" checkbox that I use to check|uncheck all checkboxes. Since I want to know what value I'm passing to the database I set these to off, since the checkboxes give me a value of on.

//looking for unchecked checkboxes, but don’t include the checkbox all that checks or unchecks all checkboxes
//.map - Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

//.get - Retrieve the DOM elements matched by the jQuery object.
//.join - (javascript) joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).

How to receive serial data using android bluetooth

Take a look at incredible Bluetooth Serial class that has onResume() ability that helped me so much. I hope this helps ;)

Calling Javascript from a html form

Pretty example by Miquel (#32) should be refilled:

<html>
 <head>
  <script type="text/javascript">
   function handleIt(txt) {   // txt == content of form input
    alert("Entered value: " + txt);
   }
  </script>
 </head>
 <body>
 <!-- javascript function in form action must have a parameter. This 
    parameter contains a value of named input -->
  <form name="myform" action="javascript:handleIt(lastname.value)">  
   <input type="text" name="lastname" id="lastname" maxlength="40"> 
   <input name="Submit"  type="submit" value="Update"/>
  </form>
 </body>
</html>

And the form should have:

<form name="myform" action="javascript:handleIt(lastname.value)"> 

How to set or change the default Java (JDK) version on OS X?

add following command to the ~/.zshenv file

export JAVA_HOME=`/usr/libexec/java_home -v 1.8` 

How do we use runOnUiThread in Android?

You can use from this sample :

In the following example, we are going to use this facility to publish the result from a synonym search that was processed by a background thread.

To accomplish the goal during the OnCreate activity callback, we will set up onClickListener to run searchTask on a created thread.

When the user clicks on the Search button, we will create a Runnable anonymous class that searches for the word typed in R.id.wordEt EditText and starts the thread to execute Runnable.

When the search completes, we will create an instance of Runnable SetSynonymResult to publish the result back on the synonym TextView over the UI thread.

This technique is sometime not the most convenient one, especially when we don't have access to an Activity instance; therefore, in the following chapters, we are going to discuss simpler and cleaner techniques to update the UI from a background computing task.

public class MainActivity extends AppCompatActivity {

    class SetSynonymResult implements Runnable {
        String synonym;

        SetSynonymResult(String synonym) {
            this.synonym = synonym;
        }

        public void run() {
            Log.d("AsyncAndroid", String.format("Sending synonym result %s on %d",
                    synonym, Thread.currentThread().getId()) + " !");
            TextView tv = (TextView) findViewById(R.id.synonymTv);
            tv.setText(this.synonym);
        }
    }

    ;

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

        Button search = (Button) findViewById(R.id.searchBut);
        final EditText word = (EditText) findViewById(R.id.wordEt);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Runnable searchTask = new Runnable() {
                    @Override
                    public void run() {
                        String result = searchSynomim(word.getText().toString());
                        Log.d("AsyncAndroid", String.format("Searching for synonym for %s on %s",
                                word.getText(), Thread.currentThread().getName()));
                        runOnUiThread(new SetSynonymResult(result));
                    }
                };
                Thread thread = new Thread(searchTask);
                thread.start();
            }
        });

    }

    static int i = 0;

    String searchSynomim(String word) {
        return ++i % 2 == 0 ? "fake" : "mock";
    }
}

Source :

asynchronous android programming Helder Vasconcelos

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

For me, on Android Studio 4.1, what did the trick was good ole File > Invalidate Cache & Restart

No more Fatal Signals after that. I'm sure it had something to do with the profiler, but can't be certain. I just know restarting AS stopped the crashes on my emulator. enter image description here

Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));      
 $phpExcel->getDefaultStyle()
    ->applyFromArray($styleArray);

int to string in MySQL

Try it using CONCAT

CONCAT('site.com/path/','%', CAST(t1.id AS CHAR(25)), '%','/more')

500 Internal Server Error for php file not for html

Google guides me here but it didn't fix mine, this is a very general question and there are various causes, so I post my problem and solution here for reference in case anyone might read this later.

Another possible cause of 500 error is syntax error in header(...) function, like this one:

header($_SERVER['SERVER_PROTOCOL'] . '200 OK');

Be aware there should be space between server protocol and status code, so it should be:

header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');

So I suggest check your http header call if you have it in your code.

how to set default main class in java?

you can right click on the project select "set configuration" then "Customize", from there you can choose your main class. ScreenShot

Extract filename and extension in Bash

IMHO the best solution has already been given (using shell parameter expansion) and are the best rated one at this time.

I however add this one which just use dumbs commands, which is not efficient and which noone serious should use ever :

FILENAME=$(echo $FILE | cut -d . -f 1-$(printf $FILE | tr . '\n' | wc -l))
EXTENSION=$(echo $FILE | tr . '\n' | tail -1)

Added just for fun :-)

Add default value of datetime field in SQL Server to a timestamp

While the marked answer is correct with:

ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn

You should always be aware of timezones when adding default datetime values in to a column.

Say for example, this datetime value is designed to indicate when a member joined a website and you want it to be displayed back to the user, GETDATE() will give you the server time so could show discrepancies if the user is in a different locale to the server.

If you expect to deal with international users, it is better in some cases to use GETUTCDATE(), which:

Returns the current database system timestamp as a datetime value. The database time zone offset is not included. This value represents the current UTC time (Coordinated Universal Time). This value is derived from the operating system of the computer on which the instance of SQL Server is running.

ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETUTCDATE() FOR YourColumn

When retrieving the values, the front end application/website should transform this value from UTC time to the locale/culture of the user requesting it.

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

If the other answers don't work you can check if something else is using the port with netstat:

netstat -ano | findstr <your port number>

If nothing is already using it, the port might be excluded, try this command to see if the range is blocked by something else:

netsh interface ipv4 show excludedportrange protocol=tcp

Animation CSS3: display + opacity

HOW TO ANIMATE OPACITY WITH CSS:
this is my code:
the CSS code

_x000D_
_x000D_
.item {   
    height:200px;
    width:200px;
    background:red;
    opacity:0;
    transition: opacity 1s ease-in-out;
}

.item:hover {
    opacity: 1;
}
code {
    background: linear-gradient(to right,#fce4ed,#ffe8cc);
}
_x000D_
<div class="item">

</div>
<p><code> move mouse over top of this text</code></p>
_x000D_
_x000D_
_x000D_

or check this demo file

function vote(){
var vote = getElementById("yourOpinion")
if(this.workWithYou):
vote += 1 };
lol

How to compare two columns in Excel and if match, then copy the cell next to it

try this formula in column E:

=IF( AND( ISNUMBER(D2), D2=G2), H2, "")

your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )

you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.

I hope you understand my explanation.

Npm install cannot find module 'semver'

On MS Windows, the solution is to remove %APPDATA%\npm and reinstall node

Effectively use async/await with ASP.NET Web API

I would change your service layer to:

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
    return Task.Run(() =>
    {
        return _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
    }      
}

as you have it, you are still running your _service.Process call synchronously, and gaining very little or no benefit from awaiting it.

With this approach, you are wrapping the potentially slow call in a Task, starting it, and returning it to be awaited. Now you get the benefit of awaiting the Task.

How to get all of the immediate subdirectories in Python

I have to mention the path.py library, which I use very often.

Fetching the immediate subdirectories become as simple as that:

my_dir.dirs()

The full working example is:

from path import Path

my_directory = Path("path/to/my/directory")

subdirs = my_directory.dirs()

NB: my_directory still can be manipulated as a string, since Path is a subclass of string, but providing a bunch of useful methods for manipulating paths

How is the default submit button on an HTML form determined?

When you have multiple submit buttons in a single form and a user presses the ENTER key to submit the form from a text field, this code overrides default functionality, by calling the submit event on the form from the key press event. Here is that code:

$('form input').keypress(function(e){

    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)){ $(e.target).closest('form').submit(); return false; }
    else return true;

});

What does [STAThread] do?

The STAThreadAttribute is essentially a requirement for the Windows message pump to communicate with COM components. Although core Windows Forms does not use COM, many components of the OS such as system dialogs do use this technology.

MSDN explains the reason in slightly more detail:

STAThreadAttribute indicates that the COM threading model for the application is single-threaded apartment. This attribute must be present on the entry point of any application that uses Windows Forms; if it is omitted, the Windows components might not work correctly. If the attribute is not present, the application uses the multithreaded apartment model, which is not supported for Windows Forms.

This blog post (Why is STAThread required?) also explains the requirement quite well. If you want a more in-depth view as to how the threading model works at the CLR level, see this MSDN Magazine article from June 2004 (Archived, Apr. 2009).

mysql count group by having

SELECT COUNT(*) 
FROM   (SELECT COUNT(*) 
        FROM   movies 
        GROUP  BY id 
        HAVING COUNT(genre) = 4) t

How do I find out which settings.xml file maven is using

Use the Maven debug option, ie mvn -X :

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...

In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml.

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

When restoring a backup, how do I disconnect all active connections?

None of these were working for me, couldn't delete or disconnect current users. Also couldn't see any active connections to the DB. Restarting SQL Server (Right click and select Restart) allowed me to do it.

How to set Navigation Drawer to be opened from right to left

I have solved this problem by changing the gravity of the navigationview

android:layout_gravity

to end instead of start

<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/activity_drawer" />

It worked for me.

How to query the permissions on an Oracle directory?

Wasn't sure if you meant which Oracle users can read\write with the directory or the correlation of the permissions between Oracle Directory Object and the underlying Operating System Directory.

As DCookie has covered the Oracle side of the fence, the following is taken from the Oracle documentation found here.

Privileges granted for the directory are created independently of the permissions defined for the operating system directory, and the two may or may not correspond exactly. For example, an error occurs if sample user hr is granted READ privilege on the directory object but the corresponding operating system directory does not have READ permission defined for Oracle Database processes.

How to read attribute value from XmlNode in C#?

you can loop through all attributes like you do with nodes

foreach (XmlNode item in node.ChildNodes)
{ 
    // node stuff...

    foreach (XmlAttribute att in item.Attributes)
    {
        // attribute stuff
    }
}

Can't push image to Amazon ECR - fails with "no basic auth credentials"

I experienced the same issue.

Generating new AWS credentials (access keys) and reconfiguring AWS CLI with new credentials resolved the problem.

Earlier, aws ecr get-login --region us-east-1 generated docker login command with invalid EC registry URL.

Dynamically add event listener

I aso find this extremely confusing. as @EricMartinez points out Renderer2 listen() returns the function to remove the listener:

ƒ () { return element.removeEventListener(eventName, /** @type {?} */ (handler), false); }

If i´m adding a listener

this.listenToClick = this.renderer.listen('document', 'click', (evt) => {
    alert('Clicking the document');
})

I´d expect my function to execute what i intended, not the total opposite which is remove the listener.

// I´d expect an alert('Clicking the document'); 
this.listenToClick();
// what you actually get is removing the listener, so nothing...

In the given scenario, It´d actually make to more sense to name it like:

// Add listeners
let unlistenGlobal = this.renderer.listen('document', 'click', (evt) => {
    console.log('Clicking the document', evt);
})

let removeSimple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
    console.log('Clicking the button', evt);
});

There must be a good reason for this but in my opinion it´s very misleading and not intuitive.

Cannot enqueue Handshake after invoking quit

I think this issue is similar to mine:

  1. Connect to MySQL
  2. End MySQL service (should not quit node script)
  3. Start MySQL service, Node reconnects to MySQL
  4. Query the DB -> FAIL (Cannot enqueue Query after fatal error.)

I solved this issue by recreating a new connection with the use of promises (q).

mysql-con.js

'use strict';
var config          = require('./../config.js');
var colors          = require('colors');
var mysql           = require('mysql');
var q               = require('q');
var MySQLConnection = {};

MySQLConnection.connect = function(){
    var d = q.defer();
    MySQLConnection.connection = mysql.createConnection({
        host                : 'localhost',
        user                : 'root',
        password            : 'password',
        database            : 'database'
    });

    MySQLConnection.connection.connect(function (err) {
        if(err) {
            console.log('Not connected '.red, err.toString().red, ' RETRYING...'.blue);
            d.reject();
        } else {
            console.log('Connected to Mysql. Exporting..'.blue);
            d.resolve(MySQLConnection.connection);
        }
    });
    return d.promise;
};

module.exports = MySQLConnection;

mysqlAPI.js

var colors          = require('colors');
var mysqlCon        = require('./mysql-con.js');
mysqlCon.connect().then(function(con){
   console.log('connected!');
    mysql = con;
    mysql.on('error', function (err, result) {
        console.log('error occurred. Reconneting...'.purple);
        mysqlAPI.reconnect();
    });
    mysql.query('SELECT 1 + 1 AS solution', function (err, results) {
            if(err) console.log('err',err);
            console.log('Works bro ',results);
    });
});

mysqlAPI.reconnect = function(){
    mysqlCon.connect().then(function(con){
      console.log("connected. getting new reference");
        mysql = con;
        mysql.on('error', function (err, result) {
            mysqlAPI.reconnect();
        });
    }, function (error) {
      console.log("try again");
        setTimeout(mysqlAPI.reconnect, 2000);
    });
};

I hope this helps.

Rails how to run rake task

You can run Rake tasks from your shell by running:

rake task_name

To run from from Ruby (e.g., in the Rails console or another Rake task):

Rake::Task['task_name'].invoke

To run multiple tasks in the same namespace with a single task, create the following new task in your namespace:

task :runall => [:iqmedier, :euroads, :mikkelsen, :orville] do
  # This will run after all those tasks have run
end

What is unit testing and how do you do it?

What is unit testing?

Unit testing simply verifies that individual units of code (mostly functions) work as expected. Usually you write the test cases yourself, but some can be automatically generated.

The output from a test can be as simple as a console output, to a "green light" in a GUI such as NUnit, or a different language-specific framework.

Performing unit tests is designed to be simple, generally the tests are written in the form of functions that will determine whether a returned value equals the value you were expecting when you wrote the function (or the value you will expect when you eventually write it - this is called Test Driven Development when you write the tests first).

How do you perform unit tests?

Imagine a very simple function that you would like to test:

int CombineNumbers(int a, int b) {
    return a+b;
}

The unit test code would look something like this:

void TestCombineNumbers() {
    Assert.IsEqual(CombineNumbers(5, 10), 15); // Assert is an object that is part of your test framework
    Assert.IsEqual(CombineNumbers(1000, -100), 900);
}

When you run the tests, you will be informed that these tests have passed. Now that you've built and run the tests, you know that this particular function, or unit, will perform as you expect.

Now imagine another developer comes along and changes the CombineNumbers() function for performance, or some other reason:

int CombineNumbers(int a, int b) {
    return a * b;
}

When the developer runs the tests that you have created for this very simple function, they will see that the first Assert fails, and they now know that the build is broken.

When should you perform unit tests?

They should be done as often as possible. When you are performing tests as part of the development process, your code is automatically going to be designed better than if you just wrote the functions and then moved on. Also, concepts such as Dependency Injection are going to evolve naturally into your code.

The most obvious benefit is knowing down the road that when a change is made, no other individual units of code were affected by it if they all pass the tests.

Automate scp file transfer using a shell script

This will work:

#!/usr/bin/expect -f

spawn scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no file1 file2 file3 user@host:/path/
expect "password:"
send "xyz123\r"
expect "*\r"
expect "\r"
interact

Call-time pass-by-reference has been removed

Only call time pass-by-reference is removed. So change:

call_user_func($func, &$this, &$client ...

To this:

call_user_func($func, $this, $client ...

&$this should never be needed after PHP4 anyway period.

If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {)

Calling a PHP function from an HTML form in the same file

Take a look at this example:

<!DOCTYPE HTML> 
<html>
<head>
</head>
<body> 

<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   $name = test_input($_POST["name"]);
   $email = test_input($_POST["email"]);
   $website = test_input($_POST["website"]);
   $comment = test_input($_POST["comment"]);
   $gender = test_input($_POST["gender"]);
}

function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>

<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
   Name: <input type="text" name="name">
   <br><br>
   E-mail: <input type="text" name="email">
   <br><br>
   Website: <input type="text" name="website">
   <br><br>
   Comment: <textarea name="comment" rows="5" cols="40"></textarea>
   <br><br>
   Gender:
   <input type="radio" name="gender" value="female">Female
   <input type="radio" name="gender" value="male">Male
   <br><br>
   <input type="submit" name="submit" value="Submit"> 
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>

Creating a file only if it doesn't exist in Node.js

Todo this in a single system call you can use the fs-extra npm module. After this the file will have been created as well as the directory it is to be placed in.

const fs = require('fs-extra');
const file = '/tmp/this/path/does/not/exist/file.txt'
fs.ensureFile(file, err => {
    console.log(err) // => null
});

Another way is to use ensureFileSync which will do the same thing but synchronous.

const fs = require('fs-extra');
const file = '/tmp/this/path/does/not/exist/file.txt'
fs.ensureFileSync(file)

Angular 2 Date Input not binding to date value

Instead of [(ngModel)] you can use:

// view
<input type="date" #myDate [value]="demoUser.date | date:'yyyy-MM-dd'" (input)="demoUser.date=parseDate($event.target.value)" />

// controller
parseDate(dateString: string): Date {
    if (dateString) {
        return new Date(dateString);
    }
    return null;
}

You can also choose not to use parseDate function. In this case the date will be saved as string format like "2016-10-06" instead of Date type (I haven't tried whether this has negative consequences when manipulating the data or saving to database for example).

Android Design Support Library expandable Floating Action Button(FAB) menu

In case anyone is still looking for this functionality: I made an Android library that has this ability and much more, called ExpandableFab (https://github.com/nambicompany/expandable-fab).

The Material Design spec refers to this functionality as 'Speed Dial' and ExpandableFab implements it along with many additional features.

Nearly everything is customizable (colors, text, size, placement, margins, animations and more) and optional (don't need an Overlay, or FabOptions, or Labels, or icons, etc). Every property can be accessed or set through XML layouts or programmatically - whatever you prefer.

Written 100% in Kotlin but comes with full JavaDoc and KDoc (published API is well documented). Also comes with an example app so you can see different use cases with 0 coding.

Github: https://github.com/nambicompany/expandable-fab

Library website (w/ links to full documentation): https://nambicompany.github.io/expandable-fab/

Regular ExpandableFab implementing Material Design 'Speed Dial' functionality A highly customized ExpandableFab implementing Material Design 'Speed Dial' functionality

Set auto height and width in CSS/HTML for different screen sizes

This is what do you want? DEMO. Try to shrink the browser's window and you'll see that the elements will be ordered.

What I used? Flexible Box Model or Flexbox.

Just add the follow CSS classes to your container element (in this case div#container):

flex-init-setup and flex-ppal-setup.

Where:

  1. flex-init-setup means flexbox init setup; and
  2. flex-ppal-setup means flexbox principal setup

Here are the CSS rules:

 .flex-init-setup {
     display: -webkit-box;
     display: -moz-box;
     display: -webkit-flex;
     display: -ms-flexbox;
     display: flex;
 }
 .flex-ppal-setup {
     -webkit-flex-flow: column wrap;
     -moz-flex-flow: column wrap;
     flex-flow: column wrap;
     -webkit-justify-content: center;
     -moz-justify-content: center;
     justify-content: center;
 }

Be good, Leonardo

In Python, how to check if a string only contains certain characters?

A different approach, because in my case I needed to also check whether it contained certain words (like 'test' in this example), not characters alone:

input_string = 'abc test'
input_string_test = input_string
allowed_list = ['a', 'b', 'c', 'test', ' ']

for allowed_list_item in allowed_list:
    input_string_test = input_string_test.replace(allowed_list_item, '')

if not input_string_test:
    # test passed

So, the allowed strings (char or word) are cut from the input string. If the input string only contained strings that were allowed, it should leave an empty string and therefore should pass if not input_string.

Is it possible to "decompile" a Windows .exe? Or at least view the Assembly?

Any decent debugger can do this. Try OllyDbg. (edit: which has a great disassembler that even decodes the parameters to WinAPI calls!)

Reset IntelliJ UI to Default

From the main menu, select File | Manage IDE Settings | Restore Default Settings.

Alternatively, press Shift twice and type Restore default settings

Using a custom (ttf) font in CSS

This is not a system font. this font is not supported in other systems. you can use font-face, convert font from this Site or from this

enter image description here

Excel VBA Password via Hex Editor

New version, now you also have the GC= try to replace both DPB and GC with those

DPB="DBD9775A4B774B77B4894C77DFE8FE6D2CCEB951E8045C2AB7CA507D8F3AC7E3A7F59012A2" GC="BAB816BBF4BCF4BCF4"

password will be "test"

Unix shell script find out which directory the script file resides?

The original post contains the solution (ignore the responses, they don't add anything useful). The interesting work is done by the mentioned unix command readlink with option -f. Works when the script is called by an absolute as well as by a relative path.

For bash, sh, ksh:

#!/bin/bash 
# Absolute path to this script, e.g. /home/user/bin/foo.sh
SCRIPT=$(readlink -f "$0")
# Absolute path this script is in, thus /home/user/bin
SCRIPTPATH=$(dirname "$SCRIPT")
echo $SCRIPTPATH

For tcsh, csh:

#!/bin/tcsh
# Absolute path to this script, e.g. /home/user/bin/foo.csh
set SCRIPT=`readlink -f "$0"`
# Absolute path this script is in, thus /home/user/bin
set SCRIPTPATH=`dirname "$SCRIPT"`
echo $SCRIPTPATH

See also: https://stackoverflow.com/a/246128/59087

Distinct pair of values SQL

What you mean is either

SELECT DISTINCT a, b FROM pairs;

or

SELECT a, b FROM pairs GROUP BY a, b;

How can I clear the Scanner buffer in Java?

You can't explicitly clear Scanner's buffer. Internally, it may clear the buffer after a token is read, but that's an implementation detail outside of the porgrammers' reach.

Split by comma and strip whitespace in Python

Split using a regular expression. Note I made the case more general with leading spaces. The list comprehension is to remove the null strings at the front and back.

>>> import re
>>> string = "  blah, lots  ,  of ,  spaces, here "
>>> pattern = re.compile("^\s+|\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
['blah', 'lots', 'of', 'spaces', 'here']

This works even if ^\s+ doesn't match:

>>> string = "foo,   bar  "
>>> print([x for x in pattern.split(string) if x])
['foo', 'bar']
>>>

Here's why you need ^\s+:

>>> pattern = re.compile("\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
['  blah', 'lots', 'of', 'spaces', 'here']

See the leading spaces in blah?

Clarification: above uses the Python 3 interpreter, but results are the same in Python 2.

Pick any kind of file via an Intent in Android

The other answers are not incorrect. However, now there are more options for opening files. For example, if you want the app to have long term, permanent acess to a file, you can use ACTION_OPEN_DOCUMENT instead. Refer to the official documentation: Open files using storage access framework. Also refer to this answer.

How to prevent a dialog from closing when a button is clicked

Kotlin

val dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_userinput, null)
        val dialogBuilder = MaterialAlertDialogBuilder(requireContext(), R.style.AlertDialogTheme)
   
        dialogBuilder.setView(dialogView)
        dialogBuilder.setCancelable(false)
        dialogBuilder.setPositiveButton("send",null)
        dialogBuilder.setNegativeButton("cancel") { dialog,_ ->
        dialog.dismiss()
        }


        val alertDialog = dialogBuilder.create()
        alertDialog.show()

        val positiveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
        positiveButton.setOnClickListener {
            val myInputText = dialogView.etxt_userinput.text.toString().trim()
            if(myInputText.isNotEmpty()){
             //Do something
            }else{
                //Prompt error
                dialogView.etxt_userinput.error = "Please fill this"
            }
        }

We just create an AlertDialog with the dialogBuilder and then just set the positive button as we want

Composer - the requested PHP extension mbstring is missing from your system

I set the PHPRC variable and uncommented zend_extension=php_opcache.dll in php.ini and all works well.

How to pass text in a textbox to JavaScript function?

You could just get the input value in the onclick-event like so:

onclick="execute(document.getElementById('textbox1').value);"

You would of course have to add an id to your textbox

AppSettings get value from .config file

Or you can either use

string value = system.configuration.ConfigurationManager.AppSettings.Get("ClientsFilePath");

//Gets the values associated with the specified key from the System.Collections.Specialized.NameValueCollection

How to convert an int array to String with toString method in Java

This function returns a array of int in the string form like "6097321041141011026"

private String IntArrayToString(byte[] array) {
        String strRet="";
        for(int i : array) {
            strRet+=Integer.toString(i);
        }
        return strRet;
    }

How to specify test directory for mocha?

Now a days(year 2020) you can handle this using mocha configuration file:

Step 1: Create .mocharc.js file at the root location of your application

Step 2: Add below code in mocha config file:

'use strict';

module.exports = {
  spec: 'src/app/**/*.test.js'
};

For More option in config file refer this link: https://github.com/mochajs/mocha/blob/master/example/config/.mocharc.js