Programs & Examples On #Word break

a CSS property that defines how to break or wrap lines within words

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

WebApiConfig.Register(GlobalConfiguration.Configuration); should be on top.

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

There's a huge difference. break-all is basically unusable for rendering readable text.

Let's say you've got the string This is a text from an old magazine in a container which only fits 6 chars per row.

word-break: break-all

This i
s a te
xt fro
m an o
ld mag
azine

As you can see the result is awful. break-all will try to fit as many chararacters into each row as possible, it will even split a 2 letter word like "is" onto 2 rows! It's ridiculous. This is why break-all is rarely ever used.

word-wrap: break-word

This
is a
text
from
an old
magazi
ne

break-word will only break words which are too long to ever fit the container (like "magazine", which is 8 chars, and the container only fits 6 chars). It will never break words that could fit the container in their entirety, instead it will push them to a new line.

_x000D_
_x000D_
<div style="width: 100px; border: solid 1px black; font-family: monospace;">_x000D_
  <h1 style="word-break: break-all;">This is a text from an old magazine</h1>_x000D_
  <hr>_x000D_
  <h1 style="word-wrap: break-word;">This is a text from an old magazine</h1>_x000D_
</div
_x000D_
_x000D_
_x000D_

Soft hyphen in HTML (<wbr> vs. &shy;)

Unfortunately, &shy's support is so inconsistent between browsers that it can't really be used.

QuirksMode is right -- there's no good way to use soft hyphens in HTML right now. See what you can do to go without them.

2013 edit: According to QuirksMode, &shy; now works/is supported on all major browsers.

Cannot install node modules that require compilation on Windows 7 x64/VS2012

After a long struggle, I've switched my node architecture to x86 and it worked like a charm.

Android: Create a toggle button with image and no text

create toggle_selector.xml in res/drawable

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/toggle_on" android:state_checked="true"/>
  <item android:drawable="@drawable/toggle_off" android:state_checked="false"/>
</selector>

apply the selector to your toggle button

<ToggleButton
            android:id="@+id/chkState"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/toggle_selector"
            android:textOff=""
            android:textOn=""/>

Note: for removing the text i used following in above code

textOff=""
textOn=""

Accessing inventory host variable in Ansible playbook

You are on the right track about hostvars.
This magic variable is used to access information about other hosts.

hostvars is a hash with inventory hostnames as keys.
To access fields of each host, use hostvars['test-1'], hostvars['test2-1'], etc.

ansible_ssh_host is deprecated in favor of ansible_host since 2.0.
So you should first remove "_ssh" from inventory hosts arguments (i.e. to become "ansible_user", "ansible_host", and "ansible_port"), then in your role call it with:

{{ hostvars['your_host_group'].ansible_host }}

ImportError: No module named Image

On a system with both Python 2 and 3 installed and with pip2-installed Pillow failing to provide Image, it is possible to install PIL for Python 2 in a way that will solve ImportError: No module named Image:

easy_install-2.7 --user PIL

or

sudo easy_install-2.7 PIL

How to Import .bson file format on mongodb

mongorestore is the tool to use to import bson files that were dumped by mongodump.

From the docs:

mongorestore takes the output from mongodump and restores it.

Example:

# On the server run dump, it will create 2 files per collection
# in ./dump directory:
# ./dump/my-collection.bson
# ./dump/my-collection.metadata.json
mongodump -h 127.0.0.1 -d my-db -c my-collection

# Locally, copy this structure and run restore.
# All collections from ./dump directory are picked up.
scp user@server:~/dump/**/* ./
mongorestore -h 127.0.0.1 -d my-db

Is there a query language for JSON?

The built-in array.filter() method makes most of these so-called javascript query libraries obsolete

You can put as many conditions inside the delegate as you can imagine: simple comparison, startsWith, etc. I haven't tested but you could probably nest filters too for querying inner collections.

Calling a phone number in swift

openURL() has been deprecated in iOS 10. Here is the new syntax:

if let url = URL(string: "tel://\(busPhone)") {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
}

Controlling Maven final name of jar artifact

In my maven ee project I am using:

<build>
    <finalName>shop</finalName>

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>${maven.war.version}</version>
            <configuration><webappDirectory>${project.build.directory}/${project.build.finalName}     </webappDirectory>
            </configuration>
        </plugin>
    </plugins>
</build>

Generating Random Passwords

This is a lot larger, but I think it looks a little more comprehensive: http://www.obviex.com/Samples/Password.aspx

///////////////////////////////////////////////////////////////////////////////
// SAMPLE: Generates random password, which complies with the strong password
//         rules and does not contain ambiguous characters.
//
// To run this sample, create a new Visual C# project using the Console
// Application template and replace the contents of the Class1.cs file with
// the code below.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// 
// Copyright (C) 2004 Obviex(TM). All rights reserved.
// 
using System;
using System.Security.Cryptography;

/// <summary>
/// This class can generate random passwords, which do not include ambiguous 
/// characters, such as I, l, and 1. The generated password will be made of
/// 7-bit ASCII symbols. Every four characters will include one lower case
/// character, one upper case character, one number, and one special symbol
/// (such as '%') in a random order. The password will always start with an
/// alpha-numeric character; it will not start with a special symbol (we do
/// this because some back-end systems do not like certain special
/// characters in the first position).
/// </summary>
public class RandomPassword
{
    // Define default min and max password lengths.
    private static int DEFAULT_MIN_PASSWORD_LENGTH  = 8;
    private static int DEFAULT_MAX_PASSWORD_LENGTH  = 10;

    // Define supported password characters divided into groups.
    // You can add (or remove) characters to (from) these groups.
    private static string PASSWORD_CHARS_LCASE  = "abcdefgijkmnopqrstwxyz";
    private static string PASSWORD_CHARS_UCASE  = "ABCDEFGHJKLMNPQRSTWXYZ";
    private static string PASSWORD_CHARS_NUMERIC= "23456789";
    private static string PASSWORD_CHARS_SPECIAL= "*$-+?_&=!%{}/";

    /// <summary>
    /// Generates a random password.
    /// </summary>
    /// <returns>
    /// Randomly generated password.
    /// </returns>
    /// <remarks>
    /// The length of the generated password will be determined at
    /// random. It will be no shorter than the minimum default and
    /// no longer than maximum default.
    /// </remarks>
    public static string Generate()
    {
        return Generate(DEFAULT_MIN_PASSWORD_LENGTH, 
                        DEFAULT_MAX_PASSWORD_LENGTH);
    }

    /// <summary>
    /// Generates a random password of the exact length.
    /// </summary>
    /// <param name="length">
    /// Exact password length.
    /// </param>
    /// <returns>
    /// Randomly generated password.
    /// </returns>
    public static string Generate(int length)
    {
        return Generate(length, length);
    }

    /// <summary>
    /// Generates a random password.
    /// </summary>
    /// <param name="minLength">
    /// Minimum password length.
    /// </param>
    /// <param name="maxLength">
    /// Maximum password length.
    /// </param>
    /// <returns>
    /// Randomly generated password.
    /// </returns>
    /// <remarks>
    /// The length of the generated password will be determined at
    /// random and it will fall with the range determined by the
    /// function parameters.
    /// </remarks>
    public static string Generate(int   minLength,
                                  int   maxLength)
    {
        // Make sure that input parameters are valid.
        if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)
            return null;

        // Create a local array containing supported password characters
        // grouped by types. You can remove character groups from this
        // array, but doing so will weaken the password strength.
        char[][] charGroups = new char[][] 
        {
            PASSWORD_CHARS_LCASE.ToCharArray(),
            PASSWORD_CHARS_UCASE.ToCharArray(),
            PASSWORD_CHARS_NUMERIC.ToCharArray(),
            PASSWORD_CHARS_SPECIAL.ToCharArray()
        };

        // Use this array to track the number of unused characters in each
        // character group.
        int[] charsLeftInGroup = new int[charGroups.Length];

        // Initially, all characters in each group are not used.
        for (int i=0; i<charsLeftInGroup.Length; i++)
            charsLeftInGroup[i] = charGroups[i].Length;

        // Use this array to track (iterate through) unused character groups.
        int[] leftGroupsOrder = new int[charGroups.Length];

        // Initially, all character groups are not used.
        for (int i=0; i<leftGroupsOrder.Length; i++)
            leftGroupsOrder[i] = i;

        // Because we cannot use the default randomizer, which is based on the
        // current time (it will produce the same "random" number within a
        // second), we will use a random number generator to seed the
        // randomizer.

        // Use a 4-byte array to fill it with random bytes and convert it then
        // to an integer value.
        byte[] randomBytes = new byte[4];

        // Generate 4 random bytes.
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(randomBytes);

        // Convert 4 bytes into a 32-bit integer value.
        int seed = BitConverter.ToInt32(randomBytes, 0);

        // Now, this is real randomization.
        Random  random  = new Random(seed);

        // This array will hold password characters.
        char[] password = null;

        // Allocate appropriate memory for the password.
        if (minLength < maxLength)
            password = new char[random.Next(minLength, maxLength+1)];
        else
            password = new char[minLength];

        // Index of the next character to be added to password.
        int nextCharIdx;

        // Index of the next character group to be processed.
        int nextGroupIdx;

        // Index which will be used to track not processed character groups.
        int nextLeftGroupsOrderIdx;

        // Index of the last non-processed character in a group.
        int lastCharIdx;

        // Index of the last non-processed group.
        int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;

        // Generate password characters one at a time.
        for (int i=0; i<password.Length; i++)
        {
            // If only one character group remained unprocessed, process it;
            // otherwise, pick a random character group from the unprocessed
            // group list. To allow a special character to appear in the
            // first position, increment the second parameter of the Next
            // function call by one, i.e. lastLeftGroupsOrderIdx + 1.
            if (lastLeftGroupsOrderIdx == 0)
                nextLeftGroupsOrderIdx = 0;
            else
                nextLeftGroupsOrderIdx = random.Next(0, 
                                                     lastLeftGroupsOrderIdx);

            // Get the actual index of the character group, from which we will
            // pick the next character.
            nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];

            // Get the index of the last unprocessed characters in this group.
            lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;

            // If only one unprocessed character is left, pick it; otherwise,
            // get a random character from the unused character list.
            if (lastCharIdx == 0)
                nextCharIdx = 0;
            else
                nextCharIdx = random.Next(0, lastCharIdx+1);

            // Add this character to the password.
            password[i] = charGroups[nextGroupIdx][nextCharIdx];

            // If we processed the last character in this group, start over.
            if (lastCharIdx == 0)
                charsLeftInGroup[nextGroupIdx] = 
                                          charGroups[nextGroupIdx].Length;
            // There are more unprocessed characters left.
            else
            {
                // Swap processed character with the last unprocessed character
                // so that we don't pick it until we process all characters in
                // this group.
                if (lastCharIdx != nextCharIdx)
                {
                    char temp = charGroups[nextGroupIdx][lastCharIdx];
                    charGroups[nextGroupIdx][lastCharIdx] = 
                                charGroups[nextGroupIdx][nextCharIdx];
                    charGroups[nextGroupIdx][nextCharIdx] = temp;
                }
                // Decrement the number of unprocessed characters in
                // this group.
                charsLeftInGroup[nextGroupIdx]--;
            }

            // If we processed the last group, start all over.
            if (lastLeftGroupsOrderIdx == 0)
                lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
            // There are more unprocessed groups left.
            else
            {
                // Swap processed group with the last unprocessed group
                // so that we don't pick it until we process all groups.
                if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
                {
                    int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
                    leftGroupsOrder[lastLeftGroupsOrderIdx] = 
                                leftGroupsOrder[nextLeftGroupsOrderIdx];
                    leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
                }
                // Decrement the number of unprocessed groups.
                lastLeftGroupsOrderIdx--;
            }
        }

        // Convert password characters into a string and return the result.
        return new string(password);
     }
}

/// <summary>
/// Illustrates the use of the RandomPassword class.
/// </summary>
public class RandomPasswordTest
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        // Print 100 randomly generated passwords (8-to-10 char long).
        for (int i=0; i<100; i++)
            Console.WriteLine(RandomPassword.Generate(8, 10));
    }
}
//
// END OF FILE
///////////////////////////////////////////////////////////////////////////////

How to match all occurrences of a regex

You can use string.scan(your_regex).flatten. If your regex contains groups, it will return in a single plain array.

string = "A 54mpl3 string w1th 7 numbers scatter3r ar0und"
your_regex = /(\d+)[m-t]/
string.scan(your_regex).flatten
=> ["54", "1", "3"]

Regex can be a named group as well.

string = 'group_photo.jpg'
regex = /\A(?<name>.*)\.(?<ext>.*)\z/
string.scan(regex).flatten

You can also use gsub, it's just one more way if you want MatchData.

str.gsub(/\d/).map{ Regexp.last_match }

invalid_grant trying to get oAuth token from google

I ran into this same problem despite specifying the "offline" access_type in my request as per bonkydog's answer. Long story short I found that the solution described here worked for me:

https://groups.google.com/forum/#!topic/google-analytics-data-export-api/4uNaJtquxCs

In essence, when you add an OAuth2 Client in your Google API's console Google will give you a "Client ID" and an "Email address" (assuming you select "webapp" as your client type). And despite Google's misleading naming conventions, they expect you to send the "Email address" as the value of the client_id parameter when you access their OAuth2 API's.

This applies when calling both of these URL's:

Note that the call to the first URL will succeed if you call it with your "Client ID" instead of your "Email address". However using the code returned from that request will not work when attempting to get a bearer token from the second URL. Instead you will get an 'Error 400' and an "invalid_grant" message.

How to click or tap on a TextView text

from inside an activity that calls a layout and a textview, this click listener works:

setContentView(R.layout.your_layout);
TextView tvGmail = (TextView) findViewById(R.id.tvGmail);
String TAG = "yourLogCatTag";
tvGmail.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View viewIn) {
                try {
                    Log.d(TAG,"GMAIL account selected");
                } catch (Exception except) {
                    Log.e(TAG,"Ooops GMAIL account selection problem "+except.getMessage());
                }
            }
        });

the text view is declared like this (default wizard):

        <TextView
            android:id="@+id/tvGmail"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/menu_id_google"
            android:textSize="30sp" />

and in the strings.xml file

<string name="menu_id_google">Google ID (Gmail)</string>

HTML image not showing in Gmail

I know Gmail already fix all the problem above, the alt and stuff now.

And this is unrelated to the question but probably someone experiences the same as me.

So my web designer use "image" tag instead of "img", but the symptom was the same. It works on outlook but not Gmail.
It takes me an hour to realize. Sigh, such a waste of time.

So make sure the tag is "img" not "image" as well.

Openssl is not recognized as an internal or external command

go to bin folder path in cmd and then run following command

keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl base64

you will get your key hash

Valid content-type for XML, HTML and XHTML documents

HTML: text/html, full-stop.

XHTML: application/xhtml+xml, or only if following HTML compatbility guidelines, text/html. See the W3 Media Types Note.

XML: text/xml, application/xml (RFC 2376).

There are also many other media types based around XML, for example application/rss+xml or image/svg+xml. It's a safe bet that any unrecognised but registered ending in +xml is XML-based. See the IANA list for registered media types ending in +xml.

(For unregistered x- types, all bets are off, but you'd hope +xml would be respected.)

Finding longest string in array

I will do something like this:

function findLongestWord(str) {
var array = str.split(" ");
var maxLength=array[0].length;
for(var i=0; i < array.length; i++ ) {
if(array[i].length > maxLength) maxLength = array[i].length}
return maxLength;}

findLongestWord("What if we try a super-long word such as otorhinolaryngology");

Making interface implementations async

Neither of these options is correct. You're trying to implement a synchronous interface asynchronously. Don't do that. The problem is that when DoOperation() returns, the operation won't be complete yet. Worse, if an exception happens during the operation (which is very common with IO operations), the user won't have a chance to deal with that exception.

What you need to do is to modify the interface, so that it is asynchronous:

interface IIO
{
    Task DoOperationAsync(); // note: no async here
}

class IOImplementation : IIO
{
    public async Task DoOperationAsync()
    {
        // perform the operation here
    }
}

This way, the user will see that the operation is async and they will be able to await it. This also pretty much forces the users of your code to switch to async, but that's unavoidable.

Also, I assume using StartNew() in your implementation is just an example, you shouldn't need that to implement asynchronous IO. (And new Task() is even worse, that won't even work, because you don't Start() the Task.)

Python - OpenCV - imread - Displaying Image

In openCV whenever you try to display an oversized image or image bigger than your display resolution you get the cropped display. It's a default behaviour.
In order to view the image in the window of your choice openCV encourages to use named window. Please refer to namedWindow documentation

The function namedWindow creates a window that can be used as a placeholder for images and trackbars. Created windows are referred to by their names.

cv.namedWindow(name, flags=CV_WINDOW_AUTOSIZE) where each window is related to image container by the name arg, make sure to use same name

eg:

import cv2
frame = cv2.imread('1.jpg')
cv2.namedWindow("Display 1")
cv2.resizeWindow("Display 1", 300, 300)
cv2.imshow("Display 1", frame)

C: What is the difference between ++i and i++?

The effective result of using either in a loop is identical. In other words, the loop will do the same exact thing in both instances.

In terms of efficiency, there could be a penalty involved with choosing i++ over ++i. In terms of the language spec, using the post-increment operator should create an extra copy of the value on which the operator is acting. This could be a source of extra operations.

However, you should consider two main problems with the preceding logic.

  1. Modern compilers are great. All good compilers are smart enough to realize that it is seeing an integer increment in a for-loop, and it will optimize both methods to the same efficient code. If using post-increment over pre-increment actually causes your program to have a slower running time, then you are using a terrible compiler.

  2. In terms of operational time-complexity, the two methods (even if a copy is actually being performed) are equivalent. The number of instructions being performed inside of the loop should dominate the number of operations in the increment operation significantly. Therefore, in any loop of significant size, the penalty of the increment method will be massively overshadowed by the execution of the loop body. In other words, you are much better off worrying about optimizing the code in the loop rather than the increment.

In my opinion, the whole issue simply boils down to a style preference. If you think pre-increment is more readable, then use it. Personally, I prefer the post-incrment, but that is probably because it was what I was taught before I knew anything about optimization.

This is a quintessential example of premature optimization, and issues like this have the potential to distract us from serious issues in design. It is still a good question to ask, however, because there is no uniformity in usage or consensus in "best practice."

Python and pip, list all versions of a package that's available?

For pip >= 20.3 use:

pip install --use-deprecated=legacy-resolver pylibmc==

For updates see: https://github.com/pypa/pip/issues/9139

For pip >= 9.0 use:

$ pip install pylibmc==
Collecting pylibmc==
  Could not find a version that satisfies the requirement pylibmc== (from 
  versions: 0.2, 0.3, 0.4, 0.5.1, 0.5.2, 0.5.3, 0.5.4, 0.5.5, 0.5, 0.6.1, 0.6, 
  0.7.1, 0.7.2, 0.7.3, 0.7.4, 0.7, 0.8.1, 0.8.2, 0.8, 0.9.1, 0.9.2, 0.9, 
  1.0-alpha, 1.0-beta, 1.0, 1.1.1, 1.1, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.3.0)
No matching distribution found for pylibmc==

– all the available versions will be printed without actually downloading or installing any additional packages.

For pip < 9.0 use:

pip install pylibmc==blork

where blork can be any string that is not a valid version number.

<ng-container> vs <template>

The documentation (https://angular.io/guide/template-syntax#!#star-template) gives the following example. Say we have template code like this:

<hero-detail *ngIf="currentHero" [hero]="currentHero"></hero-detail>

Before it will be rendered, it will be "de-sugared". That is, the asterix notation will be transcribed to the notation:

<template [ngIf]="currentHero">
  <hero-detail [hero]="currentHero"></hero-detail>
</template>

If 'currentHero' is truthy this will be rendered as

<hero-detail> [...] </hero-detail>

But what if you want an conditional output like this:

<h1>Title</h1><br>
<p>text</p>

.. and you don't want the output be wrapped in a container.

You could write the de-sugared version directly like so:

<template [ngIf]="showContent">
  <h1>Title</h1>
  <p>text</p><br>
</template>

And this will work fine. However, now we need ngIf to have brackets [] instead of an asterix *, and this is confusing (https://github.com/angular/angular.io/issues/2303)

For that reason a different notation was created, like so:

<ng-container *ngIf="showContent"><br>
  <h1>Title</h1><br>
  <p>text</p><br>
</ng-container>

Both versions will produce the same results (only the h1 and p tag will be rendered). The second one is preferred because you can use *ngIf like always.

Java equivalent to JavaScript's encodeURIComponent that produces identical output?

Looking at the implementation differences, I see that:

MDC on encodeURIComponent():

  • literal characters (regex representation): [-a-zA-Z0-9._*~'()!]

Java 1.5.0 documentation on URLEncoder:

  • literal characters (regex representation): [-a-zA-Z0-9._*]
  • the space character " " is converted into a plus sign "+".

So basically, to get the desired result, use URLEncoder.encode(s, "UTF-8") and then do some post-processing:

  • replace all occurrences of "+" with "%20"
  • replace all occurrences of "%xx" representing any of [~'()!] back to their literal counter-parts

Finish all previous activities

When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your application starts, clear all the other activities, then have the last remaining activity finish. Have the following code run when the user presses the exit button. In my case, LoginActivity is the first activity in my program to run.

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

The above code clears all the activities except for LoginActivity. Then put the following code inside the LoginActivity's onCreate(...), to listen for when LoginActivity is recreated and the 'EXIT' signal was passed:

if (getIntent().getBooleanExtra("EXIT", false)) {
    finish();  
}

Why is making an exit button in Android so hard?

Android tries hard to discourage you from having an "exit" button in your application, because they want the user to never care about whether or not the programs they use are running in the background or not.

The Android OS developers want your program to be able to survive an unexpected shutdown and power off of the phone, and when the user restarts the program, they pick up right where they left off. So the user can receive a phone call while they use your application, and open maps which requires your application to be freed for more resources.

When the user resumes your application, they pick up right where they left off with no interruption. This exit button is usurping power from the activity manager, potentially causing problems with the automatically managed android program life cycle.

force client disconnect from server with socket.io and nodejs

You can do socket = undefined in erase which socket you have connected. So when want to connected do socket(url)

So it will look like this

const socketClient = require('socket.io-client');

let socket;

// Connect to server
socket = socketClient(url)

// When want to disconnect
socket = undefined;

MySQL search and replace some text in a field

And if you want to search and replace based on the value of another field you could do a CONCAT:

update table_name set `field_name` = replace(`field_name`,'YOUR_OLD_STRING',CONCAT('NEW_STRING',`OTHER_FIELD_VALUE`,'AFTER_IF_NEEDED'));

Just to have this one here so that others will find it at once.

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

it sometimes occurs when we use a custom adapter in any activity of fragment . and we return null object i.e null view so the activity gets confused which view to load , so that is why this exception occurs

shows the position where to change the view

How do I make a column unique and index it in a Ruby on Rails migration?

The short answer for old versions of Rails (see other answers for Rails 4+):

add_index :table_name, :column_name, unique: true

To index multiple columns together, you pass an array of column names instead of a single column name,

add_index :table_name, [:column_name_a, :column_name_b], unique: true

If you get "index name... is too long", you can add name: "whatever" to the add_index method to make the name shorter.

For fine-grained control, there's a "execute" method that executes straight SQL.

That's it!

If you are doing this as a replacement for regular old model validations, check to see how it works. The error reporting to the user will likely not be as nice without model-level validations. You can always do both.

click() event is calling twice in jquery

My simple answer was to turn the click bind into a function and call that from the onclick of the element - worked a treat! whereas none of the above did

One line ftp server in python

The simpler solution will be to user pyftpd library. This library allows you to spin Python FTP server in one line. It doesn’t come installed by default though, but we can install it using simple apt command

apt-get install python-pyftpdlib

now from the directory you want to serve just run the pythod module

python -m pyftpdlib -p 21 

Is it possible to create static classes in PHP (like in C#)?

You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct() you'll get an error).

Therefore you'd have to create an initialize() function and call it in each method:

<?php

class Hello
{
    private static $greeting = 'Hello';
    private static $initialized = false;

    private static function initialize()
    {
        if (self::$initialized)
            return;

        self::$greeting .= ' There!';
        self::$initialized = true;
    }

    public static function greet()
    {
        self::initialize();
        echo self::$greeting;
    }
}

Hello::greet(); // Hello There!


?>

How to 'bulk update' with Django?

Consider using django-bulk-update found here on GitHub.

Install: pip install django-bulk-update

Implement: (code taken directly from projects ReadMe file)

from bulk_update.helper import bulk_update

random_names = ['Walter', 'The Dude', 'Donny', 'Jesus']
people = Person.objects.all()

for person in people:
    r = random.randrange(4)
    person.name = random_names[r]

bulk_update(people)  # updates all columns using the default db

Update: As Marc points out in the comments this is not suitable for updating thousands of rows at once. Though it is suitable for smaller batches 10's to 100's. The size of the batch that is right for you depends on your CPU and query complexity. This tool is more like a wheel barrow than a dump truck.

How to get the Enum Index value in C#

Firstly, there could be two values that you're referring to:

Underlying Value

If you are asking about the underlying value, which could be any of these types: byte, sbyte, short, ushort, int, uint, long or ulong

Then you can simply cast it to it's underlying type. Assuming it's an int, you can do it like this:

int eValue = (int)enumValue;

However, also be aware of each items default value (first item is 0, second is 1 and so on) and the fact that each item could have been assigned a new value, which may not necessarily be in any order particular order! (Credit to @JohnStock for the poke to clarify).

This example assigns each a new value, and show the value returned:

public enum MyEnum
{
    MyValue1 = 34,
    MyValue2 = 27
}

(int)MyEnum.MyValue2 == 27; // True

Index Value

The above is generally the most commonly required value, and is what your question detail suggests you need, however each value also has an index value (which you refer to in the title). If you require this then please see other answers below for details.

What is Shelving in TFS?

I come across this all the time, so supplemental information regarding branches:

If you're working with multiple branches, shelvesets are tied to the specific branch in which you created them. So, if you let a changeset rust on the shelf for too long and have to unshelve to a different branch, then you have to do that with the July release of the power tools.

tfpt unshelve /migrate

Testing the type of a DOM element in JavaScript

Perhaps you'll have to check the nodetype too:

if(element.nodeType == 1){//element of type html-object/tag
  if(element.tagName=="a"){
    //this is an a-element
  }
  if(element.tagName=="div"){
    //this is a div-element
  }
}

Edit: Corrected the nodeType-value

Fixing npm path in Windows 8 and 10

Try this one dude if you're using windows:

1.) Search environment variables at your start menu's search box.
2.) Click it then go to Environment Variables...
3.) Click PATH, click Edit
4.) Click New and try to copy and paste this: C:\Program Files\nodejs\node_modules\npm\bin

If you got an error. Do the number 4.) Click New, then browse the bin folder

  • You may also Visit this link for more info.

What is the maximum length of a Push Notification alert text?

Here're some screenshots (banner, alert, & notification center)

AlertBannerNotification Center

Regex to get the words after matching string

You're almost there. Use the following regex (with multi-line option enabled)

\bObject Name:\s+(.*)$

The complete match would be

Object Name:   D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log

while the captured group one would contain

D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log

If you want to capture the file path directly use

(?m)(?<=\bObject Name:).*$

jQuery: Handle fallback for failed AJAX Request

Yes, it's built in to jQuery. See the docs at jquery documentation.

ajaxError may be what you want.

What is the use of a private static variable in Java?

If you use private static variables in your class, Static Inner classes in your class can reach your variables. This is perfectly good for context security.

Copying an array of objects into another array in javascript

If you want to keep reference:

Array.prototype.push.apply(destinationArray, sourceArray);

Can iterators be reset in Python?

No. Python's iterator protocol is very simple, and only provides one single method (.next() or __next__()), and no method to reset an iterator in general.

The common pattern is to instead create a new iterator using the same procedure again.

If you want to "save off" an iterator so that you can go back to its beginning, you may also fork the iterator by using itertools.tee

"End of script output before headers" error in Apache

In my case I had a similar problem but with c ++ this in windows 10, the problem was solved by adding the environment variables (path) windows, the folder of the c ++ libraries, in my case I used the codeblock libraries:

C:\codeblocks\MinGW\bin

How to convert milliseconds to "hh:mm:ss" format?

Going by Bohemian's answer we need need not use TimeUnit to find a known value. Much more optimal code would be

String hms = String.format("%02d:%02d:%02d", millisLeft/(3600*1000),
                    millisLeft/(60*1000) % 60,
                    millisLeft/1000 % 60);

Hope it helps

C# : Out of Memory exception

My Development Team resolved this situation:

We added the following Post-Build script into the .exe project and compiled again, setting the target to x86 and increasing by 1.5 gb and also x64 Platform target increasing memory using 3.2 gb. Our application is 32 bit.

Related URLs:

Script:

if exist "$(DevEnvDir)..\tools\vsvars32.bat" (
    call "$(DevEnvDir)..\tools\vsvars32.bat"
    editbin /largeaddressaware "$(TargetPath)"
)

HTML not loading CSS file

Not sure this is valuable, but I will leave this here for others. Making sure that "Anonymous Authentication" was set to "Enabled" loaded my CSS file correctly.

To do that in Visual Studio 2019:

  1. Select your solution's name, right click, and hit "properties"
  2. Navigate to the "Properties" frame, typically in the bottom right corner
  3. Ensure that "Anonymous authentication" is set to "Enabled" as shown below

enter image description here

How may I reference the script tag that loaded the currently-executing script?

I was inserting script tags dynamically with this usual alternative to eval and simply set a global property currentComponentScript right before adding to the DOM.

  const old = el.querySelector("script")[0];
  const replacement = document.createElement("script");
  replacement.setAttribute("type", "module");
  replacement.appendChild(document.createTextNode(old.innerHTML));
  window.currentComponentScript = replacement;
  old.replaceWith(replacement);

Doesn't work in a loop though. The DOM doesn't run the scripts until the next macrotask so a batch of them will only see the last value set. You'd have to setTimeout the whole paragraph, and then setTimeout the next one after the previous finishes. I.e. chain the setTimeouts, not just call setTimeout multiple times in a row from a loop.

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

Setting core.filemode to false does work, but make sure the settings in ~/.gitconfig aren't being overridden by those in .git/config.

Firebase Storage How to store and Retrieve images

Yes, you can store and view images in Firebase. You can use a filepicker to get the image file. Then you can host the image however you want, I prefer Amazon s3. Once the image is hosted you can display the image using the URL generated for the image.

Hope this helps.

How to change the font on the TextView?

I finally got a very easy solution to this.

  1. use these Support libraries in app level gradle,

    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:support-v4:26.0.2'
    
  2. then create a directory named "font" inside the res folder

  3. put fonts(ttf) files in that font directory, keep in mind the naming conventions [e.g.name should not contain any special character, any uppercase character and any space or tab]
  4. After that, reference that font from xml like this

            <Button
            android:id="@+id/btn_choose_employee"
            android:layout_width="140dp"
            android:layout_height="40dp"
            android:layout_centerInParent="true"
            android:background="@drawable/rounded_red_btn"
            android:onClick="btnEmployeeClickedAction"
            android:text="@string/searching_jobs"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:fontFamily="@font/times_new_roman_test"
            />
    

In this example, times_new_roman_test is a font ttf file from that font directory

Concatenating two std::vectors

vector<int> v1 = {1, 2, 3, 4, 5};
vector<int> v2 = {11, 12, 13, 14, 15};
copy(v2.begin(), v2.end(), back_inserter(v1));

What's the @ in front of a string in C#?

Since you explicitly asked for VB as well, let me just add that this verbatim string syntax doesn't exist in VB, only in C#. Rather, all strings are verbatim in VB (except for the fact that they cannot contain line breaks, unlike C# verbatim strings):

Dim path = "C:\My\Path"
Dim message = "She said, ""Hello, beautiful world."""

Escape sequences don't exist in VB (except for the doubling of the quote character, like in C# verbatim strings) which makes a few things more complicated. For example, to write the following code in VB you need to use concatenation (or any of the other ways to construct a string)

string x = "Foo\nbar";

In VB this would be written as follows:

Dim x = "Foo" & Environment.NewLine & "bar"

(& is the VB string concatenation operator. + could equally be used.)

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

The first answer is definitely the correct answer and is what I based this lambda version off of, which is much shorter in syntax. Since Runnable has only 1 override method "run()", we can use a lambda:

this.m_someBoolFlag = false;
new android.os.Handler().postDelayed(() -> this.m_someBoolFlag = true, 300);

Maximum packet size for a TCP connection

If you are with Linux machines, "ifconfig eth0 mtu 9000 up" is the command to set the MTU for an interface. However, I have to say, big MTU has some downsides if the network transmission is not so stable, and it may use more kernel space memories.

Postgres: SQL to list table foreign keys

short but sweet upvote if it works for you.

select  * from information_schema.key_column_usage where constraint_catalog=current_catalog and table_name='your_table_name' and position_in_unique_constraint notnull;

What does ${} (dollar sign and curly braces) mean in a string in Javascript?

You can also perform Implicit Type Conversions with template literals. Example:

let fruits = ["mango","orange","pineapple","papaya"];

console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya

Checking the equality of two slices

You need to loop over each of the elements in the slice and test. Equality for slices is not defined. However, there is a bytes.Equal function if you are comparing values of type []byte.

func testEq(a, b []Type) bool {

    // If one is nil, the other must also be nil.
    if (a == nil) != (b == nil) { 
        return false; 
    }

    if len(a) != len(b) {
        return false
    }

    for i := range a {
        if a[i] != b[i] {
            return false
        }
    }

    return true
}

Charts for Android

SciChart for Android is a relative newcomer, but brings extremely fast high performance real-time charting to the Android platform.

SciChart is a commercial control but available under royalty free distribution / per developer licensing. There is also free licensing available for educational use with some conditions.

Some useful links can be found below:

enter image description here

Disclosure: I am the tech lead on the SciChart project!

Change primary key column in SQL Server

Necromancing.
It looks you have just as good a schema to work with as me... Here is how to do it correctly:

In this example, the table name is dbo.T_SYS_Language_Forms, and the column name is LANG_UID

-- First, chech if the table exists...
IF 0 < (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE = 'BASE TABLE'
    AND TABLE_SCHEMA = 'dbo'
    AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
    -- Check for NULL values in the primary-key column
    IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
    BEGIN
        ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL 

        -- No, don't drop, FK references might already exist...
        -- Drop PK if exists 
        -- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name 
        --DECLARE @pkDropCommand nvarchar(1000) 
        --SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
        --WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
        --AND TABLE_SCHEMA = 'dbo' 
        --AND TABLE_NAME = 'T_SYS_Language_Forms' 
        ----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
        --))
        ---- PRINT @pkDropCommand 
        --EXECUTE(@pkDropCommand) 

        -- Instead do
        -- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';


        -- Check if they keys are unique (it is very possible they might not be) 
        IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
        BEGIN

            -- If no Primary key for this table
            IF 0 =  
            (
                SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
                AND TABLE_SCHEMA = 'dbo' 
                AND TABLE_NAME = 'T_SYS_Language_Forms' 
                -- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
            )
                ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
            ;

            -- Adding foreign key
            IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms') 
                ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID); 
        END -- End uniqueness check
        ELSE
            PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...' 
    END -- End NULL check
    ELSE
        PRINT 'FSCK, need to figure out how to update NULL value(s)...' 
END 

Git: How to commit a manually deleted file?

It says right there in the output of git status:

#   (use "git add/rm <file>..." to update what will be committed)

so just do:

git rm <filename>

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

NodeJS, at one point (I think it was v0.6.x) had ArrayBuffer support. I created a small library for base64 encoding and decoding here, but since updating to v0.7, the tests (on NodeJS) fail. I'm thinking of creating something that normalizes this, but till then, I suppose Node's native Buffer should be used.

How to add click event to a iframe with JQuery

You can solve it very easily, just wrap that iframe in wrapper, and track clicks on it.

Like this:

<div id="iframe_id_wrapper"> <iframe id="iframe_id" src="http://something.com"></iframe> </div>

And disable pointer events on iframe itself.

#iframe_id { pointer-events: none; }

After this changes your code will work like expected.

$('#iframe_id_wrapper').click(function() { //run function that records clicks });

How to detect a USB drive has been plugged in?

Here is a code that works for me, which is a part from the website above combined with my early trials: http://www.codeproject.com/KB/system/DriveDetector.aspx

This basically makes your form listen to windows messages, filters for usb drives and (cd-dvds), grabs the lparam structure of the message and extracts the drive letter.

protected override void WndProc(ref Message m)
    {

        if (m.Msg == WM_DEVICECHANGE)
        {
            DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
            if ((m.WParam.ToInt32() == DBT_DEVICEARRIVAL) &&  (vol.dbcv_devicetype == DBT_DEVTYPVOLUME) )
            {
                MessageBox.Show(DriveMaskToLetter(vol.dbcv_unitmask).ToString());
            }
            if ((m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
            {
                MessageBox.Show("usb out");
            }
        }
        base.WndProc(ref m);
    }

    [StructLayout(LayoutKind.Sequential)] //Same layout in mem
    public struct DEV_BROADCAST_VOLUME
    {
        public int dbcv_size;
        public int dbcv_devicetype;
        public int dbcv_reserved;
        public int dbcv_unitmask;
    }

    private static char DriveMaskToLetter(int mask)
    {
        char letter;
        string drives = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //1 = A, 2 = B, 3 = C
        int cnt = 0;
        int pom = mask / 2;
        while (pom != 0)    // while there is any bit set in the mask shift it right        
        {        
            pom = pom / 2;
            cnt++;
        }
        if (cnt < drives.Length)
            letter = drives[cnt];
        else
            letter = '?';
        return letter;
    }

Do not forget to add this:

using System.Runtime.InteropServices;

and the following constants:

    const int WM_DEVICECHANGE = 0x0219; //see msdn site
    const int DBT_DEVICEARRIVAL = 0x8000;
    const int DBT_DEVICEREMOVALCOMPLETE = 0x8004;
    const int DBT_DEVTYPVOLUME = 0x00000002;  

XAMPP Object not found error

Enter the command in Terminal:

sudo gedit /opt/lampp/etc/httpd.conf

and comment the line as below.

Virtual hosts

Include etc/extra/httpd-vhosts.conf**

now Restart the Lampp with

sudo gedit /opt/lampp/lamp restart

go to your browser and refresh the page it works.

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

How to setup Main class in manifest file in jar produced by NetBeans project

In 7.3 just enable Properties/Build/Package/Copy Dependent Libraries and main class will be added to manifest when building depending on selected target.

remove empty lines from text file with PowerShell

This piece of code from Randy Skretka is working fine for me, but I had the problem, that I still had a newline at the end of the file.

(gc file.txt) | ? {$_.trim() -ne "" } | set-content file.txt

So I added finally this:

$content = [System.IO.File]::ReadAllText("file.txt")
$content = $content.Trim()
[System.IO.File]::WriteAllText("file.txt", $content)

How to get a variable name as a string in PHP?

You might consider changing your approach and using a variable variable name?

$var_name = "FooBar";
$$var_name = "a string";

then you could just

print($var_name);

to get

FooBar

Here's the link to the PHP manual on Variable variables

Assign a synthesizable initial value to a reg in Verilog

You should use what your FPGA documentation recommends. There is no portable way to initialize register values other than using a reset net. This has a hardware cost associated with it on most synthesis targets.

DateTime.Compare how to check if a date is less than 30 days old?

Compare is unnecessary, Days / TotalDays are unnecessary.

All you need is

if (expireDate < DateTime.Now) {
    // has expired
} else {
    // not expired
}

note this will work if you decide to use minutes or months or even years as your expiry criteria.

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

What is interrupt ?

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.

How is it implemented ?

The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static Thread.isInterrupted, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.

Quote from Thread.interrupt() API:

Interrupts this thread. First the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.

If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

If none of the previous conditions hold then this thread's interrupt status will be set.

Check this out for complete understanding about same :

http://download.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

How to solve error message: "Failed to map the path '/'."

The following works for me: 1. Right click on "Default web site" 2. Choose Advance settings 3. Setup Physical Path to C:\inetpub\wwwroot 4. Click OK. 5. Browse the Default web site. --> It works.

Binding an Image in WPF MVVM

Displaying an Image in WPF is much easier than that. Try this:

<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left" 
    Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom" 
    Grid.Row="8" Width="200"  Grid.ColumnSpan="2" />

And the property can just be a string:

public string DisplayedImage 
{
    get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}

Although you really should add your images to a folder named Images in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:

public string DisplayedImage 
{
    get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}

UPDATE >>>

As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.


UPDATE 2 >>>

If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image control. Using the string property that I suggested, try this:

<StackPanel>
    <Image Source="{Binding DisplayedImagePath}" />
    <TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>

If you can't see the file path in the TextBlock, then you probably haven't set your DataContext to the instance of your view model. If you can see the text, then the problem is with your file path.


UPDATE 3 >>>

In .NET 4, the above Image.Source values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack path like this:

<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">

For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.

How to get current time in python and break up into year, month, day, hour, minute?

The datetime module is your friend:

import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
# 2015 5 6 8 53 40

You don't need separate variables, the attributes on the returned datetime object have all you need.

What I can do to resolve "1 commit behind master"?

If the message is "n commits behind master."

You need to rebase your dev branch with master. You got the above message because after checking out dev branch from master, the master branch got new commit and has moved ahead. You need to get those new commits to your dev branch.

Steps:

git checkout master
git pull        #this will update your local master
git checkout yourDevBranch
git rebase master

there can be some merge conflicts which you have to resolve.

Remove multiple objects with rm()

An other solution rm(list=ls(pattern="temp")), remove all objects matching the pattern.

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

Use the backslash before db on the header and you can use it then typically as you wrote it before.

Here is the example:

Use \DB;

Then inside your controller class you can use as you did before, like that ie :

$item = DB::table('items')->get();

WCF ServiceHost access rights

Open a command prompt as the administrator and you write below command to add your URL:

netsh http add urlacl url=http://+:8000/YourServiceLibrary/YourService user=Everyone

How to redirect to another page in node.js

Ok, I'll try to help you using one my examples. First of all, you need to know I am using express for my application directory structure and for creating files like app.js in an automatically way. My login.html looks like:

...
<div class="form">
<h2>Login information</h2>
<form action="/login" method = "post">
  <input type="text" placeholder="E-Mail" name="email" required/>
  <input type="password" placeholder="Password" name="password" required/>
  <button>Login</button>
</form>

The important thing here is action="/login". This is the path I use in my index.js (for navigating between the views) which look like this:

app.post('/login', passport.authenticate('login', {
    successRedirect : '/home', 
    failureRedirect : '/login', 
    failureFlash : true
}));

app.get('/home', function(request, response) {
        response.render('pages/home');
});

This allows me to redirect to another page after a succesful login. There is a helpful tutorial you could check out for redirecting between pages:

http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/

To read a statement like <%= user.attributes.name %> let's have a look at a simple profile.html which has the following structure:

<div id = "profile">
<h3>Profilinformationen</h3>
    <form>
        <fieldset>
            <label id = "usernameLabel">Username:</label>
            <input type = "text" id="usernameText" value = "<%= user.user.username %>" />
            <br>
        </fieldset>
    </form>

To get the the attributes of the user variable, you have to initialize a user variable in your routing.js (called index.js in my case). This looks like

app.get('/profile', auth, function(request, response) {
    response.render('pages/profile', {
        user : request.user
    });
});

I am using mongoose for my object model:

var mongoose = require('mongoose');
var bcrypt   = require('bcrypt-nodejs');
var role     = require('./role');

var userSchema = mongoose.Schema({
    user             : {
        username     : String,
        email        : String,
        password     : String
    }
});

Ask me anytime for further questions... Best regards, Nazar

How to create a WPF Window without a border that can be resized via a grip only?

If you set the AllowsTransparency property on the Window (even without setting any transparency values) the border disappears and you can only resize via the grip.

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="640" Height="480" 
    WindowStyle="None"
    AllowsTransparency="True"
    ResizeMode="CanResizeWithGrip">

    <!-- Content -->

</Window>

Result looks like:

What is `git push origin master`? Help with git's refs, heads and remotes

Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.

Commands

Make sure you're on your master branch with

1)git checkout master

then create the new branch with

2)git branch --track my_test origin/my_test

and check it out with

3)git checkout my_test.

You can then push and pull without specifying which local and remote.

However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:

git pull -u my_test origin/my_test
git push -u my_test origin/my_test

Config

The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.

[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
    remote = origin
    merge = refs/heads/my_test

This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.

You can find something very similar to this in the config after running the commands above.

Some useful resources:

Hive Alter table change Column Name

In the comments @libjack mentioned a point which is really important. I would like to illustrate more into it. First, we can check what are the columns of our table by describe <table_name>; command. enter image description here

there is a double-column called _c1 and such columns are created by the hive itself when we moving data from one table to another. To address these columns we need to write it inside backticks

`_c1`

Finally, the ALTER command will be,

ALTER TABLE <table_namr> CHANGE `<system_genarated_column_name>` <new_column_name> <data_type>;

Selenium and xPath - locating a link by containing text

@FindBy(xpath = "//span[@class='y2' and contains(text(), 'Your Text')] ") 
private WebElementFacade emailLinkToVerifyAccount;

This approach will work for you, hopefully.

Event listener for when element becomes visible?

If you just want to run some code when an element becomes visible in the viewport:

function onVisible(element, callback) {
  new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if(entry.intersectionRatio > 0) {
        callback(element);
        observer.disconnect();
      }
    });
  }).observe(element);
}

When the element has become visible the intersection observer calls callback and then destroys itself with .disconnect().

Use it like this:

onVisible(document.querySelector("#myElement"), () => console.log("it's visible"));

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

In my case I parsed an S3 url into its components.

For example:

Url:    s3://bucket-name/path/to/file

Was parsed into:

Bucket: bucket-name
Path:   /path/to/file

Having the path part containing a leading '/' failed the request.

Difference between array_push() and $array[] =

You should always use $array[] if possible because as the box states there is no overhead for the function call. Thus it is a bit faster than the function call.

What is the difference between java and core java?

It's not an official term. I guess it means knowledge of the Java language itself and the most important parts of the standard API (java.lang, java.io, java.utils packages, basically), as opposed to the multitude of specialzed APIs and frameworks (J2EE, JPA, JNDI, JSTL, ...) that are often required for Java jobs.

How can I change the font size using seaborn FacetGrid?

For the legend, you can use this

plt.setp(g._legend.get_title(), fontsize=20)

Where g is your facetgrid object returned after you call the function making it.

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.

Regular expressions in C: examples?

Regular expressions actually aren't part of ANSI C. It sounds like you might be talking about the POSIX regular expression library, which comes with most (all?) *nixes. Here's an example of using POSIX regexes in C (based on this):

#include <regex.h>        
regex_t regex;
int reti;
char msgbuf[100];

/* Compile regular expression */
reti = regcomp(&regex, "^a[[:alnum:]]", 0);
if (reti) {
    fprintf(stderr, "Could not compile regex\n");
    exit(1);
}

/* Execute regular expression */
reti = regexec(&regex, "abc", 0, NULL, 0);
if (!reti) {
    puts("Match");
}
else if (reti == REG_NOMATCH) {
    puts("No match");
}
else {
    regerror(reti, &regex, msgbuf, sizeof(msgbuf));
    fprintf(stderr, "Regex match failed: %s\n", msgbuf);
    exit(1);
}

/* Free memory allocated to the pattern buffer by regcomp() */
regfree(&regex);

Alternatively, you may want to check out PCRE, a library for Perl-compatible regular expressions in C. The Perl syntax is pretty much that same syntax used in Java, Python, and a number of other languages. The POSIX syntax is the syntax used by grep, sed, vi, etc.

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

I have also faced this problem but i had restart Hadoop and use command hadoop dfsadmin -safemode leave

now start hive it will work i think

Is "&#160;" a replacement of "&nbsp;"?

  • &nbsp; is the character entity reference (meant to be easily parseable by humans).
  • &#160; is the numeric entity reference (meant to be easily parseable by machines).

They are the same except for the fact that the latter does not need another lookup table to find its actual value. The lookup table is called a DTD, by the way.

You can read more about character entity references in the offical W3C documents.

Chrome Dev Tools - Modify javascript and reload

Yes, just open the "Source" Tab in the dev-tools and navigate to the script you want to change . Make your adjustments directly in the dev tools window and then hit ctrl+s to save the script - know the new js will be used until you refresh the whole page.

Remove json element

All the answers are great, and it will do what you ask it too, but I believe the best way to delete this, and the best way for the garbage collector (if you are running node.js) is like this:

var json = { <your_imported_json_here> };
var key = "somekey";
json[key] = null;
delete json[key];

This way the garbage collector for node.js will know that json['somekey'] is no longer required, and will delete it.

How can I capture packets in Android?

It's probably worth mentioning that for http/https some people proxy their browser traffic through Burp/ZAP or another intercepting "attack proxy". A thread that covers options for this on Android devices can be found here: https://android.stackexchange.com/questions/32366/which-browser-does-support-proxies

How to check what user php is running as?

<?php echo exec('whoami'); ?>

Best practice to look up Java Enum

If you want the lookup to be case insensitive you can loop through the values making it a little more friendly:

 public enum MyEnum {
   A, B, C, D;

      public static MyEnum lookup(String id) {
        boolean found = false;
        for(MyEnum enum: values()){
           if(enum.toString().equalsIgnoreCase(id)) found = true;
        }  
        if(!found) throw new RuntimeException("Invalid value for my enum: " +id);
       }
}

What is meant by Ems? (Android TextView)

It is the width of the letter M in a given English font size.
So 2em is twice the width of the letter M in this given font.
For a non-English font, it is the width of the widest letter in that font. This width size in pixels is different than the width size of the M in the English font but it is still 1em.
So if I use a text with 12sp in an English font, 1em is relative to this 12sp English font; using an Italian font with 12sp gives 1em that is different in pixels width than the English one.

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

PHP remove special character from string

Your dot is matching all characters. Escape it (and the other special characters), like this:

preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String);

How to change the default background color white to something else in twitter bootstrap

Bootstrap 4 provides standard methods for this, fully described here: https://getbootstrap.com/docs/4.3/getting-started/theming

Eg. you can override defaults simply by setting variables in the SASS file, where you import bootstrap. An example from the docs (which also answers the question):

// Your variable overrides
$body-bg: #000;
$body-color: #111;

// Bootstrap and its default variables
@import "../node_modules/bootstrap/scss/bootstrap";

What .NET collection provides the fastest search

If you're using .Net 3.5, you can make cleaner code using:

foreach (Record item in LookupCollection.Intersect(LargeCollection))
{
  //dostuff
}

I don't have .Net 3.5 here and so this is untested. It relies on an extension method. Not that LookupCollection.Intersect(LargeCollection) is probably not the same as LargeCollection.Intersect(LookupCollection) ... the latter is probably much slower.

This assumes LookupCollection is a HashSet

Biggest differences of Thrift vs Protocol Buffers?

Protocol Buffers seems to have a more compact representation, but that's only an impression I get from reading the Thrift whitepaper. In their own words:

We decided against some extreme storage optimizations (i.e. packing small integers into ASCII or using a 7-bit continuation format) for the sake of simplicity and clarity in the code. These alterations can easily be made if and when we encounter a performance-critical use case that demands them.

Also, it may just be my impression, but Protocol Buffers seems to have some thicker abstractions around struct versioning. Thrift does have some versioning support, but it takes a bit of effort to make it happen.

How to check if user input is not an int value

Simply throw Exception if input is invalid

Scanner sc=new Scanner(System.in);
try
{
  System.out.println("Please input an integer");
  //nextInt will throw InputMismatchException
  //if the next token does not match the Integer
  //regular expression, or is out of range
  int usrInput=sc.nextInt();
}
catch(InputMismatchException exception)
{
  //Print "This is not an integer"
  //when user put other than integer
  System.out.println("This is not an integer");
}

Multi-dimensional arraylist or list in C#?

Not exactly. But you can create a list of lists:

var ll = new List<List<int>>();
for(int i = 0; i < 10; ++i) {
    var l = new List<int>();
    ll.Add(l);
}

Can a div have multiple classes (Twitter Bootstrap)

A div can can hold more than one classes either using bootstrap or not

<div class="active dropdown-toggle my-class">Multiple Classes</div>
For applying multiple classes just separate the classes by space.

Take a look at this links you will find many examples
http://getbootstrap.com/css/
http://css-tricks.com/un-bloat-css-by-using-multiple-classes/

Python memory usage of numpy arrays

In python notebooks I often want to filter out 'dangling' numpy.ndarray's, in particular the ones that are stored in _1, _2, etc that were never really meant to stay alive.

I use this code to get a listing of all of them and their size.

Not sure if locals() or globals() is better here.

import sys
import numpy
from humanize import naturalsize

for size, name in sorted(
    (value.nbytes, name)
    for name, value in locals().items()
    if isinstance(value, numpy.ndarray)):
  print("{:>30}: {:>8}".format(name, naturalsize(size)))

DNS caching in linux

You have here available an example of DNS Caching in Debian using dnsmasq.

Configuration summary:

/etc/default/dnsmasq

# Ensure you add this line
DNSMASQ_OPTS="-r /etc/resolv.dnsmasq"

/etc/resolv.dnsmasq

# Your preferred servers
nameserver 1.1.1.1
nameserver 8.8.8.8
nameserver 2001:4860:4860::8888

/etc/resolv.conf

nameserver 127.0.0.1

Then just restart dnsmasq.

Benchmark test using DNS 1.1.1.1:

for i in {1..100}; do time dig slashdot.org @1.1.1.1; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'

Benchmark test using you local cached DNS:

for i in {1..100}; do time dig slashdot.org; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'

Show div when radio button selected

I would handle it like so:

$(document).ready(function() {
   $('input[type="radio"]').click(function() {
       if($(this).attr('id') == 'watch-me') {
            $('#show-me').show();           
       }

       else {
            $('#show-me').hide();   
       }
   });
});

What is the Python equivalent of Matlab's tic and toc functions?

pip install easy-tictoc

In the code:

from tictoc import tic, toc

tic()

#Some code

toc()

Disclaimer: I'm the author of this library.

Is it possible to put a ConstraintLayout inside a ScrollView?

There was a bug with ConstraintLayout inside ScrollViews and it has been fixed. google has fixed the bug in Android Studio 2.2 Preview 2 (constraintlayout 1.0.0-alpha2).

Check this link for new update (Preview 2): works properly inside ScrollView and RecycleView

Solution 1:

The solution was to use android:fillViewport="true" on the ScrollView

Solution 2:

Use NestedScrollView instead of ScrollView with android:fillViewport="true"

Edit - 09/16/20:

Currently, it is more usual to use the ScrollView with the ConstraintLayout height set to wrap_content, it works very well, don't forget the fillViewPort and that both Scroll and Nested support only one direct child.

Using Pip to install packages to Anaconda Environment

If you didn't add pip when creating conda environment

conda create -n env_name pip

and also didn't install pip inside the environment

source activate env_name
conda install pip

then the only pip you got is the system pip, which will install packages globally.

Bus as you can see in this issue, even if you did either of the procedure mentioned above, the behavior of pip inside conda environment is still kind of undefined.

To ensure using the pip installed inside conda environment without having to type the lengthy /home/username/anaconda/envs/env_name/bin/pip, I wrote a shell function:

# Using pip to install packages inside conda environments.
cpip() {
    ERROR_MSG="Not in a conda environment."
    ERROR_MSG="$ERROR_MSG\nUse \`source activate ENV\`"
    ERROR_MSG="$ERROR_MSG to enter a conda environment."

    [ -z "$CONDA_DEFAULT_ENV" ] && echo "$ERROR_MSG" && return 1

    ERROR_MSG='Pip not installed in current conda environment.'
    ERROR_MSG="$ERROR_MSG\nUse \`conda install pip\`"
    ERROR_MSG="$ERROR_MSG to install pip in current conda environment."

    [ -e "$CONDA_PREFIX/bin/pip" ] || (echo "$ERROR_MSG" && return 2)

    PIP="$CONDA_PREFIX/bin/pip"
    "$PIP" "$@"
}

Hope this is helpful to you.

Pass Javascript Array -> PHP

AJAX requests are no different from GET and POST requests initiated through a <form> element. Which means you can use $_GET and $_POST to retrieve the data.

When you're making an AJAX request (jQuery example):

// JavaScript file

elements = [1, 2, 9, 15].join(',')
$.post('/test.php', {elements: elements})

It's (almost) equivalent to posting this form:

<form action="/test.php" method="post">
  <input type="text" name="elements" value="1,2,9,15">
</form>

In both cases, on the server side you can read the data from the $_POST variable:

// test.php file

$elements = $_POST['elements'];
$elements = explode(',', $elements);

For the sake of simplicity I'm joining the elements with comma here. JSON serialization is a more universal solution, though.

Why doesn't height: 100% work to expand divs to the screen height?

if you want, for example, a left column (height 100%) and the content (height auto) you can use absolute :

#left_column {
    float:left;
    position: absolute;
    max-height:100%;
    height:auto !important;
    height: 100%;
    overflow: hidden;

    width : 180px; /* for example */
}

#left_column div {
    height: 2000px;
}

#right_column {
    float:left;
    height:100%;
    margin-left : 180px; /* left column's width */
}

in html :

  <div id="content">
      <div id="left_column">
        my navigation content
        <div></div>
      </div>

      <div id="right_column">
        my content
      </div>
   </div>

how to set value of a input hidden field through javascript?

It seems to work fine in Google Chrome. Which browser are you using? Here the proof http://jsfiddle.net/CN8XL/

Anyhow you can also access to the input value parameter through the document.FormName.checkyear.value. You have to wrap in the input in a <form> tag like with the proper name attribute, like shown below:

<form name="FormName">
    <input type="hidden" name="checkyear" id="checkyear" value="">
</form>

Have you considered using the jQuery Library? Here are the docs for .val() function.

Embedding JavaScript engine into .NET

Anybody just tuning in check out Jurassic as well:

http://jurassic.codeplex.com/

edit: this has moved to github (and seems active at first glance)

https://github.com/paulbartrum/jurassic

How to make circular background using css?

Here is a solution for doing it with a single div element with CSS properties, border-radius does the magic.

CSS:

.circle{
    width:100px;
    height:100px;
    border-radius:50px;
    font-size:20px;
    color:#fff;
    line-height:100px;
    text-align:center;
    background:#000
}

HTML:

<div class="circle">Hello</div>

What is the difference between attribute and property?

<property attribute="attributeValue">proopertyValue</property>

would be one way to look at it.

In C#

[Attribute]
public class Entity
{
    private int Property{get; set;};

When should iteritems() be used instead of items()?

Just as @Wessie noted, dict.iteritems, dict.iterkeys and dict.itervalues (which return an iterator in Python2.x) as well as dict.viewitems, dict.viewkeys and dict.viewvalues (which return view objects in Python2.x) were all removed in Python3.x

And dict.items, dict.keys and dict.values used to return a copy of the dictionary's list in Python2.x now return view objects in Python3.x, but they are still not the same as iterator.

If you want to return an iterator in Python3.x, use iter(dictview) :

$ python3.3

>>> d = {'one':'1', 'two':'2'}
>>> type(d.items())
<class 'dict_items'>
>>>
>>> type(d.keys())
<class 'dict_keys'>
>>>
>>>
>>> ii = iter(d.items())
>>> type(ii)
<class 'dict_itemiterator'>
>>>
>>> ik = iter(d.keys())
>>> type(ik)
<class 'dict_keyiterator'>

Maven with Eclipse Juno

From Eclipse

  • Go to Help
  • Eclipse Marketplace
  • Search for m2e or maven integration for eclipse
  • click on Install against - 'Maven Integration for Eclipse (Juno and newer) 1.4'
  • Restart and Enjoy!!!

Dynamically allocating an array of objects

  1. Use array or common container for objects only if they have default and copy constructors.

  2. Store pointers otherwise (or smart pointers, but may meet some issues in this case).

PS: Always define own default and copy constructors otherwise auto-generated will be used

ASP.NET Web Application Message Box

Why should not use jquery popup for this purpose.I use bpopup for this purpose.See more about this.
http://dinbror.dk/bpopup/

Return multiple fields as a record in PostgreSQL with PL/pgSQL

you can do this using OUT parameter and CROSS JOIN

CREATE OR REPLACE FUNCTION get_object_fields(my_name text, OUT f1 text, OUT f2 text)
AS $$
SELECT t1.name, t2.name
FROM  table1 t1 
CROSS JOIN table2 t2 
WHERE t1.name = my_name AND t2.name = my_name;
$$ LANGUAGE SQL;

then use it as a table:

select get_object_fields( 'Pending') ;
get_object_fields
-------------------
(Pending,code)
(1 row)

or

select * from get_object_fields( 'Pending');
f1    |   f
---------+---------
Pending | code
(1 row)

or

select (get_object_fields( 'Pending')).f1;
f1
---------
Pending
(1 row)

How to print a single backslash?

You need to escape your backslash by preceding it with, yes, another backslash:

print("\\")

And for versions prior to Python 3:

print "\\"

The \ character is called an escape character, which interprets the character following it differently. For example, n by itself is simply a letter, but when you precede it with a backslash, it becomes \n, which is the newline character.

As you can probably guess, \ also needs to be escaped so it doesn't function like an escape character. You have to... escape the escape, essentially.

See the Python 3 documentation for string literals.

Broadcast Receiver within a Service

as your service is already setup, simply add a broadcast receiver in your service:

private final BroadcastReceiver receiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
        //action for sms received
      }
      else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
           //action for phone state changed
      }     
   }
};

in your service's onCreate do this:

IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more

registerReceiver(receiver, filter);

and in your service's onDestroy:

unregisterReceiver(receiver);

and you are good to go to receive broadcast for what ever filters you mention in onCreate. Make sure to add any permission if required. for e.g.

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

Is it possible to iterate through JSONArray?

Not with an iterator.

For org.json.JSONArray, you can do:

for (int i = 0; i < arr.length(); i++) {
  arr.getJSONObject(i);
}

For javax.json.JsonArray, you can do:

for (int i = 0; i < arr.size(); i++) {
  arr.getJsonObject(i);
}

Java program to get the current date without timestamp

  DateFormat dateFormat = new SimpleDateFormat("MMMM dd yyyy");
  java.util.Date date = new java.util.Date();
  System.out.println("Current Date : " + dateFormat.format(date));

Hive External Table Skip First Row

I also struggled with this and found no way to tell hive to skip first row, like there is e.g. in Greenplum. So finally I had to remove it from the files. e.g. "cat File.csv | grep -v RecordId > File_no_header.csv"

How do I generate random number for each row in a TSQL Select?

Try this:

SELECT RAND(convert(varbinary, newid()))*(b-a)+a magic_number 

Where a is the lower number and b is the upper number

What exactly does the "u" do? "git push -u origin master" vs "git push origin master"

The key is "argument-less git-pull". When you do a git pull from a branch, without specifying a source remote or branch, git looks at the branch.<name>.merge setting to know where to pull from. git push -u sets this information for the branch you're pushing.

To see the difference, let's use a new empty branch:

$ git checkout -b test

First, we push without -u:

$ git push origin test
$ git pull
You asked me to pull without telling me which branch you
want to merge with, and 'branch.test.merge' in
your configuration file does not tell me, either. Please
specify which branch you want to use on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details.

If you often merge with the same branch, you may want to
use something like the following in your configuration file:

    [branch "test"]
    remote = <nickname>
    merge = <remote-ref>

    [remote "<nickname>"]
    url = <url>
    fetch = <refspec>

See git-config(1) for details.

Now if we add -u:

$ git push -u origin test
Branch test set up to track remote branch test from origin.
Everything up-to-date
$ git pull
Already up-to-date.

Note that tracking information has been set up so that git pull works as expected without specifying the remote or branch.

Update: Bonus tips:

  • As Mark mentions in a comment, in addition to git pull this setting also affects default behavior of git push. If you get in the habit of using -u to capture the remote branch you intend to track, I recommend setting your push.default config value to upstream.
  • git push -u <remote> HEAD will push the current branch to a branch of the same name on <remote> (and also set up tracking so you can do git push after that).

Find mouse position relative to element

Based on @Patrick Boos solution but fixing potential problem with intermediate scrollbars.

export function getRelativeCoordinates(event: MouseEvent, referenceElement: HTMLElement) {
  const position = {
    x: event.pageX,
    y: event.pageY,
  };

  const offset = {
    left: referenceElement.offsetLeft,
    top: referenceElement.offsetTop,
  };

  let reference = referenceElement.offsetParent as HTMLElement;

  while (reference) {
    offset.left += reference.offsetLeft;
    offset.top += reference.offsetTop;
    reference = reference.offsetParent as HTMLElement;
  }

  const scrolls = {
    left: 0,
    top: 0,
  };

  reference = event.target as HTMLElement;
  while (reference) {
    scrolls.left += reference.scrollLeft;
    scrolls.top += reference.scrollTop;
    reference = reference.parentElement as HTMLElement;
  }

  return {
    x: position.x + scrolls.left - offset.left,
    y: position.y + scrolls.top - offset.top,
  };
}

Best/Most Comprehensive API for Stocks/Financial Data

I usually find that ProgrammableWeb is a good place to go when looking for APIs.

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

As suggested by Mark Ransom, I found the right encoding for that problem. The encoding was "ISO-8859-1", so replacing open("u.item", encoding="utf-8") with open('u.item', encoding = "ISO-8859-1") will solve the problem.

Date Difference in php on days?

I would recommend to use date->diff function, as in example below:

   $dStart = new DateTime('2012-07-26');
   $dEnd  = new DateTime('2012-08-26');
   $dDiff = $dStart->diff($dEnd);
   echo $dDiff->format('%r%a'); // use for point out relation: smaller/greater

see http://www.php.net/manual/en/datetime.diff.php

$this->session->set_flashdata() and then $this->session->flashdata() doesn't work in codeigniter

Well, the documentation does actually state that

CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared.

as the very first thing, which obviusly means that you need to do a new server request. A redirect, a refresh, a link or some other mean to send the user to the next request.

Why use flashdata if you are using it in the same request, anyway? You'd might as well not use flashdata or use a regular session.

How to get the last char of a string in PHP?

Remember, if you have a string which was read as a line from a text file using the fgets() function, you need to use substr($string, -3, 1) so that you get the actual character and not part of the CRLF (Carriage Return Line Feed).

I don't think the person who asked the question needed this, but for me, I was having trouble getting that last character from a string from a text file so I'm sure others will come across similar problems.

How to convert local time string to UTC?

NOTE -- As of 2020 you should not be using .utcnow() or .utcfromtimestamp(xxx). As you've presumably moved on to python3,you should be using timezone aware datetime objects.

>>> from datetime import timezone
>>> dt_now = datetime.now(tz=timezone.utc)
>>> dt_ts = datetime.fromtimestamp(1571595618.0, tz=timezone.utc)

for details see: see: https://blog.ganssle.io/articles/2019/11/utcnow.html

original answer (from 2010):

The datetime module's utcnow() function can be used to obtain the current UTC time.

>>> import datetime
>>> utc_datetime = datetime.datetime.utcnow()
>>> utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2010-02-01 06:59:19'

As the link mentioned above by Tom: http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/ says:

UTC is a timezone without daylight saving time and still a timezone without configuration changes in the past.

Always measure and store time in UTC.

If you need to record where the time was taken, store that separately. Do not store the local time + timezone information!

NOTE - If any of your data is in a region that uses DST, use pytz and take a look at John Millikin's answer.

If you want to obtain the UTC time from a given string and your lucky enough to be in a region in the world that either doesn't use DST, or you have data that is only offset from UTC without DST applied:

--> using local time as the basis for the offset value:

>>> # Obtain the UTC Offset for the current system:
>>> UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now()
>>> local_datetime = datetime.datetime.strptime("2008-09-17 14:04:00", "%Y-%m-%d %H:%M:%S")
>>> result_utc_datetime = local_datetime + UTC_OFFSET_TIMEDELTA
>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2008-09-17 04:04:00'

--> Or, from a known offset, using datetime.timedelta():

>>> UTC_OFFSET = 10
>>> result_utc_datetime = local_datetime - datetime.timedelta(hours=UTC_OFFSET)
>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2008-09-17 04:04:00'

UPDATE:

Since python 3.2 datetime.timezone is available. You can generate a timezone aware datetime object with the command below:

import datetime

timezone_aware_dt = datetime.datetime.now(datetime.timezone.utc)

If your ready to take on timezone conversions go read this:

https://medium.com/@eleroy/10-things-you-need-to-know-about-date-and-time-in-python-with-datetime-pytz-dateutil-timedelta-309bfbafb3f7

Disable/turn off inherited CSS3 transitions

If you want to disable a single transition property, you can do:

transition: color 0s;

(since a zero second transition is the same as no transition.)

Return index of highest value in an array

<?php

$array = array(11 => 14,
               10 => 9,
               12 => 7,
               13 => 7,
               14 => 4,
               15 => 6);

echo array_search(max($array), $array);

?>

array_search() return values:

Returns the key for needle if it is found in the array, FALSE otherwise.

If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

How to check if an app is installed from a web-page on an iPhone?

As far as I know you can not, from a browser, check if an app is installed or not.

But you can try redirecting the phone to the app, and if nothing happens redirect the phone to a specified page, like this:

setTimeout(function () { window.location = "https://itunes.apple.com/appdir"; }, 25);
window.location = "appname://";

If the second line of code gives a result then the first row is never executed.

Hope this helps!

Similar question:

What is more efficient? Using pow to square or just multiply it with itself?

The most efficient way is to consider the exponential growth of the multiplications. Check this code for p^q:

template <typename T>
T expt(T p, unsigned q){
    T r =1;
    while (q != 0) {
        if (q % 2 == 1) {    // if q is odd
            r *= p;
            q--;
        }
        p *= p;
        q /= 2;
    }
    return r;
}

Swift - Split string over multiple lines

Swift 4 has addressed this issue by giving Multi line string literal support.To begin string literal add three double quotes marks (”””) and press return key, After pressing return key start writing strings with any variables , line breaks and double quotes just like you would write in notepad or any text editor. To end multi line string literal again write (”””) in new line.

See Below Example

     let multiLineStringLiteral = """
    This is one of the best feature add in Swift 4
    It let’s you write “Double Quotes” without any escaping
    and new lines without need of “\n”
    """

print(multiLineStringLiteral)

New og:image size for Facebook share?

What size this image should be depends on where it is to be used.

It is up to applications, eg WhatsApp, Facebook Messenger, Reddit, etc etc to decide what to do with the image. Some use it as a square image, some as a 1:19.1 rectangle, and some use different sizes when the display environment is of different sizes even for the same application. There are no rules, and there is no way to control what applications do with the image.

So you should test out the image on your intended target application(s) and find a compromise. That applications tend to cache the image makes it a pain on the trial and error approach.

"static const" vs "#define" vs "enum"

I wrote quick test program to demonstrate one difference:

#include <stdio.h>

enum {ENUM_DEFINED=16};
enum {ENUM_DEFINED=32};

#define DEFINED_DEFINED 16
#define DEFINED_DEFINED 32

int main(int argc, char *argv[]) {

   printf("%d, %d\n", DEFINED_DEFINED, ENUM_DEFINED);

   return(0);
}

This compiles with these errors and warnings:

main.c:6:7: error: redefinition of enumerator 'ENUM_DEFINED'
enum {ENUM_DEFINED=32};
      ^
main.c:5:7: note: previous definition is here
enum {ENUM_DEFINED=16};
      ^
main.c:9:9: warning: 'DEFINED_DEFINED' macro redefined [-Wmacro-redefined]
#define DEFINED_DEFINED 32
        ^
main.c:8:9: note: previous definition is here
#define DEFINED_DEFINED 16
        ^

Note that enum gives an error when define gives a warning.

Rendering HTML inside textarea

try this example

_x000D_
_x000D_
function toggleRed() {_x000D_
  var text = $('.editable').text();_x000D_
  $('.editable').html('<p style="color:red">' + text + '</p>');_x000D_
}_x000D_
_x000D_
function toggleItalic() {_x000D_
  var text = $('.editable').text();_x000D_
  $('.editable').html("<i>" + text + "</i>");_x000D_
}_x000D_
_x000D_
$('.bold').click(function() {_x000D_
  toggleRed();_x000D_
});_x000D_
_x000D_
$('.italic').click(function() {_x000D_
  toggleItalic();_x000D_
});
_x000D_
.editable {_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
  border: 1px solid #ccc;_x000D_
  padding: 5px;_x000D_
  resize: both;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="editable" contenteditable="true"></div>_x000D_
<button class="bold">toggle red</button>_x000D_
<button class="italic">toggle italic</button>
_x000D_
_x000D_
_x000D_

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

"Case" can return single value only, but you can use complex type:

create type foo as (a int, b text);
select (case 1 when 1 then (1,'qq')::foo else (2,'ww')::foo end).*;

Time complexity of accessing a Python dict

As others have pointed out, accessing dicts in Python is fast. They are probably the best-oiled data structure in the language, given their central role. The problem lies elsewhere.

How many tuples are you memoizing? Have you considered the memory footprint? Perhaps you are spending all your time in the memory allocator or paging memory.

Get integer value from string in swift

You can bridge from String to NSString and convert from CInt to Int like this:

var myint: Int = Int(stringNumb.bridgeToObjectiveC().intValue)

How are people unit testing with Entity Framework 6, should you bother?

In short I would say no, the juice is not worth the squeeze to test a service method with a single line that retrieves model data. In my experience people who are new to TDD want to test absolutely everything. The old chestnut of abstracting a facade to a 3rd party framework just so you can create a mock of that frameworks API with which you bastardise/extend so that you can inject dummy data is of little value in my mind. Everyone has a different view of how much unit testing is best. I tend to be more pragmatic these days and ask myself if my test is really adding value to the end product, and at what cost.

How to redirect output of an already running process

You can also do it using reredirect (https://github.com/jerome-pouiller/reredirect/).

The command bellow redirects the outputs (standard and error) of the process PID to FILE:

reredirect -m FILE PID

The README of reredirect also explains other interesting features: how to restore the original state of the process, how to redirect to another command or to redirect only stdout or stderr.

The tool also provides relink, a script allowing to redirect the outputs to the current terminal:

relink PID
relink PID | grep usefull_content

(reredirect seems to have same features than Dupx described in another answer but, it does not depend on Gdb).

How to create a new column in a select query

SELECT field1, 
       field2,
       'example' AS newfield
FROM TABLE1

This will add a column called "newfield" to the output, and its value will always be "example".

How do I compile a .cpp file on Linux?

You'll need to compile it using:

g++ inputfile.cpp -o outputbinary

The file you are referring has a missing #include <cstdlib> directive, if you also include that in your file, everything shall compile fine.

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

You're missing service name:

 SQL> connect username/password@hostname:port/SERVICENAME

EDIT

If you can connect to the database from other computer try running there:

select sys_context('USERENV','SERVICE_NAME') from dual

and

select sys_context('USERENV','SID') from dual

DBCC SHRINKFILE on log file not reducing size even after BACKUP LOG TO DISK

I tried many ways but this works.

Sample code is availalbe in DBCC SHRINKFILE

USE DBName;  
GO  
-- Truncate the log by changing the database recovery model to SIMPLE.  
ALTER DATABASE DBName  
SET RECOVERY SIMPLE;  
GO  
-- Shrink the truncated log file to 1 MB.  
DBCC SHRINKFILE (DBName_log, 1);  --File name SELECT * FROM sys.database_files; query to get the file name
GO  
-- Reset the database recovery model.  
ALTER DATABASE DBName  
SET RECOVERY FULL;  
GO

Add CSS to iFrame

Based on solution You've already found How to apply CSS to iframe?:

var cssLink = document.createElement("link") 
cssLink.href = "file://path/to/style.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 
frames['iframe'].document.body.appendChild(cssLink);

or more jqueryish (from Append a stylesheet to an iframe with jQuery):

var $head = $("iframe").contents().find("head");                
$head.append($("<link/>", 
    { rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));

as for security issues: Disabling same-origin policy in Safari

Hiding the scroll bar on an HTML page

Use the CSS overflow property:

.noscroll {
  width: 150px;
  height: 150px;
  overflow: auto; /* Or hidden, or visible */
}

Here are some more examples:

How to render an array of objects in React?

Shubham's answer explains very well. This answer is addition to it as per to avoid some pitfalls and refactoring to a more readable syntax

Pitfall : There is common misconception in rendering array of objects especially if there is an update or delete action performed on data. Use case would be like deleting an item from table row. Sometimes when row which is expected to be deleted, does not get deleted and instead other row gets deleted.

To avoid this, use key prop in root element which is looped over in JSX tree of .map(). Also adding React's Fragment will avoid adding another element in between of ul and li when rendered via calling method.

state = {
    userData: [
        { id: '1', name: 'Joe', user_type: 'Developer' },
        { id: '2', name: 'Hill', user_type: 'Designer' }
    ]
};

deleteUser = id => {
    // delete operation to remove item
};

renderItems = () => {
    const data = this.state.userData;

    const mapRows = data.map((item, index) => (
        <Fragment key={item.id}>
            <li>
                {/* Passing unique value to 'key' prop, eases process for virtual DOM to remove specific element and update HTML tree  */}
                <span>Name : {item.name}</span>
                <span>User Type: {item.user_type}</span>
                <button onClick={() => this.deleteUser(item.id)}>
                    Delete User
                </button>
            </li>
        </Fragment>
    ));
    return mapRows;
};

render() {
    return <ul>{this.renderItems()}</ul>;
}

Important : Decision to use which value should we pass to key prop also matters as common way is to use index parameter provided by .map().

TLDR; But there's a drawback to it and avoid it as much as possible and use any unique id from data which is being iterated such as item.id. There's a good article on this - https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318

How do I set the selenium webdriver get timeout?

Try this:

 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

Is there anyway to exclude artifacts inherited from a parent POM?

Repeat the parent's dependency in child pom.xml and insert the exclusion there:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>com.vaadin.external.google</groupId>
            <artifactId>android-json</artifactId>
        </exclusion>
    </exclusions>
</dependency>

How to print a dictionary's key?

If you want to get the key of a single value, the following would help:

def get_key(b): # the value is passed to the function
    for k, v in mydic.items():
        if v.lower() == b.lower():
            return k

In pythonic way:

c = next((x for x, y in mydic.items() if y.lower() == b.lower()), \
     "Enter a valid 'Value'")
print(c)

Directing print output to a .txt file

You can redirect stdout into a file "output.txt":

import sys
sys.stdout = open('output.txt','wt')
print ("Hello stackoverflow!")
print ("I have a question.")

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

Programmatically getting the MAC of an Android device

Taken from the Android sources here. This is the actual code that shows your MAC ADDRESS in the system's settings app.

private void refreshWifiInfo() {
    WifiInfo wifiInfo = mWifiManager.getConnectionInfo();

    Preference wifiMacAddressPref = findPreference(KEY_MAC_ADDRESS);
    String macAddress = wifiInfo == null ? null : wifiInfo.getMacAddress();
    wifiMacAddressPref.setSummary(!TextUtils.isEmpty(macAddress) ? macAddress
            : getActivity().getString(R.string.status_unavailable));

    Preference wifiIpAddressPref = findPreference(KEY_CURRENT_IP_ADDRESS);
    String ipAddress = Utils.getWifiIpAddresses(getActivity());
    wifiIpAddressPref.setSummary(ipAddress == null ?
            getActivity().getString(R.string.status_unavailable) : ipAddress);
}

What does "wrong number of arguments (1 for 0)" mean in Ruby?

If you change from using a lambda with one argument to a function with one argument, you will get this error.

For example:

You had:

foobar = lambda do |baz|
  puts baz
end

and you changed the definition to

def foobar(baz)
  puts baz
end

And you left your invocation as:

foobar.call(baz)

And then you got the message

ArgumentError: wrong number of arguments (0 for 1)

when you really meant:

foobar(baz)

Installing Tomcat 7 as Service on Windows Server 2008

I had a similar problem, there isn't a service.bat in the zip version of tomcat that I downloaded ages ago.

I simply downloaded a new 64-bit Windows zip version of tomcat from http://tomcat.apache.org/download-70.cgi and replaced my existing tomcat\bin folder with the one I just downloaded (Remember to keep a backup first!).

Start command prompt > navigate to the tomcat\bin directory > issue the command:

service.bat install

Hope that helps!

Session TimeOut in web.xml

To set a session-timeout that never expires is not desirable because you would be reliable on the user to push the logout-button every time he's finished to prevent your server of too much load (depending on the amount of users and the hardware). Additionaly there are some security issues you might run into you would rather avoid.

The reason why the session gets invalidated while the server is still working on a task is because there is no communication between client-side (users browser) and server-side through e.g. a http-request. Therefore the server can't know about the users state, thinks he's idling and invalidates the session after the time set in your web.xml.

To get around this you have several possibilities:

  • You could ping your backend while the task is running to touch the session and prevent it from being expired
  • increase the <session-timeout> inside the server but I wouldn't recommend this
  • run your task in a dedicated thread which touches (extends) the session while working or notifies the user when the thread has finished

There was a similar question asked, maybe you can adapt parts of this solution in your project. Have a look at this.

Hope this helps, have Fun!

Text blinking jQuery

I was going to post the steps-timed polyfill, but then I remembered that I really don’t want to ever see this effect, so…

function blink(element, interval) {
    var visible = true;

    setInterval(function() {
        visible = !visible;
        element.style.visibility = visible ? "visible" : "hidden";
    }, interval || 1000);
}

regex pattern to match the end of a string

Should be

~/([^/]*)$~

Means: Match a / and then everything, that is not a / ([^/]*) until the end ($, "end"-anchor).

I use the ~ as delimiter, because now I don't need to escape the forward-slash /.

Should a RESTful 'PUT' operation return something

There's a difference between the header and body of a HTTP response. PUT should never return a body, but must return a response code in the header. Just choose 200 if it was successful, and 4xx if not. There is no such thing as a null return code. Why do you want to do this?

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

For those who have a file from an input control, don't know what its orientation is, are a bit lazy and don't want to include a large library below is the code provided by @WunderBart melded with the answer he links to (https://stackoverflow.com/a/32490603) that finds the orientation.

function getDataUrl(file, callback2) {
        var callback = function (srcOrientation) {
            var reader2 = new FileReader();
            reader2.onload = function (e) {
                var srcBase64 = e.target.result;
                var img = new Image();

                img.onload = function () {
                    var width = img.width,
                        height = img.height,
                        canvas = document.createElement('canvas'),
                        ctx = canvas.getContext("2d");

                    // set proper canvas dimensions before transform & export
                    if (4 < srcOrientation && srcOrientation < 9) {
                        canvas.width = height;
                        canvas.height = width;
                    } else {
                        canvas.width = width;
                        canvas.height = height;
                    }

                    // transform context before drawing image
                    switch (srcOrientation) {
                        case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
                        case 3: ctx.transform(-1, 0, 0, -1, width, height); break;
                        case 4: ctx.transform(1, 0, 0, -1, 0, height); break;
                        case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
                        case 6: ctx.transform(0, 1, -1, 0, height, 0); break;
                        case 7: ctx.transform(0, -1, -1, 0, height, width); break;
                        case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
                        default: break;
                    }

                    // draw image
                    ctx.drawImage(img, 0, 0);

                    // export base64
                    callback2(canvas.toDataURL());
                };

                img.src = srcBase64;
            }

            reader2.readAsDataURL(file);
        }

        var reader = new FileReader();
        reader.onload = function (e) {

            var view = new DataView(e.target.result);
            if (view.getUint16(0, false) != 0xFFD8) return callback(-2);
            var length = view.byteLength, offset = 2;
            while (offset < length) {
                var marker = view.getUint16(offset, false);
                offset += 2;
                if (marker == 0xFFE1) {
                    if (view.getUint32(offset += 2, false) != 0x45786966) return callback(-1);
                    var little = view.getUint16(offset += 6, false) == 0x4949;
                    offset += view.getUint32(offset + 4, little);
                    var tags = view.getUint16(offset, little);
                    offset += 2;
                    for (var i = 0; i < tags; i++)
                        if (view.getUint16(offset + (i * 12), little) == 0x0112)
                            return callback(view.getUint16(offset + (i * 12) + 8, little));
                }
                else if ((marker & 0xFF00) != 0xFF00) break;
                else offset += view.getUint16(offset, false);
            }
            return callback(-1);
        };
        reader.readAsArrayBuffer(file);
    }

which can easily be called like such

getDataUrl(input.files[0], function (imgBase64) {
      vm.user.BioPhoto = imgBase64;
});

Converting newline formatting from Mac to Windows

Here's a really simple approach, worked well for me, courtesy Davy Schmeits's Weblog:

cat foo | col -b > foo2

Where foo is the file that has the Control+M characters at the end of the line, and foo2 the new file you are creating.

Why is the Android emulator so slow? How can we speed up the Android emulator?

I just noticed something I can't explain, but hey, for me it works!

I was compiling Android from sources anyway and the built-in emulator started in a few seconds (my machine is dual core AMD 2.7 GHz) and in a minute, perhaps two at the first run, the system was up. Using Eclipse ADT bundle, on the other hand, resulted in half an hour of emulator startup. Unacceptable.

The solution that works here (I have no means to test it on other machines, so if you feel inclined, test and verify):

  • Download and build Android SDK on your machine. It may take some time (you know, compilation of whole system is tiresome). Instructions can be found here:
    1. Initializing
    2. Downloading
    3. Building (I changed commands to 'lunch sdk-eng' and 'make sdk -j4'; besides that build tips are useful, especially concerning ccache and -jN option)
  • When done, run 'android' and the SDK manager should appear. Download tools and desired platform packages. If commands are not found, try rerunning '. build/envsetup.sh' and 'lunch sdk-eng' commands to set up pathes; they are lost after exiting a terminal session.
  • Run 'emulator' to check how fast it starts up. For me it's MUCH faster than the Eclipse-bundled one.
  • If that works, point Eclipse to the SDK you just compiled. Window-Preferences-Android in left pane -> choose SDK location. It should be dir with 'tools' subdir and something in 'platforms' subdir. For me it's <source base dir>/out/host/linux-x86
  • Apply/OK, restart Eclipse if needed. If it does not complain about anything, run your Android app. In my case, the emulator starts in a few seconds and finishes boot in under a minute. There is still a bit delay, but it entirely acceptable for me.

Also, I agree with running from snapshot and saving state to snapshot. My advice concerns only emulator startup time. I still have no idea why it is so long by default. Anyway, if that works for you, enjoy :)

close fxml window by code, javafx

I'm not sure if this is the best way (or if it works), but you could try:

private void on_btnClose_clicked(ActionEvent actionEvent) {

        Window window = getScene().getWindow();   

        if (window instanceof Stage){
            ((Stage) window).close();
        }
}

(Assuming your controller is a Node. Otherwise you have to get the node first (getScene() is a method of Node)

How to define Singleton in TypeScript

namespace MySingleton {
  interface IMySingleton {
      doSomething(): void;
  }
  class MySingleton implements IMySingleton {
      private usePrivate() { }
      doSomething() {
          this.usePrivate();
      }
  }
  export var Instance: IMySingleton = new MySingleton();
}

This way we can apply an interface, unlike in Ryan Cavanaugh's accepted answer.

What are the advantages and disadvantages of recursion?

We should use recursion in following scenarios:

  • when we don't know the finite number of iteration for example our fuction exit condition is based on dynamic programming (memoization)
  • when we need to perform operations on reverse order of the elements. Meaning we want to process last element first and then n-1, n-2 and so on till first element

Recursion will save multiple traversals. And it will be useful, if we can divide the stack allocation like:

int N = 10;
int output = process(N) + process(N/2);
public void process(int n) {
    if (n==N/2 + 1 || n==1) {
       return 1;
    }

    return process(n-1) + process(n-2);
}

In this case only half stacks will be allocated at any given time.

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

I think the easiest solution is to set

Created DATETIME2 NOT NULL DEFAULT GETDATE()

in column declaration and in VS2010 EntityModel designer set corresponding column property StoreGeneratedPattern = Computed.

How to convert integers to characters in C?

Casting the integer to a char will do what you want.

char theChar=' ';
int theInt = 97;
theChar=(char) theInt;

cout<<theChar<<endl;

There is no difference between 'a' and 97 besides the way you interperet them.

Convert integer to hexadecimal and back again

int valInt = 12;
Console.WriteLine(valInt.ToString("X"));  // C  ~ possibly single-digit output 
Console.WriteLine(valInt.ToString("X2")); // 0C ~ always double-digit output

How to execute a raw update sql with dynamic binding in rails

I needed to use raw sql because I failed at getting composite_primary_keys to function with activerecord 2.3.8. So in order to access the sqlserver 2000 table with a composite primary key, raw sql was required.

sql = "update [db].[dbo].[#{Contacts.table_name}] " +
      "set [COLUMN] = 0 " +
      "where [CLIENT_ID] = '#{contact.CLIENT_ID}' and CONTACT_ID = '#{contact.CONTACT_ID}'"
st = ActiveRecord::Base.connection.raw_connection.prepare(sql)
st.execute

If a better solution is available, please share.

How can I force users to access my page over HTTPS instead of HTTP?

Using this is NOT enough:

if($_SERVER["HTTPS"] != "on")
{
    header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
    exit();
}

If you have any http content (like an external http image source), the browser will detect a possible threat. So be sure all your ref and src inside your code are https

List distinct values in a vector in R

You can also use the sqldf package in R.

Z <- sqldf('SELECT DISTINCT tablename.columnname FROM tablename ')

What is time_t ultimately a typedef to?

The time_t Wikipedia article article sheds some light on this. The bottom line is that the type of time_t is not guaranteed in the C specification.

The time_t datatype is a data type in the ISO C library defined for storing system time values. Such values are returned from the standard time() library function. This type is a typedef defined in the standard header. ISO C defines time_t as an arithmetic type, but does not specify any particular type, range, resolution, or encoding for it. Also unspecified are the meanings of arithmetic operations applied to time values.

Unix and POSIX-compliant systems implement the time_t type as a signed integer (typically 32 or 64 bits wide) which represents the number of seconds since the start of the Unix epoch: midnight UTC of January 1, 1970 (not counting leap seconds). Some systems correctly handle negative time values, while others do not. Systems using a 32-bit time_t type are susceptible to the Year 2038 problem.

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

I would agree with Benjamin, either install MAMP or MacPorts (http://www.macports.org/). Keeping your PHP install separate is simpler and avoids messing up the core PHP install if you make any mistakes!

MacPorts is a bit better for installing other software, such as ImageMagick. See a full list of available ports at http://www.macports.org/ports.php

MAMP just really does PHP, Apache and MySQL so any future PHP modules you want will need to be manually enabled. It is incredibly easy to use though.

JavaScript listener, "keypress" doesn't detect backspace?

Something I wrote up incase anyone comes across an issue with people hitting backspace while thinking they are in a form field

window.addEventListener("keydown", function(e){
    /*
     * keyCode: 8
     * keyIdentifier: "U+0008"
    */
    if(e.keyCode === 8 && document.activeElement !== 'text') {
        e.preventDefault();
        alert('Prevent page from going back');
    }
});

sql query with multiple where statements

This..

(
        (meta_key = 'lat' AND meta_value >= '60.23457047672217')
    OR
        (meta_key = 'lat' AND meta_value <= '60.23457047672217')
)

is the same as

(
        (meta_key = 'lat')
)

Adding it all together (the same applies to the long filter) you have this impossible WHERE clause which will give no rows because meta_key cannot be 2 values in one row

WHERE
    (meta_key = 'lat' AND meta_key = 'long' )

You need to review your operators to make sure you get the correct logic

How to add form validation pattern in Angular 2?

You could build your form using FormBuilder as it let you more flexible way to configure form.

export class MyComp {
  form: ControlGroup;

  constructor(@Inject()fb: FormBuilder) {  
    this.form = fb.group({  
      foo: ['', MyValidators.regex(/^(?!\s|.*\s$).*$/)]  
    });  
  }

Then in your template :

<input type="text" ngControl="foo" />
<div *ngIf="!form.foo.valid">Please correct foo entry !</div> 

You can also customize ng-invalid CSS class.

As there is actually no validators for regex, you have to write your own. It is a simple function that takes a control in input, and return null if valid or a StringMap if invalid.

export class MyValidators {
  static regex(pattern: string): Function {
    return (control: Control): {[key: string]: any} => {
      return control.value.match(pattern) ? null : {pattern: true};
    };
  }
}

Hope that it help you.

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

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

Convert array to JSON string in swift

As it stands you're converting it to data, then attempting to convert the data to to an object as JSON (which fails, it's not JSON) and converting that to a string, basically you have a bunch of meaningless transformations.

As long as the array contains only JSON encodable values (string, number, dictionary, array, nil) you can just use NSJSONSerialization to do it.

Instead just do the array->data->string parts:

Swift 3/4

let array = [ "one", "two" ]

func json(from object:Any) -> String? {
    guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else {
        return nil
    }
    return String(data: data, encoding: String.Encoding.utf8)
}

print("\(json(from:array as Any))")

Original Answer

let array = [ "one", "two" ]
let data = NSJSONSerialization.dataWithJSONObject(array, options: nil, error: nil)
let string = NSString(data: data!, encoding: NSUTF8StringEncoding)

although you should probably not use forced unwrapping, it gives you the right starting point.

How do you fix a bad merge, and replay your good commits onto a fixed merge?

Rewriting Git history demands changing all the affected commit ids, and so everyone who's working on the project will need to delete their old copies of the repo, and do a fresh clone after you've cleaned the history. The more people it inconveniences, the more you need a good reason to do it - your superfluous file isn't really causing a problem, but if only you are working on the project, you might as well clean up the Git history if you want to!

To make it as easy as possible, I'd recommend using the BFG Repo-Cleaner, a simpler, faster alternative to git-filter-branch specifically designed for removing files from Git history. One way in which it makes your life easier here is that it actually handles all refs by default (all tags, branches, etc) but it's also 10 - 50x faster.

You should carefully follow the steps here: http://rtyley.github.com/bfg-repo-cleaner/#usage - but the core bit is just this: download the BFG jar (requires Java 6 or above) and run this command:

$ java -jar bfg.jar --delete-files filename.orig my-repo.git

Your entire repository history will be scanned, and any file named filename.orig (that's not in your latest commit) will be removed. This is considerably easier than using git-filter-branch to do the same thing!

Full disclosure: I'm the author of the BFG Repo-Cleaner.

AngularJS 1.2 $injector:modulerr

Sometime I have seen this error when you are switching between the projects and running the projects on the same port one after the other. In that case goto chrome Developer Tools > Network and try to check the actual written js file for: if the file match with the workspce. To resolve this select Disable Cache under network.

is python capable of running on multiple cores?

Threads share a process and a process runs on a core, but you can use python's multiprocessing module to call your functions in separate processes and use other cores, or you can use the subprocess module, which can run your code and non-python code too.

Finding duplicate values in a SQL table

This selects/deletes all duplicate records except one record from each group of duplicates. So, the delete leaves all unique records + one record from each group of the duplicates.

Select duplicates:

SELECT *
FROM table
WHERE
    id NOT IN (
        SELECT MIN(id)
        FROM table
        GROUP BY column1, column2
);

Delete duplicates:

DELETE FROM table
WHERE
    id NOT IN (
        SELECT MIN(id)
        FROM table
        GROUP BY column1, column2
);

Be aware of larger amounts of records, it can cause performance problems.

Python idiom to return first item or None

The most python idiomatic way is to use the next() on a iterator since list is iterable. just like what @J.F.Sebastian put in the comment on Dec 13, 2011.

next(iter(the_list), None) This returns None if the_list is empty. see next() Python 2.6+

or if you know for sure the_list is not empty:

iter(the_list).next() see iterator.next() Python 2.2+

Using ng-if as a switch inside ng-repeat?

I will suggest move all templates to separate files, and don't do spagetti inside repeat

take a look here:

html:

<div ng-repeat = "data in comments">
    <div ng-include src="buildUrl(data.type)"></div>
 </div>

js:

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {

  $scope.comments = [
    {"_id":"52fb84fac6b93c152d8b4569",
       "post_id":"52fb84fac6b93c152d8b4567",
       "user_id":"52df9ab5c6b93c8e2a8b4567",
       "type":"hoot"},  
    {"_id":"52fb798cc6b93c74298b4568",
       "post_id":"52fb798cc6b93c74298b4567",
       "user_id":"52df9ab5c6b93c8e2a8b4567",
       "type":"story"},        
    {"_id":"52fb7977c6b93c5c2c8b456b",
       "post_id":"52fb7977c6b93c5c2c8b456a",
       "user_id":"52df9ab5c6b93c8e2a8b4567",
       "type":"article"}
  ];

  $scope.buildUrl = function(type) {
    return type + '.html';
  }
});

http://plnkr.co/edit/HxnirSvMHNQ748M2WeRt?p=preview

Change text from "Submit" on input tag

<input name="submitBnt" type="submit" value="like"/>

name is useful when using $_POST in php and also in javascript as document.getElementByName('submitBnt'). Also you can use name as a CS selector like input[name="submitBnt"]; Hope this helps

Clone contents of a GitHub repository (without the folder itself)

this worker for me

git clone <repository> .

Where do I put image files, css, js, etc. in Codeigniter?

This is how I handle the public assets. Here I use Phalcon PHP's Bootstrap method.

Folder Structure

|-.htaccess*
|-application/
|-public/
  |-.htaccess**
  |-index.php***
  |-css/
  |-js/
  |-img/
  |-font/
  |-upload/
|-system

Files to edit

  1. .htaccess*

    All requests to the project will be rewritten to the public/ directory making it the document root. This step ensures that the internal project folders remain hidden from public viewing and thus eliminates security threats of this kind. - Phalconphp Doc

    <IfModule mod_rewrite.c>
        RewriteEngine on
        RewriteRule  ^$ public/    [L]
        RewriteRule  (.*) public/$1 [L]
    </IfModule>
    
  2. .htaccess**

    Rules will check if the requested file exists and, if it does, it doesn’t have to be rewritten by the web server module. - Phalconphp Doc

    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ index.php/$1 [QSA,L]
    </IfModule>
    
  3. index.php***

    Modify the application path and the system path as,

    $system_path = '../system';
    $application_folder = '../application';
    

Now you use the public folder as base_url()."public/[YOUR ASSET FOLDER]"

Hope this helps :)

how to create inline style with :before and :after

You can't. With inline styles you are targeting the element directly. You can't use other selectors there.

What you can do however is define different classes in your stylesheet that define different colours and then add the class to the element.

getting the difference between date in days in java

Use JodaTime for this. It is much better than the standard Java DateTime Apis. Here is the code in JodaTime for calculating difference in days:

private static void dateDiff() {

    System.out.println("Calculate difference between two dates");
    System.out.println("=================================================================");

    DateTime startDate = new DateTime(2000, 1, 19, 0, 0, 0, 0);
    DateTime endDate = new DateTime();

    Days d = Days.daysBetween(startDate, endDate);
    int days = d.getDays();

    System.out.println("  Difference between " + endDate);
    System.out.println("  and " + startDate + " is " + days + " days.");

  }