Programs & Examples On #Data driven

A programming paradigm in which the program statements describe the data to be matched and the processing required rather than defining a sequence of steps to be taken.

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

embedding image in html email

One additional hint to Pavel Perna's post which helped me very much (cannot comment with my reputation, that's why I post this as answer): In some versions of Microsoft Exchange, the inline contents disposition is removed (see this post by Microsoft). The image is simply not part in the mail the user sees in Outlook. As a workaround, use "Content-Disposition: attachement" instead. Outlook 2016 won't show images as attachement that are used in the mail message, although they use the "Content-Disposition: attachement".

Curl GET request with json parameter

GET takes name value pairs.

Try something like:

curl http://server:5050/a/c/getName/?param1=pradeep

or

curl http://server:5050/a/c/getName?param1=pradeep

btw a regular REST should look something like

curl http://server:5050/a/c/getName/pradeep If it takes JSON in GET URL, it's not a standard way.

Difference between null and empty ("") Java String

There is a pretty significant difference between the two. The empty string "" is "the string that has no characters in it." It's an actual string that has a well-defined length. All of the standard string operations are well-defined on the empty string - you can convert it to lower case, look up the index of some character in it, etc. The null string null is "no string at all." It doesn't have a length because it's not a string at all. Trying to apply any standard string operation to the null string will cause a NullPointerException at runtime.

How to change a field name in JSON using Jackson

There is one more option to rename field:

Jackson MixIns.

Useful if you deal with third party classes, which you are not able to annotate, or you just do not want to pollute the class with Jackson specific annotations.

The Jackson documentation for Mixins is outdated, so this example can provide more clarity. In essence: you create mixin class which does the serialization in the way you want. Then register it to the ObjectMapper:

objectMapper.addMixIn(ThirdParty.class, MyMixIn.class);

How to insert values in two dimensional array programmatically?

In case you don't know in advance how many elements you will have to handle it might be a better solution to use collections instead (https://en.wikipedia.org/wiki/Java_collections_framework). It would be possible also to create a new bigger 2-dimensional array, copy the old data over and insert the new items there, but the collection framework handles this for you automatically.

In this case you could use a Map of Strings to Lists of Strings:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyClass {
    public static void main(String args[]) {
        Map<String, List<String>> shades = new HashMap<>();

        ArrayList<String> shadesOfGrey = new ArrayList<>();
        shadesOfGrey.add("lightgrey");
        shadesOfGrey.add("dimgray");
        shadesOfGrey.add("sgi gray 92");

        ArrayList<String> shadesOfBlue = new ArrayList<>();
        shadesOfBlue.add("dodgerblue 2");
        shadesOfBlue.add("steelblue 2");
        shadesOfBlue.add("powderblue");

        ArrayList<String> shadesOfYellow = new ArrayList<>();
        shadesOfYellow.add("yellow 1");
        shadesOfYellow.add("gold 1");
        shadesOfYellow.add("darkgoldenrod 1");

        ArrayList<String> shadesOfRed = new ArrayList<>();
        shadesOfRed.add("indianred 1");
        shadesOfRed.add("firebrick 1");
        shadesOfRed.add("maroon 1");

        shades.put("greys", shadesOfGrey);
        shades.put("blues", shadesOfBlue);
        shades.put("yellows", shadesOfYellow);
        shades.put("reds", shadesOfRed);

        System.out.println(shades.get("greys").get(0)); // prints "lightgrey"
    }
}

VB.NET - Remove a characters from a String

Function RemoveCharacter(ByVal stringToCleanUp, ByVal characterToRemove)
  ' replace the target with nothing
  ' Replace() returns a new String and does not modify the current one
  Return stringToCleanUp.Replace(characterToRemove, "")
End Function

Here's more information about VB's Replace function

Is JavaScript a pass-by-reference or pass-by-value language?

It's always pass by value, but for objects the value of the variable is a reference. Because of this, when you pass an object and change its members, those changes persist outside of the function. This makes it look like pass by reference. But if you actually change the value of the object variable you will see that the change does not persist, proving it's really pass by value.

Example:

_x000D_
_x000D_
function changeObject(x) {_x000D_
  x = { member: "bar" };_x000D_
  console.log("in changeObject: " + x.member);_x000D_
}_x000D_
_x000D_
function changeMember(x) {_x000D_
  x.member = "bar";_x000D_
  console.log("in changeMember: " + x.member);_x000D_
}_x000D_
_x000D_
var x = { member: "foo" };_x000D_
_x000D_
console.log("before changeObject: " + x.member);_x000D_
changeObject(x);_x000D_
console.log("after changeObject: " + x.member); /* change did not persist */_x000D_
_x000D_
console.log("before changeMember: " + x.member);_x000D_
changeMember(x);_x000D_
console.log("after changeMember: " + x.member); /* change persists */
_x000D_
_x000D_
_x000D_

Output:

before changeObject: foo
in changeObject: bar
after changeObject: foo

before changeMember: foo
in changeMember: bar
after changeMember: bar

Programmatically extract contents of InstallShield setup.exe

Start with:

setup.exe /?

And you should see a dialog popup with some options displayed.

Open file with associated application

This is an old thread but just in case anyone comes across it like I did. pi.FileName needs to be set to the file name (and possibly full path to file ) of the executable you want to use to open your file. The below code works for me to open a video file with VLC.

var path = files[currentIndex].fileName;
var pi = new ProcessStartInfo(path)
{
    Arguments = Path.GetFileName(path),
    UseShellExecute = true,
    WorkingDirectory = Path.GetDirectoryName(path),
    FileName = "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe",
    Verb = "OPEN"
};
Process.Start(pi)

Tigran's answer works but will use windows' default application to open your file, so using ProcessStartInfo may be useful if you want to open the file with an application that is not the default.

I want to execute shell commands from Maven's pom.xml

Thanks! Tomer Ben David. it helped me. as I am doing pip install in demo folder as you mentioned npm install

<groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.3.2</version>
            <executions>
              <execution>
                <goals>
                  <goal>exec</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <executable>pip</executable>
              <arguments><argument>install</argument></arguments>                            
             <workingDirectory>${project.build.directory}/Demo</workingDirectory>
            </configuration>

Proper MIME type for OTF fonts

Since Feb 2017 RFC 8081 groups all MIME types for fonts under the top level font media type. The older MIME types from my original posting are now listed as deprecated.

Font types as listed by IANA are now:

Other non-standard font formats are left as are:


[Outdated Original Post]

As there's still a lot of confusion on the web about MIME types for web fonts, I thought I'd give a current answer, complete with effective dates, and supporting links to IANA and the W3C.

Here are the official MIME types for Web Fonts:

Note there is a movement to change all the above to MIME types of font/XXX, as backed by the W3C in its proposal for WOFF v2. This is being tracked by the Internet Engineering Task Force (IETF) under The font Top Level Type and in February 2017 was approved RFC status (see RFC 8081) so it may all change yet!

While on the topic of web servers, it's worth mentioning that HTTP responses may gzip (or otherwise compress) all the above font formats except .woff & .woff2 which are already heavily compressed.

I say more in MIME Types for Web Fonts with (Fantom) BedSheet.

macro for Hide rows in excel 2010

You almost got it. You are hiding the rows within the active sheet. which is okay. But a better way would be add where it is.

Rows("52:55").EntireRow.Hidden = False

becomes

activesheet.Rows("52:55").EntireRow.Hidden = False

i've had weird things happen without it. As for making it automatic. You need to use the worksheet_change event within the sheet's macro in the VBA editor (not modules, double click the sheet1 to the far left of the editor.) Within that sheet, use the drop down menu just above the editor itself (there should be 2 listboxes). The listbox to the left will have the events you are looking for. After that just throw in the macro. It should look like the below code,

Private Sub Worksheet_Change(ByVal Target As Range)
test1
end Sub

That's it. Anytime you change something, it will run the macro test1.

Pointer to incomplete class type is not allowed

One thing to check for...

If your class is defined as a typedef:

typedef struct myclass { };

Then you try to refer to it as struct myclass anywhere else, you'll get Incomplete Type errors left and right. It's sometimes a mistake to forget the class/struct was typedef'ed. If that's the case, remove "struct" from:

typedef struct mystruct {}...

struct mystruct *myvar = value;

Instead use...

mystruct *myvar = value;

Common mistake.

How do I REALLY reset the Visual Studio window layout?

I tried most of the suggestions, and none of them worked. I didn't get a chance to try /resetuserdata. Finally I reinstalled the plugin and uninstalled it again, and the windows went away.

Measure execution time for a Java method

You might want to think about aspect-oriented programming. You don't want to litter your code with timings. You want to be able to turn them off and on declaratively.

If you use Spring, take a look at their MethodInterceptor class.

How to display images from a folder using php - PHP

Here is a possible solution the solution #3 on my comments to blubill's answer:

yourscript.php
========================
<?php
    $dir = '/home/user/Pictures';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if (file_exists($dir) == false) 
    {
        echo 'Directory "', $dir, '" not found!';
    } 
    else 
    {
        $dir_contents = scandir($dir);

        foreach ($dir_contents as $file) 
        {
            $file_type = strtolower(end(explode('.', $file)));
            if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true)     
            {
                $name = basename($file);
                echo "<img src='img.php?name={$name}' />";
            }
        }
    }
?>


img.php
========================
<?php
    $name = $_GET['name'];
    $mimes = array
    (
        'jpg' => 'image/jpg',
        'jpeg' => 'image/jpg',
        'gif' => 'image/gif',
        'png' => 'image/png'
    );

    $ext = strtolower(end(explode('.', $name)));

    $file = '/home/users/Pictures/'.$name;
    header('content-type: '. $mimes[$ext]);
    header('content-disposition: inline; filename="'.$name.'";');
    readfile($file);
?>

How to Round to the nearest whole number in C#

You have the Math.Round function that does exactly what you want.

Math.Round(1.1) results with 1
Math.Round(1.8) will result with 2.... and so one.

ggplot with 2 y axes on each side and different scales

We definitely could build a plot with dual Y-axises using base R funtion plot.

# pseudo dataset
df <- data.frame(x = seq(1, 1000, 1), y1 = sample.int(100, 1000, replace=T), y2 = sample(50, 1000, replace = T))

# plot first plot 
with(df, plot(y1 ~ x, col = "red"))

# set new plot
par(new = T) 

# plot second plot, but without axis
with(df, plot(y2 ~ x, type = "l", xaxt = "n", yaxt = "n", xlab = "", ylab = ""))

# define y-axis and put y-labs
axis(4)
with(df, mtext("y2", side = 4))

When should I use the Visitor Design Pattern?

As Konrad Rudolph already pointed out, it is suitable for cases where we need double dispatch

Here is an example to show a situation where we need double dispatch & how visitor helps us in doing so.

Example :

Lets say I have 3 types of mobile devices - iPhone, Android, Windows Mobile.

All these three devices have a Bluetooth radio installed in them.

Lets assume that the blue tooth radio can be from 2 separate OEMs – Intel & Broadcom.

Just to make the example relevant for our discussion, lets also assume that the APIs exposes by Intel radio are different from the ones exposed by Broadcom radio.

This is how my classes look –

enter image description here enter image description here

Now, I would like to introduce an operation – Switching On the Bluetooth on mobile device.

Its function signature should like something like this –

 void SwitchOnBlueTooth(IMobileDevice mobileDevice, IBlueToothRadio blueToothRadio)

So depending upon Right type of device and Depending upon right type of Bluetooth radio, it can be switched on by calling appropriate steps or algorithm.

In principal, it becomes a 3 x 2 matrix, where-in I’m trying to vector the right operation depending upon the right type of objects involved.

A polymorphic behaviour depending upon the type of both the arguments.

enter image description here

Now, Visitor pattern can be applied to this problem. Inspiration comes from the Wikipedia page stating – “In essence, the visitor allows one to add new virtual functions to a family of classes without modifying the classes themselves; instead, one creates a visitor class that implements all of the appropriate specializations of the virtual function. The visitor takes the instance reference as input, and implements the goal through double dispatch.”

Double dispatch is a necessity here due to the 3x2 matrix

Here is how the set up will look like - enter image description here

I wrote the example to answer another question, the code & its explanation is mentioned here.

Is there a JavaScript function that can pad a string to get to a determined length?

Here is a JavaScript function that adds specified number of paddings with custom symble. the function takes three parameters.

    padMe --> string or number to left pad
    pads  --> number of pads
    padSymble --> custom symble, default is "0" 

    function leftPad(padMe, pads, padSymble) {
         if( typeof padMe === "undefined") {
             padMe = "";
         }
         if (typeof pads === "undefined") {
             pads = 0;
         }
         if (typeof padSymble === "undefined") {
             padSymble = "0";
         }

         var symble = "";
         var result = [];
         for(var i=0; i < pads ; i++) {
            symble += padSymble;
         }
        var length = symble.length - padMe.toString().length;
        result = symble.substring(0, length);
        return result.concat(padMe.toString());
    }
/* Here are some results:

> leftPad(1)
"1"
> leftPad(1, 4)
"0001"
> leftPad(1, 4, "0")
"0001"
> leftPad(1, 4, "@")
"@@@1"

*/

How can you strip non-ASCII characters from a string? (in C#)

no need for regex. just use encoding...

sOutput = System.Text.Encoding.ASCII.GetString(System.Text.Encoding.ASCII.GetBytes(sInput));

Getting or changing CSS class property with Javascript using DOM style

As mentioned by Quynh Nguyen, you don't need the '.' in the className. However - document.getElementsByClassName('col1') will return an array of objects.

This will return an "undefined" value because an array doesn't have a class. You'll still need to loop through the array elements...

function changeBGColor() {
  var cols = document.getElementsByClassName('col1');
  for(i = 0; i < cols.length; i++) {
    cols[i].style.backgroundColor = 'blue';
  }
}

Extract Number from String in Python

You can filter the string by digits using str.isdigit method,

>>> int(filter(str.isdigit, str1))
3158

Change one value based on another value in pandas

df['FirstName']=df['ID'].apply(lambda x: 'Matt' if x==103 else '')
df['LastName']=df['ID'].apply(lambda x: 'Jones' if x==103 else '')

Flatten list of lists

>>> lis=[[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
>>> [x[0] for x in lis]
[180.0, 173.8, 164.2, 156.5, 147.2, 138.2]

Loop over array dimension in plpgsql

Since PostgreSQL 9.1 there is the convenient FOREACH:

DO
$do$
DECLARE
   m   varchar[];
   arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
      RAISE NOTICE 'another_func(%,%)',m[1], m[2];
   END LOOP;
END
$do$

Solution for older versions:

DO
$do$
DECLARE
   arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
   FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
   LOOP
      RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
   END LOOP;
END
$do$

Also, there is no difference between varchar[] and varchar[][] for the PostgreSQL type system. I explain in more detail here.

The DO statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql is the default (so you can omit the declaration).

key_load_public: invalid format

It seems that ssh cannot read your public key. But that doesn't matter.

You upload your public key to github, but you authenticate using your private key. See e.g. the FILES section in ssh(1).

How to change the text on the action bar

The best way to change the action bar name is to go to the AndroidManifest.xml and type this code.

<activity android:name=".YourActivity"
        android:label="NameYouWantToDisplay> </activity>

When to use <span> instead <p>?

A practical explanation: By default, <p> </p> will add line breaks before and after the enclosed text (so it creates a paragraph). <span> does not do this, that is why it is called inline.

How do I rename a column in a database table using SQL?

The standard would be ALTER TABLE, but that's not necessarily supported by every DBMS you're likely to encounter, so if you're looking for an all-encompassing syntax, you may be out of luck.

grep's at sign caught as whitespace

After some time with Google I asked on the ask ubuntu chat room.

A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:

grep -P "(^|\s)abc(\s|$)" gives the result I was looking for. -P is an experimental implementation of perl regexps.

grepping for abc and then using filters like grep -v '@abc' (this is far from perfect...) should also work, but my patch does something similar.

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

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

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

AttributeError: 'numpy.ndarray' object has no attribute 'append'

Use numpy.concatenate(list1 , list2) or numpy.append() Look into the thread at Append a NumPy array to a NumPy array.

Redirecting from cshtml page

Change to this:

@{ Response.Redirect("~/HOME/NoResults");}

Fragment MyFragment not attached to Activity

I faced similar issues when the application settings activity with the loaded preferences was visible. If I would change one of the preferences and then make the display content rotate and change the preference again, it would crash with a message that the fragment (my Preferences class) was not attached to an activity.

When debugging it looked like the onCreate() Method of the PreferencesFragment was being called twice when the display content rotated. That was strange enough already. Then I added the isAdded() check outside of the block where it would indicate the crash and it solved the issue.

Here is the code of the listener that updates the preferences summary to show the new entry. It is located in the onCreate() method of my Preferences class which extends the PreferenceFragment class:

public static class Preferences extends PreferenceFragment {
    SharedPreferences.OnSharedPreferenceChangeListener listener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // ...
        listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                // check if the fragment has been added to the activity yet (necessary to avoid crashes)
                if (isAdded()) {
                    // for the preferences of type "list" set the summary to be the entry of the selected item
                    if (key.equals(getString(R.string.pref_fileviewer_textsize))) {
                        ListPreference listPref = (ListPreference) findPreference(key);
                        listPref.setSummary("Display file content with a text size of " + listPref.getEntry());
                    } else if (key.equals(getString(R.string.pref_fileviewer_segmentsize))) {
                        ListPreference listPref = (ListPreference) findPreference(key);
                        listPref.setSummary("Show " + listPref.getEntry() + " bytes of a file at once");
                    }
                }
            }
        };
        // ...
    }

I hope this will help others!

How to change facebook login button with my custom image

Found a site on google explaining some changes, according to the author of the page fb does not allow custom buttons. Heres the website.

Unfortunately, it’s against Facebook’s developer policies, which state:

You must not circumvent our intended limitations on core Facebook features.

The Facebook Connect button is intended to be rendered in FBML, which means it’s only meant to look the way Facebook lets it.

How do I run a program from command prompt as a different user and as an admin

The easiest is to create a batch file (.bat) and run that as administrator.

Right click and 'Run as administrator'

how to count length of the JSON array element

Before going to answer read this Documentation once. Then you clearly understand the answer.

Try this It may work for you.

Object.keys(data.shareInfo[i]).length

Setting the character encoding in form submit for Internet Explorer

It seems that this can't be done, not at least with current versions of IE (6 and 7).

IE supports form attribute accept-charset, but only if its value is 'utf-8'.

The solution is to modify server A to produce encoding 'ISO-8859-1' for page that contains the form.

Using HTML data-attribute to set CSS background-image url

If you wanted to keep it with just HTML and CSS you can use CSS Variables. Keep in mind, css variables aren't supported in IE.

<div class="thumb" style="--background: url('images/img.jpg')"></div> 
.thumb {
    background-image: var(--background);
}

Codepen: https://codepen.io/bruce13/pen/bJdoZW

Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?

This can be done simply by using from_records of pandas DataFrame

import numpy as np
import pandas as pd
# Creating a numpy array
x = np.arange(1,10,1).reshape(-1,1)
dataframe = pd.DataFrame.from_records(x)

Integrating Dropzone.js into existing HTML form with other fields

I have a more automated solution for this.

HTML:

<form role="form" enctype="multipart/form-data" action="{{ $url }}" method="{{ $method }}">
    {{ csrf_field() }}

    <!-- You can add extra form fields here -->

    <input hidden id="file" name="file"/>

    <!-- You can add extra form fields here -->

    <div class="dropzone dropzone-file-area" id="fileUpload">
        <div class="dz-default dz-message">
            <h3 class="sbold">Drop files here to upload</h3>
            <span>You can also click to open file browser</span>
        </div>
    </div>

    <!-- You can add extra form fields here -->

    <button type="submit">Submit</button>
</form>

JavaScript:

Dropzone.options.fileUpload = {
    url: 'blackHole.php',
    addRemoveLinks: true,
    accept: function(file) {
        let fileReader = new FileReader();

        fileReader.readAsDataURL(file);
        fileReader.onloadend = function() {

            let content = fileReader.result;
            $('#file').val(content);
            file.previewElement.classList.add("dz-success");
        }
        file.previewElement.classList.add("dz-complete");
    }
}

Laravel:

// Get file content
$file = base64_decode(request('file'));

No need to disable DropZone Discovery and the normal form submit will be able to send the file with any other form fields through standard form serialization.

This mechanism stores the file contents as base64 string in the hidden input field when it gets processed. You can decode it back to binary string in PHP through the standard base64_decode() method.

I don't know whether this method will get compromised with large files but it works with ~40MB files.

Run a mySQL query as a cron job?

It depends on what runs cron on your system, but all you have to do to run a php script from cron is to do call the location of the php installation followed by the script location. An example with crontab running every hour:

# crontab -e
00 * * * * /usr/local/bin/php /home/path/script.php

On my system, I don't even have to put the path to the php installation:

00 * * * * php /home/path/script.php

On another note, you should not be using mysql extension because it is deprecated, unless you are using an older installation of php. Read here for a comparison.

how to fix groovy.lang.MissingMethodException: No signature of method:

Because you are passing three arguments to a four arguments method. Also, you are not using the passed closure.

If you want to specify the operations to be made on top of the source contents, then use a closure. It would be something like this:

def copyAndReplaceText(source, dest, closure){
    dest.write(closure( source.text ))
}

// And you can keep your usage as:
copyAndReplaceText(source, dest){
    it.replaceAll('Visa', 'Passport!!!!')
}

If you will always swap strings, pass both, as your method signature already states:

def copyAndReplaceText(source, dest, targetText, replaceText){
    dest.write(source.text.replaceAll(targetText, replaceText))
}

copyAndReplaceText(source, dest, 'Visa', 'Passport!!!!')

MySQL high CPU usage

As this is the top post if you google for MySQL high CPU usage or load, I'll add an additional answer:

On the 1st of July 2012, a leap second was added to the current UTC-time to compensate for the slowing rotation of the earth due to the tides. When running ntp (or ntpd) this second was added to your computer's/server's clock. MySQLd does not seem to like this extra second on some OS'es, and yields a high CPU load. The quick fix is (as root):

$ /etc/init.d/ntpd stop
$ date -s "`date`"
$ /etc/init.d/ntpd start

import an array in python

(I know the question is old, but I think this might be good as a reference for people with similar questions)

If you want to load data from an ASCII/text file (which has the benefit or being more or less human-readable and easy to parse in other software), numpy.loadtxt is probably what you want:

If you just want to quickly save and load numpy arrays/matrices to and from a file, take a look at numpy.save and numpy.load:

Why do we check up to the square root of a prime number to determine if it is prime?

It's all really just basic uses of Factorization and Square Roots.

It may appear to be abstract, but in reality it simply lies with the fact that a non-prime-number's maximum possible factorial would have to be its square root because:

sqrroot(n) * sqrroot(n) = n.

Given that, if any whole number above 1 and below or up to sqrroot(n) divides evenly into n, then n cannot be a prime number.

Pseudo-code example:

i = 2;

is_prime = true;

while loop (i <= sqrroot(n))
{
  if (n % i == 0)
  {
    is_prime = false;
    exit while;
  }
  ++i;
}

R - argument is of length zero in if statement

You can use isTRUE for such cases. isTRUE is the same as { is.logical(x) && length(x) == 1 && !is.na(x) && x }

If you use shiny there you could use isTruthy which covers the following cases:

  • FALSE

  • NULL

  • ""

  • An empty atomic vector

  • An atomic vector that contains only missing values

  • A logical vector that contains all FALSE or missing values

  • An object of class "try-error"

  • A value that represents an unclicked actionButton()

Is it possible to use a div as content for Twitter's Popover

here is an another example

<a   data-container = "body" data-toggle = "popover" data-placement = "left" 
    data-content = "&lt;img src='<?php echo baseImgUrl . $row1[2] ?>' width='250' height='100' &gt;&lt;div&gt;&lt;h3&gt; <?php echo $row1['1'] ?>&lt/h3&gt; &lt;p&gt; &lt;span&gt;<?php echo $countsss ?>videos &lt;/span&gt;
&lt;span&gt;<?php echo $countsss1 ?> followers&lt;/span&gt;
&lt;/p&gt;&lt;/div&gt;
<?php echo $row1['4'] ?>   &lt;hr&gt;&lt;div&gt;
&lt;span&gt; &lt;button type='button' class='btn btn-default pull-left green'&gt;Follow  &lt;/button&gt;  &lt;/span&gt; &lt;span&gt; &lt;button type='button' class='btn btn-default pull-left green'&gt; Go to channel page&lt;/button&gt;   &lt;/span&gt;&lt;span&gt; &lt;button type='button' class='btn btn-default pull-left green'&gt;Close  &lt;/button&gt;  &lt;/span&gt;

 &lt;/div&gt;">

<?php echo $row1['1'] ?>
  </a>

Dynamically Add Images React Webpack

Using url-loader, described here (SurviveJS - Loading Images), you can then use in your code :

import LogoImg from 'YOUR_PATH/logo.png';

and

<img src={LogoImg}/>

Edit: a precision, images are inlined in the js archive with this technique. It can be worthy for small images, but use the technique wisely.

"webxml attribute is required" error in Maven

If you change the default project path, you must specify the location of the web.xml file, for example:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.5</version>
            <configuration>
                <webXml>src\main\web\WEB-INF\web.xml</webXml>
            </configuration>
        </plugin>

How often does python flush to a file?

For file operations, Python uses the operating system's default buffering unless you configure it do otherwise. You can specify a buffer size, unbuffered, or line buffered.

For example, the open function takes a buffer size argument.

http://docs.python.org/library/functions.html#open

"The optional buffering argument specifies the file’s desired buffer size:"

  • 0 means unbuffered,
  • 1 means line buffered,
  • any other positive value means use a buffer of (approximately) that size.
  • A negative buffering means to use the system default, which is usually line buffered for tty devices and fully buffered for other files.
  • If omitted, the system default is used.

code:

bufsize = 0
f = open('file.txt', 'w', buffering=bufsize)

How to increase buffer size in Oracle SQL Developer to view all records?

Select Tools > Preferences > Database / Advanced

There is an input field for Sql Array Fetch Size but it only allows setting a max of 500 rows.

Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

Try adding an extension like this:

    public extension UIDevice {

    var modelName: String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8 where value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }

        switch identifier {
        case "iPod5,1":                                 return "iPod Touch 5"
        case "iPod7,1":                                 return "iPod Touch 6"
        case "iPhone3,1", "iPhone3,2", "iPhone3,3":     return "iPhone 4"
        case "iPhone4,1":                               return "iPhone 4s"
        case "iPhone5,1", "iPhone5,2":                  return "iPhone 5"
        case "iPhone5,3", "iPhone5,4":                  return "iPhone 5c"
        case "iPhone6,1", "iPhone6,2":                  return "iPhone 5s"
        case "iPhone7,2":                               return "iPhone 6"
        case "iPhone7,1":                               return "iPhone 6 Plus"
        case "iPhone8,1":                               return "iPhone 6s"
        case "iPhone8,2":                               return "iPhone 6s Plus"
        case "iPhone9,1", "iPhone9,3":                  return "iPhone 7"
        case "iPhone9,2", "iPhone9,4":                  return "iPhone 7 Plus"
        case "iPhone8,4":                               return "iPhone SE"
        case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
        case "iPad3,1", "iPad3,2", "iPad3,3":           return "iPad 3"
        case "iPad3,4", "iPad3,5", "iPad3,6":           return "iPad 4"
        case "iPad4,1", "iPad4,2", "iPad4,3":           return "iPad Air"
        case "iPad5,3", "iPad5,4":                      return "iPad Air 2"
        case "iPad2,5", "iPad2,6", "iPad2,7":           return "iPad Mini"
        case "iPad4,4", "iPad4,5", "iPad4,6":           return "iPad Mini 2"
        case "iPad4,7", "iPad4,8", "iPad4,9":           return "iPad Mini 3"
        case "iPad5,1", "iPad5,2":                      return "iPad Mini 4"
        case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8":return "iPad Pro"
        case "AppleTV5,3":                              return "Apple TV"
        case "i386", "x86_64":                          return "Simulator"
        default:                                        return identifier
        }
    }

}

This is how you will use it:

let modelName = UIDevice.currentDevice().modelName

EDIT For simulator, you can try a solution here

Is <div style="width: ;height: ;background: "> CSS?

1)Yes it is, when there is style then it is styling your code(css).2) is belong to html it is like a container that keep your css.

How do I get class name in PHP?

<?php
namespace CMS;
class Model {
  const _class = __CLASS__;
}

echo Model::_class; // will return 'CMS\Model'

for older than PHP 5.5

how to dynamically add options to an existing select in vanilla javascript

.add() also works.

var daySelect = document.getElementById("myDaySelect");
var myOption = document.createElement("option");
myOption.text = "test";
myOption.value = "value";
daySelect.add(option);

W3 School - try

Find a row in dataGridView based on column and value

Those who use WPF

for (int i = 0; i < dataGridName.Items.Count; i++)
{
      string cellValue= ((DataRowView)dataGridName.Items[i]).Row["columnName"].ToString();                
      if (cellValue.Equals("Search_string")) // check the search_string is present in the row of ColumnName
      {
         object item = dataGridName.Items[i];
         dataGridName.SelectedItem = item; // selecting the row of dataGridName
         dataGridName.ScrollIntoView(item);                    
         break;
      }
}

if you want to get the selected row items after this, the follwing code snippet is helpful

DataRowView drv = dataGridName.SelectedItem as DataRowView;
DataRow dr = drv.Row;
string item1= Convert.ToString(dr.ItemArray[0]);// get the first column value from selected row 
string item2= Convert.ToString(dr.ItemArray[1]);// get the second column value from selected row 

Regex to replace everything except numbers and a decimal point

Check the link Regular Expression Demo

use the below reg exp

[a-z] + [^0-9\s.]+|.(?!\d)

JQuery Ajax POST in Codeigniter

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class UserController extends CI_Controller {

        public function verifyUser()    {
            $userName =  $_POST['userName'];
            $userPassword =  $_POST['userPassword'];
            $status = array("STATUS"=>"false");
            if($userName=='admin' && $userPassword=='admin'){
                $status = array("STATUS"=>"true");  
            }
            echo json_encode ($status) ;    
        }
    }


function makeAjaxCall(){
    $.ajax({
        type: "post",
        url: "http://localhost/CodeIgnitorTutorial/index.php/usercontroller/verifyUser",
        cache: false,               
        data: $('#userForm').serialize(),
        success: function(json){                        
        try{        
            var obj = jQuery.parseJSON(json);
            alert( obj['STATUS']);


        }catch(e) {     
            alert('Exception while request..');
        }       
        },
        error: function(){                      
            alert('Error while request..');
        }
 });
}

How to change the minSdkVersion of a project?

In your app/build.gradle file, you can set the minSdkVersion inside defaultConfig.

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.name.app"
        minSdkVersion 19    // This over here
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }

Javascript: formatting a rounded number to N decimals

I think that there is a more simple approach to all given here, and is the method Number.toFixed() already implemented in JavaScript.

simply write:

var myNumber = 2;

myNumber.toFixed(2); //returns "2.00"
myNumber.toFixed(1); //returns "2.0"

etc...

Procedure expects parameter which was not supplied

First - why is that an EXEC? Shouldn't that just be

AS
SELECT Column_Name, ...
FROM ...
WHERE TABLE_NAME = @template

The current SP doesn't make sense? In particular, that would look for a column matching @template, not the varchar value of @template. i.e. if @template is 'Column_Name', it would search WHERE TABLE_NAME = Column_Name, which is very rare (to have table and column named the same).

Also, if you do have to use dynamic SQL, you should use EXEC sp_ExecuteSQL (keeping the values as parameters) to prevent from injection attacks (rather than concatenation of input). But it isn't necessary in this case.

Re the actual problem - it looks OK from a glance; are you sure you don't have a different copy of the SP hanging around? This is a common error...

Can I get Unix's pthread.h to compile in Windows?

Just pick up the TDM-GCC 64x package. (It constains both the 32 and 64 bit versions of the MinGW toolchain and comes within a neat installer.) More importantly, it contains something called the "winpthread" library.

It comprises of the pthread.h header, libwinpthread.a, libwinpthread.dll.a static libraries for both 32-bit and 64-bit and the required .dlls libwinpthread-1.dll and libwinpthread_64-1.dll(this, as of 01-06-2016).

You'll need to link to the libwinpthread.a library during build. Other than that, your code can be the same as for native Pthread code on Linux. I've so far successfully used it to compile a few basic Pthread programs in 64-bit on windows.

Alternatively, you can use the following library which wraps the windows threading API into the pthreads API: pthreads-win32.

The above two seem to be the most well known ways for this.

Hope this helps.

Print new output on same line

Similar to what has been suggested, you can do:

print(i, end=',')

Output: 0,1,2,3,

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

Here is how the default implementation (ASP.NET Framework or ASP.NET Core) works. It uses a Key Derivation Function with random salt to produce the hash. The salt is included as part of the output of the KDF. Thus, each time you "hash" the same password you will get different hashes. To verify the hash the output is split back to the salt and the rest, and the KDF is run again on the password with the specified salt. If the result matches to the rest of the initial output the hash is verified.

Hashing:

public static string HashPassword(string password)
{
    byte[] salt;
    byte[] buffer2;
    if (password == null)
    {
        throw new ArgumentNullException("password");
    }
    using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8))
    {
        salt = bytes.Salt;
        buffer2 = bytes.GetBytes(0x20);
    }
    byte[] dst = new byte[0x31];
    Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
    Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
    return Convert.ToBase64String(dst);
}

Verifying:

public static bool VerifyHashedPassword(string hashedPassword, string password)
{
    byte[] buffer4;
    if (hashedPassword == null)
    {
        return false;
    }
    if (password == null)
    {
        throw new ArgumentNullException("password");
    }
    byte[] src = Convert.FromBase64String(hashedPassword);
    if ((src.Length != 0x31) || (src[0] != 0))
    {
        return false;
    }
    byte[] dst = new byte[0x10];
    Buffer.BlockCopy(src, 1, dst, 0, 0x10);
    byte[] buffer3 = new byte[0x20];
    Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
    using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
    {
        buffer4 = bytes.GetBytes(0x20);
    }
    return ByteArraysEqual(buffer3, buffer4);
}

Change a web.config programmatically with C# (.NET)

Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
//section.SectionInformation.UnprotectSection();
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
config.Save();

Running MSBuild fails to read SDKToolsPath

Short answer: In the .csproj file, there is a way to specify the path to sgen.exe, using SGenToolPath:

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="14.0">
  <PropertyGroup>
    <SGenToolPath>C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools</SGenToolPath>
  </PropertyGroup>

Your path may be different, but SGenToolPath is what you want.

For a list of other common MSBuild Project properties, see: https://msdn.microsoft.com/en-us/library/bb629394.aspx

We ended up using this SGenToolPath setting in the .csproj file, instead of editing the registry values on the build server. Editing the registry values on my local machine had worked as well, but was a bit more complicated and we didn't want to mess with the registry on the build server.

For the registry: In that case the problem was that the SDK40ToolsPath(s) under HKLM\SOFTWARE\Wow6432Node\Microsoft\MSBuild were pointing to a registry value $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.0A\WinSDK-NetFx40Tools-x86@InstallationFolder) which did not exist. I just replaced that with the actual path directly.

UUID max character length

Section 3 of RFC4122 provides the formal definition of UUID string representations. It's 36 characters (32 hex digits + 4 dashes).

Sounds like you need to figure out where the invalid 60-char IDs are coming from and decide 1) if you want to accept them, and 2) what the max length of those IDs might be based on whatever API is used to generate them.

How to filter WooCommerce products by custom attribute

You can use the WooCommerce Layered Nav widget, which allows you to use different sets of attributes as filters for products. Here's the "official" description:

Shows a custom attribute in a widget which lets you narrow down the list of products when viewing product categories.

If you look into plugins/woocommerce/widgets/widget-layered_nav.php, you can see the way it operates with the attributes in order to set filters. The URL then looks like this:

http://yoursite.com/shop/?filtering=1&filter_min-kvadratura=181&filter_max-kvadratura=108&filter_obem-ohlajdane=111

... and the digits are actually the id-s of the different attribute values, that you want to set.

Import/Index a JSON file into Elasticsearch

One thing I've not seen anyone mention: the JSON file must have one line specifying the index the next line belongs to, for every line of the "pure" JSON file.

I.E.

{"index":{"_index":"shakespeare","_type":"act","_id":0}}
{"line_id":1,"play_name":"Henry IV","speech_number":"","line_number":"","speaker":"","text_entry":"ACT I"}

Without that, nothing works, and it won't tell you why

matplotlib: how to draw a rectangle on image

You need use patches.

import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig2 = plt.figure()
ax2 = fig2.add_subplot(111, aspect='equal')

ax2.add_patch(
     patches.Rectangle(
        (0.1, 0.1),
        0.5,
        0.5,
        fill=False      # remove background
     ) ) 
fig2.savefig('rect2.png', dpi=90, bbox_inches='tight')

Put spacing between divs in a horizontal row?

I would suggest making the divs a little smaller and adding a margin of a percentage.

_x000D_
_x000D_
<div style="width:100%; height: 200px; background-color: grey;">_x000D_
  <div style="width: 23%; float:left; margin: 1%; background-color: red;">A</div>_x000D_
  <div style="width: 23%; float:left; margin: 1%; background-color: orange;">B</div>_x000D_
  <div style="width: 23%; float:left; margin: 1%; background-color: green;">C</div>_x000D_
  <div style="width: 23%; float:left; margin: 1%; background-color: blue;">D</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/YJT7q/

What is the difference between public, protected, package-private and private in Java?

The difference can be found in the links already provided but which one to use usually comes down to the "Principle of Least Knowledge". Only allow the least visibility that is needed.

How do you push a tag to a remote repository using Git?

To push specific, one tag do following git push origin tag_name

Remove special symbols and extra spaces and replace with underscore using the replace method

Your regular expression [^a-zA-Z0-9]\s/g says match any character that is not a number or letter followed by a space.

Remove the \s and you should get what you are after if you want a _ for every special character.

var newString = str.replace(/[^A-Z0-9]/ig, "_");

That will result in hello_world___hello_universe

If you want it to be single underscores use a + to match multiple

var newString = str.replace(/[^A-Z0-9]+/ig, "_");

That will result in hello_world_hello_universe

Android Studio: Application Installation Failed

Uninstalling from AVD worked for me. After reinstalling it worked

Android: How to open a specific folder via Intent and show its content in a file browser?

This should work:

Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + "/myFolder/");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "resource/folder");

if (intent.resolveActivityInfo(getPackageManager(), 0) != null)
{
    startActivity(intent);
}
else
{
    // if you reach this place, it means there is no any file 
    // explorer app installed on your device
}

Please, be sure that you have any file explorer app installed on your device.

EDIT: added a shantanu's recommendation from the comment.

LIBRARIES: You can also have a look at the following libraries https://android-arsenal.com/tag/35 if the current solution doesn't help you.

Converting bool to text in C++

With C++11 you might use a lambda to get a slightly more compact code and in place usage:

bool to_convert{true};
auto bool_to_string = [](bool b) -> std::string {
    return b ? "true" : "false";
};
std::string str{"string to print -> "};
std::cout<<str+bool_to_string(to_convert);

Prints:

string to print -> true

Understanding the grid classes ( col-sm-# and col-lg-# ) in Bootstrap 3

This might be late as I think most of us are using BS4. This article explained all the questions you asked in a detailed and simple manner also includes what to do when. The detailed guide to use bs4 or bootstrap

https://uxplanet.org/how-the-bootstrap-4-grid-works-a1b04703a3b7

Error running android: Gradle project sync failed. Please fix your project and try again

It was yelling at me about a line in my xml file (which was perfectly valid and never had problems the entire time I've worked on the project). I deleted the line and even after running again and cleaning and rebuilding it kept yelling at me about the completely blank line. I restarted android studio and removed the .gradle folder and it finally worked. Hopefully someone in my shoes that had all of the other answers in this thread fail them will see this answer and save a few hours.

I had this problem (clicked a prompt to "sync with gradle" on my perfectly valid and working project and it killed everything) and I researched for hours trying to figure out how to fix this, including this thread among many others. I finally found my solution, so hopefully, it'll help somebody (and hopefully they fix this terrible system)

Argument list too long error for rm, cp, mv commands

To delete all *.pdf in a directory /path/to/dir_with_pdf_files/

mkdir empty_dir        # Create temp empty dir

rsync -avh --delete --include '*.pdf' empty_dir/ /path/to/dir_with_pdf_files/

To delete specific files via rsync using wildcard is probably the fastest solution in case you've millions of files. And it will take care of error you're getting.


(Optional Step): DRY RUN. To check what will be deleted without deleting. `

rsync -avhn --delete --include '*.pdf' empty_dir/ /path/to/dir_with_pdf_files/

. . .

Click rsync tips and tricks for more rsync hacks

Where are Magento's log files located?

These code lines can help you quickly enable log setting in your magento site.

INSERT INTO `core_config_data` (`config_id`, `scope`, `scope_id`, `path`, `value`) VALUES
('', 'default', 0, 'dev/log/active', '1'),
('', 'default', 0, 'dev/log/file', 'system.log'),
('', 'default', 0, 'dev/log/exception_file', 'exception.log');

Then you can see them inside the folder: /var/log under root installation.

More detail in this blog

How to use the TextWatcher class in Android?

Create custom TextWatcher subclass:

public class CustomWatcher implements TextWatcher {

    private boolean mWasEdited = false;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

        if (mWasEdited){

            mWasEdited = false;
            return;
        }

        // get entered value (if required)
        String enteredValue  = s.toString();

        String newValue = "new value";

        // don't get trap into infinite loop
        mWasEdited = true;
        // just replace entered value with whatever you want
        s.replace(0, s.length(), newValue);

    }
}

Set listener for your EditText:

mTargetEditText.addTextChangedListener(new CustomWatcher());

Plotting multiple curves same graph and same scale

I'm not sure what you want, but i'll use lattice.

x = rep(x,2)
y = c(y1,y2)
fac.data = as.factor(rep(1:2,each=5))
df = data.frame(x=x,y=y,z=fac.data)
# this create a data frame where I have a factor variable, z, that tells me which data I have (y1 or y2)

Then, just plot

xyplot(y ~x|z, df)
# or maybe
xyplot(x ~y|z, df)

Parse json string using JSON.NET

If your keys are dynamic I would suggest deserializing directly into a DataTable:

    class SampleData
    {
        [JsonProperty(PropertyName = "items")]
        public System.Data.DataTable Items { get; set; }
    }

    public void DerializeTable()
    {
        const string json = @"{items:["
            + @"{""Name"":""AAA"",""Age"":""22"",""Job"":""PPP""},"
            + @"{""Name"":""BBB"",""Age"":""25"",""Job"":""QQQ""},"
            + @"{""Name"":""CCC"",""Age"":""38"",""Job"":""RRR""}]}";
        var sampleData = JsonConvert.DeserializeObject<SampleData>(json);
        var table = sampleData.Items;

        // write tab delimited table without knowing column names
        var line = string.Empty;
        foreach (DataColumn column in table.Columns)            
            line += column.ColumnName + "\t";                       
        Console.WriteLine(line);

        foreach (DataRow row in table.Rows)
        {
            line = string.Empty;
            foreach (DataColumn column in table.Columns)                
                line += row[column] + "\t";                                   
            Console.WriteLine(line);
        }

        // Name   Age   Job    
        // AAA    22    PPP    
        // BBB    25    QQQ    
        // CCC    38    RRR    
    }

You can determine the DataTable column names and types dynamically once deserialized.

How to deal with the URISyntaxException

A space is encoded to %20 in URLs, and to + in forms submitted data (content type application/x-www-form-urlencoded). You need the former.

Using Guava:

dependencies {
     compile 'com.google.guava:guava:28.1-jre'
}

You can use UrlEscapers:

String encodedString = UrlEscapers.urlFragmentEscaper().escape(inputString);

Don't use String.replace, this would only encode the space. Use a library instead.

How can I hide a TD tag using inline JavaScript or CSS?

<td style = "display:none" >
<p> Content display none </p>
</td>

or

<td style="visibility:hidden"> Your content is hidden </td>

Notice that: 2 those ways are differnce. You should try it to check the result.

Load content of a div on another page

You just need to add a jquery selector after the url.

See: http://api.jquery.com/load/

Example straight from the API:

$('#result').load('ajax/test.html #container');

So what that does is it loads the #container element from the specified url.

Use String.split() with multiple delimiters

You can use the regex "\W".This matches any non-word character.The required line would be:

String[] tokens=pdfName.split("\\W");

Eclipse Java error: This selection cannot be launched and there are no recent launches

Have you checked if:

  1. You created a class file under src folder in your JAVA project?(not file)
  2. Did you name your class as the same name of your class file?

I am a newbie who try to run a helloworld example and just got the same error as yours, and these work for me.

How to make div go behind another div?

To answer the question in a general manner:

Using z-index will allow you to control this. see z-index at csstricks.

The element of higher z-index will be displayed on top of elements of lower z-index.

For instance, take the following HTML:

<div id="first">first</div>
<div id="second">second</div>

If I have the following CSS:

#first {
    position: fixed;
    z-index: 2;
}

#second {
    position: fixed;
    z-index: 1;
}

#first wil be on top of #second.

But specifically in your case:

The div element is a child of the div that you wish to put in front. This is not logically possible.

How to parse a JSON string into JsonNode in Jackson?

Richard's answer is correct. Alternatively you can also create a MappingJsonFactory (in org.codehaus.jackson.map) which knows where to find ObjectMapper. The error you got was because the regular JsonFactory (from core package) has no dependency to ObjectMapper (which is in the mapper package).

But usually you just use ObjectMapper and do not worry about JsonParser or other low level components -- they will just be needed if you want to data-bind parts of stream, or do low-level handling.

Simulate limited bandwidth from within Chrome?

Note, do not use Chrome's built in Speed Tester (it will show you unthrottled speed). Instead use another site, like Fast.com. That will show you properly throttled speeds.

Also, the throttling settings might be hidden and can be accessed from the network bar by clicking the tiny down arrow.

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

Adobe Flash Builder 4.6 Read Me.pdf recommendeds that you edit the eclipse.ini file for your Eclipse instance, so that it includes the following settings:

-vmargs -Xms256m -Xmx512m -XX:MaxPermSize=256m -XX:PermSize=64m

Force an SVN checkout command to overwrite current files

svn checkout --force svn://repo website.dir

then

svn revert -R website.dir

Will check out on top of existing files in website.dir, but not overwrite them. Then the revert will overwrite them. This way you do not need to take the site down to complete it.

How to obtain Telegram chat_id for a specific user?

Using the Perl API you can get it this way: first you send a message to the bot from Telegram, then issue a getUpdates and the chat id must be there:

#!/usr/bin/perl

use Data::Dumper;
use WWW::Telegram::BotAPI;

my $TOKEN = 'blablabla';
my $api = WWW::Telegram::BotAPI->new (
    token => $TOKEN
) or die "I can't connect";

my $out = $api->api_request ('getUpdates');
warn Dumper($out);
my $chat_id = $out->{result}->[0]->{message}->{chat}->{id};
print "chat_id=$chat_id\n";

The id should be in chat_id but it may depend of the result, so I also added a dump of the whole result.

You can install the Perl API from https://github.com/Robertof/perl-www-telegram-botapi. It depends on your system but I installed easily running this on my Linux server:

$ sudo cpan WWW::Telegram::BotAPI

Hope this helps

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

Forcing the TCP/IP connection (by providing 127.0.0.1 instead of localhost or .) can reveal the real reason for the error. In my case, the database name specified in connection string was incorrect.

So, here is the checklist so far:

  • Make sure Named Pipe is enabled in configuration manager (don't forget to restart the server).
  • Make sure SQL Server Authentication (or Mixed Mode) is enabled.
  • Make sure your user name and password are correct.
  • Make sure the database you are connecting to exists.

Best practice when adding whitespace in JSX

use {} or {``} or &nbsp; to create space between span element and content.

<b> {notif.name} </b> <span id="value"> &nbsp;{ notif.count }{``} </span>

How do you echo a 4-digit Unicode character in Bash?

Quick one-liner to convert UTF-8 characters into their 3-byte format:

var="$(echo -n '?' | od -An -tx1)"; printf '\\x%s' ${var^^}; echo

How do I create a HTTP Client Request with a cookie?

This answer is deprecated, please see @ankitjaininfo's answer below for a more modern solution


Here's how I think you make a POST request with data and a cookie using just the node http library. This example is posting JSON, set your content-type and content-length accordingly if you post different data.

// NB:- node's http client API has changed since this was written
// this code is for 0.4.x
// for 0.6.5+ see http://nodejs.org/docs/v0.6.5/api/http.html#http.request

var http = require('http');

var data = JSON.stringify({ 'important': 'data' });
var cookie = 'something=anything'

var client = http.createClient(80, 'www.example.com');

var headers = {
    'Host': 'www.example.com',
    'Cookie': cookie,
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(data,'utf8')
};

var request = client.request('POST', '/', headers);

// listening to the response is optional, I suppose
request.on('response', function(response) {
  response.on('data', function(chunk) {
    // do what you do
  });
  response.on('end', function() {
    // do what you do
  });
});
// you'd also want to listen for errors in production

request.write(data);

request.end();

What you send in the Cookie value should really depend on what you received from the server. Wikipedia's write-up of this stuff is pretty good: http://en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes

Append a Lists Contents to another List C#

Try AddRange-method:

GlobalStrings.AddRange(localStrings);

Delete all lines starting with # or ; in Notepad++

In Notepad++, you can use the Mark tab in the Find dialogue to Bookmark all lines matching your query which can be regex or normal (wildcard).

Then use Search > Bookmark > Remove Bookmarked Lines.

Logging in Scala

Don't use Logula

I've actually followed the recommendation of Eugene and tried it and found out that it has a clumsy configuration and is subjected to bugs, which don't get fixed (such as this one). It doesn't look to be well maintained and it doesn't support Scala 2.10.

Use slf4s + slf4j-simple

Key benefits:

  • Supports latest Scala 2.10 (to date it's M7)
  • Configuration is versatile but couldn't be simpler. It's done with system properties, which you can set either by appending something like -Dorg.slf4j.simplelogger.defaultlog=trace to execution command or hardcode in your script: System.setProperty("org.slf4j.simplelogger.defaultlog", "trace"). No need to manage trashy config files!
  • Fits nicely with IDEs. For instance to set the logging level to "trace" in a specific run configuration in IDEA just go to Run/Debug Configurations and add -Dorg.slf4j.simplelogger.defaultlog=trace to VM options.
  • Easy setup: just drop in the dependencies from the bottom of this answer

Here's what you need to be running it with Maven:

<dependency>
  <groupId>com.weiglewilczek.slf4s</groupId>
  <artifactId>slf4s_2.9.1</artifactId>
  <version>1.0.7</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-simple</artifactId>
  <version>1.6.6</version>
</dependency>

How to change dot size in gnuplot

The pointsize command scales the size of points, but does not affect the size of dots.

In other words, plot ... with points ps 2 will generate points of twice the normal size, but for plot ... with dots ps 2 the "ps 2" part is ignored.

You could use circular points (pt 7), which look just like dots.

How do I determine if my python shell is executing in 32bit or 64bit?

For a non-programmatic solution, look in the Activity Monitor. It lists the architecture of 64-bit processes as “Intel (64-bit)”.

How to get process ID of background process?

You can use the jobs -l command to get to a particular jobL

^Z
[1]+  Stopped                 guard

my_mac:workspace r$ jobs -l
[1]+ 46841 Suspended: 18           guard

In this case, 46841 is the PID.

From help jobs:

-l Report the process group ID and working directory of the jobs.

jobs -p is another option which shows just the PIDs.

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

if you wanna ng-model value, if you can write like this in the triggered event: $scope.searchText

How to create .pfx file from certificate and private key?

I created .pfx file from .key and .pem files.

Like this openssl pkcs12 -inkey rootCA.key -in rootCA.pem -export -out rootCA.pfx

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

Delete .android folder cache files, Also delete the build folder manually from a directory and open android studio and run again.

enter image description here

Insert data using Entity Framework model

I'm using EF6, and I find something strange,

Suppose Customer has constructor with parameter ,

if I use new Customer(id, "name"), and do

 using (var db = new EfContext("name=EfSample"))
 {
    db.Customers.Add( new Customer(id, "name") );
    db.SaveChanges();
 }

It run through without error, but when I look into the DataBase, I find in fact that the data Is NOT be Inserted,

But if I add the curly brackets, use new Customer(id, "name"){} and do

 using (var db = new EfContext("name=EfSample"))
 {
    db.Customers.Add( new Customer(id, "name"){} );
    db.SaveChanges();
 }

the data will then actually BE Inserted,

seems the Curly Brackets make the difference, I guess that only when add Curly Brackets, entity framework will recognize this is a real concrete data.

Fit Image in ImageButton in Android

I'm using android:scaleType="fitCenter" with satisfaction.

How to switch a user per task or set of tasks?

A solution is to use the include statement with remote_user var (describe there : http://docs.ansible.com/playbooks_roles.html) but it has to be done at playbook instead of task level.

ASP.NET IIS Web.config [Internal Server Error]

I had the same problem. Don't remember where I found it on the web, but here is what I did:

Click "Start button"

in the search box, enter "Turn windows features on or off"

in the features window, Click: "Internet Information Services"

Click: "World Wide Web Services"

Click: "Application Development Features"

Check (enable) the features. I checked all but CGI.

IIS - this configuration section cannot be used at this path (configuration locking?)

Freezing Row 1 and Column A at the same time

Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.

For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".

Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html

Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx

What is the difference between id and class in CSS, and when should I use them?

A simple way to look at it is that an id is unique to only one element.

A class is not unique and applied to multiple elements.

For example:

<p class = "content">This is some random <strong id="veryImportant"> stuff!</strong></p>

Content is a class since it'll probably apply to some other tags aswell where as "veryImportant" is only being used once and never again.

ValueError: unconverted data remains: 02:05

Best answer is to use the from dateutil import parser.

usage:

from dateutil import parser
datetime_obj = parser.parse('2018-02-06T13:12:18.1278015Z')
print datetime_obj
# output: datetime.datetime(2018, 2, 6, 13, 12, 18, 127801, tzinfo=tzutc())

How do I detect a click outside an element?

I ended up doing something like this:

$(document).on('click', 'body, #msg_count_results .close',function() {
    $(document).find('#msg_count_results').remove();
});
$(document).on('click','#msg_count_results',function(e) {
    e.preventDefault();
    return false;
});

I have a close button within the new container for end users friendly UI purposes. I had to use return false in order to not go through. Of course, having an A HREF on there to take you somewhere would be nice, or you could call some ajax stuff instead. Either way, it works ok for me. Just what I wanted.

Adding a directory to the PATH environment variable in Windows

Option 1

After you change PATH with the GUI, close and re-open the console window.

This works because only programs started after the change will see the new PATH.

Option 2

Execute this command in the command window you have open:

set PATH=%PATH%;C:\your\path\here\

This command appends C:\your\path\here\ to the current PATH.

Breaking it down:

  • set – A command that changes cmd's environment variables only for the current cmd session; other programs and the system are unaffected.
  • PATH= – Signifies that PATH is the environment variable to be temporarily changed.
  • %PATH%;C:\your\path\here\ – The %PATH% part expands to the current value of PATH, and ;C:\your\path\here\ is then concatenated to it. This becomes the new PATH.

HttpWebRequest-The remote server returned an error: (400) Bad Request

Are you sure you should be using POST not PUT?

POST is usually used with application/x-www-urlencoded formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data. Not always, but usually, that is the right thing to do..

Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.

Cannot connect to SQL Server named instance from another SQL Server

To solve this you must ensure the following is true on the machine hosting SQL Server...

  1. Ensure Server Browser service is running
  2. Ensure TCP/IP communication is enabled for each instance you wish to communicate with over the network. enter image description here
  3. If running multiple instances, ensure each instance is using a different port, and that the port is not in use. e.g for two instance 1433 (default port for the default instance, 1435 for a named instance. enter image description here
  4. Ensure the firewall has an entry to allow communication with SQL Server browser on port 1434 over the UDP protocol.
  5. Ensure the firewall has an entry to allow communication with SQL Server instances on the ports assigned to them in step 3 over the TCP protocol enter image description here

What is the difference between a 'closure' and a 'lambda'?

A Lambda expression is just an anonymous function. in plain java, for example, you can write it like this:

Function<Person, Job> mapPersonToJob = new Function<Person, Job>() {
    public Job apply(Person person) {
        Job job = new Job(person.getPersonId(), person.getJobDescription());
        return job;
    }
};

where the class Function is just built in java code. Now you can call mapPersonToJob.apply(person) somewhere to use it. thats just one example. Thats a lambda before there was syntax for it. Lambdas a short cut for this.

Closure:

a Lambda becomes a closure when it can access the variables outside of this scope. i guess you can say its magic, it magically can wrap around the environment it was created in and use the variables outside of its scope(outer scope. so to be clear, a closure means a lambda can access its OUTER SCOPE.

in Kotlin, a lambda can always access its closure (the variables that are in its outer scope)

Does the target directory for a git clone have to match the repo name?

Yes, it is possible:

git clone https://github.com/pitosalas/st3_packages Packages 

You can specify the local root directory when using git clone.

<directory> 

The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
Cloning into an existing directory is only allowed if the directory is empty.


As Chris comments, you can then rename that top directory.
Git only cares about the .git within said top folder, which you can get with various commands:

git rev-parse --show-toplevel git rev-parse --git-dir 

change figure size and figure format in matplotlib

If you need to change the figure size after you have created it, use the methods

fig = plt.figure()
fig.set_figheight(value_height)
fig.set_figwidth(value_width)

where value_height and value_width are in inches. For me this is the most practical way.

Passing parameters from jsp to Spring Controller method

Use the @RequestParam to pass a parameter to the controller handler method. In the jsp your form should have an input field with name = "id" like the following:

<input type="text" name="id" />
<input type="submit" />

Then in your controller, your handler method should be like the following:

@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
    return "note";
}

Please also refer to these answers and tutorial:

Display a jpg image on a JPanel

You could also use

ImageIcon background = new ImageIcon("Background/background.png");
JLabel label = new JLabel();
label.setBounds(0, 0, x, y);
label.setIcon(background);

JPanel panel = new JPanel();
panel.setLayout(null);
panel.add(label);

if your working with a absolut value as layout.

Comparing object properties in c#

sometimes you don't want to compare all public properties and want to compare only the subset of them, so in this case you can just move logic to compare the desired list of properties to abstract class

public abstract class ValueObject<T> where T : ValueObject<T>
{
    protected abstract IEnumerable<object> GetAttributesToIncludeInEqualityCheck();

    public override bool Equals(object other)
    {
        return Equals(other as T);
    }

    public bool Equals(T other)
    {
        if (other == null)
        {
            return false;
        }

        return GetAttributesToIncludeInEqualityCheck()
            .SequenceEqual(other.GetAttributesToIncludeInEqualityCheck());
    }

    public static bool operator ==(ValueObject<T> left, ValueObject<T> right)
    {
        return Equals(left, right);
    }

    public static bool operator !=(ValueObject<T> left, ValueObject<T> right)
    {
        return !(left == right);
    }

    public override int GetHashCode()
    {
        int hash = 17;
        foreach (var obj in this.GetAttributesToIncludeInEqualityCheck())
            hash = hash * 31 + (obj == null ? 0 : obj.GetHashCode());

        return hash;
    }
}

and use this abstract class later to compare the objects

public class Meters : ValueObject<Meters>
{
    ...

    protected decimal DistanceInMeters { get; private set; }

    ...

    protected override IEnumerable<object> GetAttributesToIncludeInEqualityCheck()
    {
        return new List<Object> { DistanceInMeters };
    }
}

How do I make a Docker container start automatically on system boot?

I wanted to achieve on-boot container startup on Windows.

Therefore, I just created a scheduled Task which launches on system boot. That task simply starts "Docker for Windows.exe" (or whatever is the name of your docker executable).

Then, all containers with a restart policy of "always" will start up.

Boxplot in R showing the mean

abline(h=mean(x))

for a horizontal line (use v instead of h for vertical if you orient your boxplot horizontally), or

points(mean(x))

for a point. Use the parameter pch to change the symbol. You may want to colour them to improve visibility too.

Note that these are called after you have drawn the boxplot.

If you are using the formula interface, you would have to construct the vector of means. For example, taking the first example from ?boxplot:

boxplot(count ~ spray, data = InsectSprays, col = "lightgray")
means <- tapply(InsectSprays$count,InsectSprays$spray,mean)
points(means,col="red",pch=18)

If your data contains missing values, you might want to replace the last argument of the tapply function with function(x) mean(x,na.rm=T)

Explanation of <script type = "text/template"> ... </script>

By setting script tag type other than text/javascript, browser will not execute the internal code of script tag. This is called micro template. This concept is widely used in Single page application(aka SPA).

<script type="text/template">I am a Micro template. 
  I am going to make your web page faster.</script>

For micro template, type of the script tag is text/template. It is very well explained by Jquery creator John Resig http://ejohn.org/blog/javascript-micro-templating/

Why do I get a C malloc assertion failure?

99.9% likely that you have corrupted memory (over- or under-flowed a buffer, wrote to a pointer after it was freed, called free twice on the same pointer, etc.)

Run your code under Valgrind to see where your program did something incorrect.

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

Here is part of a line in my code that brought the warning up in NetBeans:

$page = (!empty($_GET['p'])) 

After much research and seeing how there are about a bazillion ways to filter this array, I found one that was simple. And my code works and NetBeans is happy:

$p = filter_input(INPUT_GET, 'p');
$page = (!empty($p))

Has anyone ever got a remote JMX JConsole to work?

You are probably experiencing an issue with a firewall. The 'problem' is that the port you specify is not the only port used, it uses 1 or maybe even 2 more ports for RMI, and those are probably blocked by a firewall.

One of the extra ports will not be know up front if you use the default RMI configuration, so you have to open up a big range of ports - which might not amuse the server administrator.

There is a solution that does not require opening up a lot of ports however, I've gotten it to work using the combined source snippets and tips from

http://forums.sun.com/thread.jspa?threadID=5267091 - link doesn't work anymore

http://blogs.oracle.com/jmxetc/entry/connecting_through_firewall_using_jmx

http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html

It's even possible to setup an ssh tunnel and still get it to work :-)

What is referencedColumnName used for in JPA?

"referencedColumnName" property is the name of the column in the table that you are making reference with the column you are anotating. Or in a short manner: it's the column referenced in the destination table. Imagine something like this: cars and persons. One person can have many cars but one car belongs only to one person (sorry, I don't like anyone else driving my car).

Table Person
name char(64) primary key
age int

Table Car
car_registration char(32) primary key
car_brand (char 64)
car_model (char64)
owner_name char(64) foreign key references Person(name)

When you implement classes you will have something like

class Person{
   ...
}

class Car{
    ...
    @ManyToOne
    @JoinColumn([column]name="owner_name", referencedColumnName="name")
    private Person owner;
}

EDIT: as @searchengine27 has commented, columnName does not exist as a field in persistence section of Java7 docs. I can't remember where I took this property from, but I remember using it, that's why I'm leaving it in my example.

Only get hash value using md5sum (without filename)

md5sum puts backslash before hash if there is backslash in file name. First 32 characters or anything before first space may not be a proper hash. It will not happen when using standard input (file name will be just -), so pixelbeat's answer will work, but many others will require adding something like | tail -c 32.

How to allow only numbers in textbox in mvc4 razor

Please use DataType attribue but this will except negative values so the regular expression below will avoid this

   [DataType(DataType.PhoneNumber,ErrorMessage="Not a number")]
   [Display(Name = "Oxygen")]
   [RegularExpression( @"^\d+$")]
   [Required(ErrorMessage="{0} is required")]
   [Range(0,30,ErrorMessage="Please use values between 0 to 30")]
    public int Oxygen { get; set; }

How to delete a folder and all contents using a bat file in windows?

@RD /S /Q "D:\PHP_Projects\testproject\Release\testfolder"

Explanation:

Removes (deletes) a directory.

RMDIR [/S] [/Q] [drive:]path RD [/S] [/Q] [drive:]path

/S      Removes all directories and files in the specified directory
        in addition to the directory itself.  Used to remove a directory
        tree.

/Q      Quiet mode, do not ask if ok to remove a directory tree with /S

This certificate has an invalid issuer Apple Push Services

This is not actually a development issue. It happens due to expiration of the Apple Worldwide Developer Relations Intermediate Certificate issued by Apple Worldwide Developer Relations Certificate Authority. WWDRCA issues the certificate to sign your software for Apple devices, allowing our systems to confirm that your software is delivered to users as intended and has not been modified.

To resolve this issue, you have to follow the below steps:

  1. Open Keychain Access
  2. Go to View -> Show Expired Certificates

Enter image description here

  1. Go to System in Keychain Enter image description here

  2. Here you find that "Apple Worldwide Developer Relations Certificate Authority" is marked as expired. So delete it. Also check under Login Tab and delete expired WWDRCA.

  3. Download new WWDR Intermediate Certificate from here(The renewed Apple Worldwide Developer Relations Certification Intermediate Certificate will expire on February 7, 2023).

  4. Install it by double clicking on it.

If you still face any issue with your iOS apps, Mac apps, Safari extensions, Apple Wallet and Safari push notifications, then please follow this link of expiration.

The Apple Worldwide Developer Relations Certification Intermediate Certificate expires soon and we've issued a renewed certificate that must be included when signing all new Apple Wallet Passes, push packages for Safari Push Notifications, and Safari Extensions starting February 14, 2016.

While most developers and users will not be affected by the certificate change, we recommend that all developers download and install the renewed certificate on their development systems and servers as a best practice. All apps will remain available on the App Store for iOS, Mac, and Apple TV.

Executing Javascript code "on the spot" in Chrome?

Right click on the page and choose 'inspect element'. In the screen that opens now (the developer tools), clicking the second icon from the left @ the bottom of it opens a console, where you can type javascript. The console is linked to the current page.

How to change XAMPP apache server port?

The best solution is to reconfigure the XAMPP Apache server to listen and use different port numbers. Here is how you do it:

1) First, you need to open the Apache “httpd.conf” file and configure it to use/listen on a new port no. To open httpd.conf file, click the “Config” button next to Apache “Start” and “Admin” buttons. In the popup menu that opens, click and open httpd.conf

2) Within the httpd.conf file search for “listen”. You’ll find two rows with something like:

#Listen 12.34.56.78:80
Listen 80

Change the port no to a port no. of your choice (e.g. port 1234) like below

#Listen 12.34.56.78:1234
Listen 1234

3) Next, in the same httpd.conf file look for “ServerName localhost:” Set it to the new port no.

ServerName localhost:1234

4) Save and close the httpd.conf file.

5) Now click the Apache config button again and open the “httpd-ssl.conf” file.

6) In the httpd-ssl.conf file, look for “Listen” again. You may find:

Listen 443

Change it to listen on a new port no of your choice. Say like:

Listen 1443

7) In the same httpd-ssl.conf file find another line that says <VirtualHost _default_:443>. Change this to your new port no. (like 1443)

8) Also in the same httpd-ssl.conf you can find another line defining the port no. For that look for “ServerName”. you might find something like:

ServerName www.example.com:443 or  ServerName localhost:433

Change this ServerName to your new port no.

8) Save and close the httpd-ssl.conf file.

9) Finally, there’s just one more place you should change the port no. For that, click and open the “Config” button of your XAMPP Control Panel. Then click the, “Service and Port Settings” button. Within it, click the “Apache” tab and enter and save the new port nos in the “main port” and “SSL port” boxes. Click save and close the config boxes.

That should do the trick. Now “Start” Apache and if everything goes well, your Apache server should start up.

You will also see the Apache Port/s no in the XAMPP control panel has change to the new port IDs you set.

How to reload or re-render the entire page using AngularJS

Before Angular 2 ( AngularJs )

Through route

$route.reload();

If you want reload whole Application

$window.location.reload();

Angular 2+

import { Location } from '@angular/common';

constructor(private location: Location) {}

ngOnInit() {  }

load() {
    this.location.reload()
}

Or

constructor(private location: Location) {}

ngOnInit() {  }

Methods (){
    this.ngOnInit();
}

How to configure log4j with a properties file

I have this code in my application today

File log4jfile = new File("./conf/log4j.properties");
PropertyConfigurator.configure(log4jfile.getAbsolutePath());

The relative path is from the working directory of the JVM (where the JVM starts).

npm not working - "read ECONNRESET"

I had the same problem when trying to run npm on system emulated in Oracle VirtualBox. I resolved it by adding Google DNS address in Network Adapter properties.

Network Adapter properties > IPv4 properties > Preferred DNS address: 8.8.8.8.

What is the difference between old style and new style classes in Python?

Declaration-wise:

New-style classes inherit from object, or from another new-style class.

class NewStyleClass(object):
    pass

class AnotherNewStyleClass(NewStyleClass):
    pass

Old-style classes don't.

class OldStyleClass():
    pass

Python 3 Note:

Python 3 doesn't support old style classes, so either form noted above results in a new-style class.

Check Whether a User Exists

Actually I cannot reproduce the problem. The script as written in the question works fine, except for the case where $1 is empty.

However, there is a problem in the script related to redirection of stderr. Although the two forms &> and >& exist, in your case you want to use >&. You already redirected stdout, that's why the form &> does not work. You can easily verify it this way:

getent /etc/passwd username >/dev/null 2&>1
ls

You will see a file named 1 in the current directory. You want to use 2>&1 instead, or use this:

getent /etc/passwd username &>/dev/null

This also redirects stdout and stderr to /dev/null.

Warning Redirecting stderr to /dev/null might not be such a good idea. When things go wrong, you will have no clue why.

Java Read Large Text File With 70million line of text

I had a similar problem, but I only needed the bytes from the file. I read through links provided in the various answers, and ultimately tried writing one similar to #5 in Evgeniy's answer. They weren't kidding, it took a lot of code.

The basic premise is that each line of text is of unknown length. I will start with a SeekableByteChannel, read data into a ByteBuffer, then loop over it looking for EOL. When something is a "carryover" between loops, it increments a counter and then ultimately moves the SeekableByteChannel position around and reads the entire buffer.

It is verbose ... but it works. It was plenty fast for what I needed, but I'm sure there are more improvements that can be made.

The process method is stripped down to the basics for kicking off reading the file.

private long startOffset;
private long endOffset;
private SeekableByteChannel sbc;

private final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

public void process() throws IOException
{
    startOffset = 0;
    sbc = Files.newByteChannel(FILE, EnumSet.of(READ));
    byte[] message = null;
    while((message = readRecord()) != null)
    {
        // do something
    }
}

public byte[] readRecord() throws IOException
{
    endOffset = startOffset;

    boolean eol = false;
    boolean carryOver = false;
    byte[] record = null;

    while(!eol)
    {
        byte data;
        buffer.clear();
        final int bytesRead = sbc.read(buffer);

        if(bytesRead == -1)
        {
            return null;
        }

        buffer.flip();

        for(int i = 0; i < bytesRead && !eol; i++)
        {
            data = buffer.get();
            if(data == '\r' || data == '\n')
            {
                eol = true;
                endOffset += i;

                if(carryOver)
                {
                    final int messageSize = (int)(endOffset - startOffset);
                    sbc.position(startOffset);

                    final ByteBuffer tempBuffer = ByteBuffer.allocateDirect(messageSize);
                    sbc.read(tempBuffer);
                    tempBuffer.flip();

                    record = new byte[messageSize];
                    tempBuffer.get(record);
                }
                else
                {
                    record = new byte[i];

                    // Need to move the buffer position back since the get moved it forward
                    buffer.position(0);
                    buffer.get(record, 0, i);
                }

                // Skip past the newline characters
                if(isWindowsOS())
                {
                    startOffset = (endOffset + 2);
                }
                else
                {
                    startOffset = (endOffset + 1);
                }

                // Move the file position back
                sbc.position(startOffset);
            }
        }

        if(!eol && sbc.position() == sbc.size())
        {
            // We have hit the end of the file, just take all the bytes
            record = new byte[bytesRead];
            eol = true;
            buffer.position(0);
            buffer.get(record, 0, bytesRead);
        }
        else if(!eol)
        {
            // The EOL marker wasn't found, continue the loop
            carryOver = true;
            endOffset += bytesRead;
        }
    }

    // System.out.println(new String(record));
    return record;
}

Eclipse Workspaces: What for and why?

Although I've used Eclipse for years, this "answer" is only conjecture (which I'm going to try tonight). If it gets down-voted out of existence, then obviously I'm wrong.

Oracle relies on CMake to generate a Visual Studio "Solution" for their MySQL Connector C source code. Within the Solution are "Projects" that can be compiled individually or collectively (by the Solution). Each Project has its own makefile, compiling its portion of the Solution with settings that are different than the other Projects.

Similarly, I'm hoping an Eclipse Workspace can hold my related makefile Projects (Eclipse), with a master Project whose dependencies compile the various unique-makefile Projects as pre-requesites to building its "Solution". (My folder structure would be as @Rafael describes).

So I'm hoping a good way to use Workspaces is to emulate Visual Studio's ability to combine dissimilar Projects into a Solution.

MS Access DB Engine (32-bit) with Office 64-bit

I hate to answer my own questions, but I did finally find a solution that actually works (using socket communication between services may fix the problem, but it creates even more problems). Since our database is legacy, it merely required Microsoft.ACE.OLEDB.12.0 in the connection string. It turns out that this was also included in Office 2007 (and MSDE 2007), where there is only a 32-bit version available. So, instead of installing MSDE 2010 32-bit, we install MSDE 2007, and it works just fine. Other applications can then install 64-bit MSDE 2010 (or 64-bit Office 2010), and it does not conflict with our application.

Thus far, it appears this is an acceptable solution for all Windows OS environments.

SQL Query - Using Order By in UNION

(SELECT FIELD1 AS NEWFIELD FROM TABLE1 ORDER BY FIELD1)
UNION
(SELECT FIELD2 FROM TABLE2 ORDER BY FIELD2)
UNION
(SELECT FIELD3 FROM TABLE3 ORDER BY FIELD3) ORDER BY NEWFIELD

Try this. It worked for me.

How does @synchronized lock/unlock in Objective-C?

The Objective-C language level synchronization uses the mutex, just like NSLock does. Semantically there are some small technical differences, but it is basically correct to think of them as two separate interfaces implemented on top of a common (more primitive) entity.

In particular with a NSLock you have an explicit lock whereas with @synchronized you have an implicit lock associated with the object you are using to synchronize. The benefit of the language level locking is the compiler understands it so it can deal with scoping issues, but mechanically they behave basically the same.

You can think of @synchronized as a compiler rewrite:

- (NSString *)myString {
  @synchronized(self) {
    return [[myString retain] autorelease];
  }
}

is transformed into:

- (NSString *)myString {
  NSString *retval = nil;
  pthread_mutex_t *self_mutex = LOOK_UP_MUTEX(self);
  pthread_mutex_lock(self_mutex);
  retval = [[myString retain] autorelease];
  pthread_mutex_unlock(self_mutex);
  return retval;
}

That is not exactly correct because the actual transform is more complex and uses recursive locks, but it should get the point across.

How to check Spark Version

You can get the spark version by using the following command:

spark-submit --version

spark-shell --version

spark-sql --version

You can visit the below site to know the spark-version used in CDH 5.7.0

http://www.cloudera.com/documentation/enterprise/release-notes/topics/cdh_rn_new_in_cdh_57.html#concept_m3k_rxh_1v

Making a drop down list using swift?

(Swift 3) Add text box and uipickerview to the storyboard then add delegate and data source to uipickerview and add delegate to textbox. Follow video for assistance https://youtu.be/SfjZwgxlwcc

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {

    @IBOutlet weak var textBox: UITextField!
    @IBOutlet weak var dropDown: UIPickerView!

    var list = ["1", "2", "3"]

    public func numberOfComponents(in pickerView: UIPickerView) -> Int{
        return 1
    }

    public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{

        return list.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        self.view.endEditing(true)
        return list[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        self.textBox.text = self.list[row]
        self.dropDown.isHidden = true
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {

        if textField == self.textBox {
            self.dropDown.isHidden = false
            //if you don't want the users to se the keyboard type:

            textField.endEditing(true)
        }
    }
}

How to add class active on specific li on user click with jQuery

You specified both jQuery and Javascript in the tags so here's both approaches.

jQuery

var selector = '.nav li';

$(selector).on('click', function(){
    $(selector).removeClass('active');
    $(this).addClass('active');
});

Fiddle: http://jsfiddle.net/bvf9u/


Pure Javascript:

var selector, elems, makeActive;

selector = '.nav li';

elems = document.querySelectorAll(selector);

makeActive = function () {
    for (var i = 0; i < elems.length; i++)
        elems[i].classList.remove('active');

    this.classList.add('active');
};

for (var i = 0; i < elems.length; i++)
    elems[i].addEventListener('mousedown', makeActive);

Fiddle: http://jsfiddle.net/rn3nc/1


jQuery with event delegation:

Please note that in approach 1, the handler is directly bound to that element. If you're expecting the DOM to update and new lis to be injected, it's better to use event delegation and delegate to the next element that will remain static, in this case the .nav:

$('.nav').on('click', 'li', function(){
    $('.nav li').removeClass('active');
    $(this).addClass('active');
});

Fiddle: http://jsfiddle.net/bvf9u/1/

The subtle difference is that the handler is bound to the .nav now, so when you click the li the event bubbles up the DOM to the .nav which invokes the handler if the element clicked matches your selector argument. This means new elements won't need a new handler bound to them, because it's already bound to an ancestor.

It's really quite interesting. Read more about it here: http://api.jquery.com/on/

Java JDBC connection status

You also can use

public boolean isDbConnected(Connection con) {
    try {
        return con != null && !con.isClosed();
    } catch (SQLException ignored) {}

    return false;
}

Python, Matplotlib, subplot: How to set the axis range?

If you have multiple subplots, i.e.

fig, ax = plt.subplots(4, 2)

You can use the same y limits for all of them. It gets limits of y ax from first plot.

plt.setp(ax, ylim=ax[0,0].get_ylim())

jQuery - Click event on <tr> elements with in a table and getting <td> element values

$("body").on("click", "#tableid tr", function () {
    debugger
    alert($(this).text());
});

$("body").on("click", "#tableid td", function () {
    debugger
    alert($(this).text());
});

How to log as much information as possible for a Java Exception?

The java.util.logging package is standard in Java SE. Its Logger includes an overloaded log method that accepts Throwable objects. It will log stacktraces of exceptions and their cause for you.

For example:

import java.util.logging.Level;
import java.util.logging.Logger;

[...]

Logger logger = Logger.getAnonymousLogger();
Exception e1 = new Exception();
Exception e2 = new Exception(e1);
logger.log(Level.SEVERE, "an exception was thrown", e2);

Will log:

SEVERE: an exception was thrown
java.lang.Exception: java.lang.Exception
    at LogStacktrace.main(LogStacktrace.java:21)
Caused by: java.lang.Exception
    at LogStacktrace.main(LogStacktrace.java:20)

Internally, this does exactly what @philipp-wendler suggests, by the way. See the source code for SimpleFormatter.java. This is just a higher level interface.

C# getting its own class name

If you need this in derived classes, you can put that code in the base class:

protected string GetThisClassName() { return this.GetType().Name; }

Then, you can reach the name in the derived class. Returns derived class name. Of course, when using the new keyword "nameof", there will be no need like this variety acts.

Besides you can define this:

public static class Extension
{
    public static string NameOf(this object o)
    {
        return o.GetType().Name;
    }
}

And then use like this:

public class MyProgram
{
    string thisClassName;

    public MyProgram()
    {
        this.thisClassName = this.NameOf();
    }
}

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

Onur Güzel provides the solution in his blog post, "Uninstall Python Package from OS X.

You should type the following commands into the terminal:

  1. sudo rm -rf /Library/Frameworks/Python.framework

  2. cd /usr/local/bin

  3. ls -l . | grep '../Library/Frameworks/Python.framework' | awk '{print $9}' | xargs sudo rm

  4. sudo rm -rf "/Applications/Python x.y"

    where command x.y is the version of Python installed. According to your question, it should be 2.7.

In Onur's words:

WARNING: This commands will remove all Python versions installed with packages. Python provided from the system will not be affected.

If you have more than 1 Python version installed from python.org, then run the fourth command again, changing "x.y" for each version of Python that is to be uninstalled.

How to grep and replace

Usually not with grep, but rather with sed -i 's/string_to_find/another_string/g' or perl -i.bak -pe 's/string_to_find/another_string/g'.

'profile name is not valid' error when executing the sp_send_dbmail command

I got the same problem also. Here's what I did:

If you're already done granting the user/group the rights to use the profile name.

  1. Go to the configuration Wizard of Database Mail
  2. Tick Manage profile security
  3. On public profiles tab, check your profile name
  4. On private profiles tab, select NT AUTHORITY\NETWORK SERVICE for user name and check your profile name
  5. Do #4 this time for NT AUTHORITY\SYSTEM user name
  6. Click Next until Finish.

How to change the button color when it is active using bootstrap?

HTML--

<div class="col-sm-12" id="my_styles">
   <button type="submit" class="btn btn-warning" id="1">Button1</button>
   <button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>

css--

.active{
         background:red;
    }
 button.btn:active{
     background:red;
 }

jQuery--

jQuery("#my_styles .btn").click(function(){
    jQuery("#my_styles .btn").removeClass('active');
    jQuery(this).toggleClass('active'); 

});

view the live demo on jsfiddle

What is Shelving in TFS?

Shelving is a way of saving all of the changes on your box without checking in. The changes are persisted on the server. At any later time you or any of your team-mates can "unshelve" them back onto any one of your machines.

It's also great for review purposes. On my team for a check in we shelve up our changes and send out an email with the change description and name of the changeset. People on the team can then view the changeset and give feedback.

FYI: The best way to review a shelveset is with the following command

tfpt review /shelveset:shelvesetName;userName

tfpt is a part of the Team Foundation Power Tools

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

When I came accross this issue none of the provided answers solved this problem or if it did I didn't like recreating the project. The way I ended up solving the issue:

enter image description here

  1. Clicking on the "Connect to Team Projects button" (The plug next to the home button in the Team Explorer tab)
  2. Right click the project you are getting this issue on.
  3. Click Connect.

I guess the "Remember me" cookie timed out but gave me a generic response for trying to push or pull any code.

input checkbox true or checked or yes

Accordingly to W3C checked input's attribute can be absent/ommited or have "checked" as its value. This does not invalidate other values because there's no restriction to the browser implementation to allow values like "true", "on", "yes" and so on. To guarantee that you'll write a cross-browser checkbox/radio use checked="checked", as recommended by W3C.

disabled, readonly and ismap input's attributes go on the same way.

EDITED

empty is not a valid value for checked, disabled, readonly and ismap input's attributes, as warned by @Quentin

figure of imshow() is too small

Update 2020

as requested by @baxxx, here is an update because random.rand is deprecated meanwhile.

This works with matplotlip 3.2.1:

from matplotlib import pyplot as plt
import random
import numpy as np

random = np.random.random ([8,90])

plt.figure(figsize = (20,2))
plt.imshow(random, interpolation='nearest')

This plots:

enter image description here

To change the random number, you can experiment with np.random.normal(0,1,(8,90)) (here mean = 0, standard deviation = 1).

What is the Linux equivalent to DOS pause?

read -n1 is not portable. A portable way to do the same might be:

(   trap "stty $(stty -g;stty -icanon)" EXIT
    LC_ALL=C dd bs=1 count=1 >/dev/null 2>&1
)   </dev/tty

Besides using read, for just a press ENTER to continue prompt you could do:

sed -n q </dev/tty

jQuery - Redirect with post data

Before document/window ready add "extend" to jQuery :

$.extend(
{
    redirectPost: function(location, args)
    {
        var form = '';
        $.each( args, function( key, value ) {

            form += '<input type="hidden" name="'+value.name+'" value="'+value.value+'">';
            form += '<input type="hidden" name="'+key+'" value="'+value.value+'">';
        });
        $('<form action="'+location+'" method="POST">'+form+'</form>').submit();
    }
});

Use :

$.redirectPost("someurl.com", $("#SomeForm").serializeArray());

Note : this method cant post files .

Finding the layers and layer sizes for each Docker image

Not exactly the original question but to find the sum total of all the images without double-counting shared layers, the following is useful (ubuntu 18):

sudo du -h -d1  /var/lib/docker/overlay2 | sort -h

Select folder dialog WPF

The FolderBrowserDialog class from System.Windows.Forms is the recommended way to display a dialog that allows a user to select a folder.

Until recently, the appearance and behaviour of this dialog was not in keeping with the other filesystem dialogs, which is one of the reasons why people were reluctant to use it.

The good news is that FolderBrowserDialog was "modernized" in NET Core 3.0, so is now a viable option for those writing either Windows Forms or WPF apps targeting that version or later.

In .NET Core 3.0, Windows Forms users [sic] a newer COM-based control that was introduced in Windows Vista: FolderBrowserDialog in NET Core 3.0

To reference System.Windows.Forms in a NET Core WPF app, it is necessary to edit the project file and add the following line:

<UseWindowsForms>true</UseWindowsForms>

This can be placed directly after the existing <UseWPF> element.

Then it's just a case of using the dialog:

using System;
using System.Windows.Forms;

...

using var dialog = new FolderBrowserDialog
{
    Description = "Time to select a folder",
    UseDescriptionForTitle = true,
    SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
        + Path.DirectorySeparatorChar,
    ShowNewFolderButton = true
};

if (dialog.ShowDialog() == DialogResult.OK)
{
    ...
}

FolderBrowserDialog has a RootFolder property that supposedly "sets the root folder where the browsing starts from" but whatever I set this to it didn't make any difference; SelectedPath seemed to be the better property to use for this purpose, however the trailing backslash is required.

Also, the ShowNewFolderButton property seems to be ignored as well, the button is always shown regardless.

How do you round a float to 2 decimal places in JRuby?

Try this:

module Util
module MyUtil



    def self.redondear_up(suma,cantidad, decimales=0)

        unless suma.present?
            return nil
        end


        if suma>0
            resultado= (suma.to_f/cantidad)
            return resultado.round(decimales)
        end


        return nil


    end

end 
end 

@font-face src: local - How to use the local font if the user already has it?

I haven’t actually done anything with font-face, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.

The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.

Does Firefox download the font when you actually use it in a font declaration? (e.g. h1 { font: 'DejaVu Serif';)?

Include headers when using SELECT INTO OUTFILE?

Actually you can make it work even with an ORDER BY.

Just needs some trickery in the order by statement - we use a case statement and replace the header value with some other value that is guaranteed to sort first in the list (obviously this is dependant on the type of field and whether you are sorting ASC or DESC)

Let's say you have three fields, name (varchar), is_active (bool), date_something_happens (date), and you want to sort the second two descending:

select 
        'name'
      , 'is_active' as is_active
      , date_something_happens as 'date_something_happens'

 union all

 select name, is_active, date_something_happens

 from
    my_table

 order by
     (case is_active when 'is_active' then 0 else is_active end) desc
   , (case date when 'date' then '9999-12-30' else date end) desc

Running a command as Administrator using PowerShell?

I am using the solution below. It handles stdout/stderr via transcript feature and passes exit code correctly to parent process. You need to adjust transcript path/filename.

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{ 
  echo "* Respawning PowerShell child process with elevated privileges"
  $pinfo = New-Object System.Diagnostics.ProcessStartInfo
  $pinfo.FileName = "powershell"
  $pinfo.Arguments = "& '" + $myinvocation.mycommand.definition + "'"
  $pinfo.Verb = "RunAs"
  $pinfo.RedirectStandardError = $false
  $pinfo.RedirectStandardOutput = $false
  $pinfo.UseShellExecute = $true
  $p = New-Object System.Diagnostics.Process
  $p.StartInfo = $pinfo
  $p.Start() | Out-Null
  $p.WaitForExit()
  echo "* Child process finished"
  type "C:/jenkins/transcript.txt"
  Remove-Item "C:/jenkins/transcript.txt"
  Exit $p.ExitCode
} Else {
  echo "Child process starting with admin privileges"
  Start-Transcript -Path "C:/jenkins/transcript.txt"
}

# Rest of your script goes here, it will be executed with elevated privileges

UILabel font size?

This worked for me:

sequencerPlayLabel.font = [UIFont fontWithName:kTypeFont size:kTypeFontSize];

-rich

Convert regular Python string to raw string

I suppose repr function can help you:

s = 't\n'
repr(s)
"'t\\n'"
repr(s)[1:-1]
't\\n'

Query to convert from datetime to date mysql

Try to cast it as a DATE

SELECT CAST(orders.date_purchased AS DATE) AS DATE_PURCHASED

How can I ignore a property when serializing using the DataContractSerializer?

Additionally, DataContractSerializer will serialize items marked as [Serializable] and will also serialize unmarked types in .NET 3.5 SP1 and later, to allow support for serializing anonymous types.

So, it depends on how you've decorated your class as to how to keep a member from serializing:

  • If you used [DataContract], then remove the [DataMember] for the property.
  • If you used [Serializable], then add [NonSerialized] in front of the field for the property.
  • If you haven't decorated your class, then you should add [IgnoreDataMember] to the property.

How to apply multiple transforms in CSS?

Just start from there that in CSS, if you repeat 2 values or more, always last one gets applied, unless using !important tag, but at the same time avoid using !important as much as you can, so in your case that's the problem, so the second transform override the first one in this case...

So how you can do what you want then?...

Don't worry, transform accepts multiple values at the same time... So this code below will work:

li:nth-child(2) {
  transform: rotate(15deg) translate(-20px, 0px); //multiple
}

If you like to play around with transform run the iframe from MDN below:

_x000D_
_x000D_
<iframe src="https://interactive-examples.mdn.mozilla.net/pages/css/transform.html" class="interactive  " width="100%" frameborder="0" height="250"></iframe>
_x000D_
_x000D_
_x000D_

Look at the link below for more info:

<< CSS transform >>

Using sudo with Python script

sometimes require a carriage return:

os.popen("sudo -S %s"%(command), 'w').write('mypass\n')

How to fill 100% of remaining height?

Create a div, which contains both divs (full and someid) and set the height of that div to the following:

height: 100vh;

The height of the containing divs (full and someid) should be set to "auto". That's all.

Numpy first occurrence of value greater than existing value

This is a little faster (and looks nicer)

np.argmax(aa>5)

Since argmax will stop at the first True ("In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.") and doesn't save another list.

In [2]: N = 10000

In [3]: aa = np.arange(-N,N)

In [4]: timeit np.argmax(aa>N/2)
100000 loops, best of 3: 52.3 us per loop

In [5]: timeit np.where(aa>N/2)[0][0]
10000 loops, best of 3: 141 us per loop

In [6]: timeit np.nonzero(aa>N/2)[0][0]
10000 loops, best of 3: 142 us per loop

Get list of data-* attributes using javascript / jQuery

or convert gilly3's excellent answer to a jQuery method:

$.fn.info = function () {
    var data = {};
    [].forEach.call(this.get(0).attributes, function (attr) {
        if (/^data-/.test(attr.name)) {
            var camelCaseName = attr.name.substr(5).replace(/-(.)/g, function ($0, $1) {
                return $1.toUpperCase();
            });
            data[camelCaseName] = attr.value;
        }
    });
    return data;
}

Using: $('.foo').info();

WCF ServiceHost access rights

please open your Visual Studio in Administration Mode then try it.

REST API Best practice: How to accept list of parameter values as input

First:

I think you can do it 2 ways

http://our.api.com/Product/<id> : if you just want one record

http://our.api.com/Product : if you want all records

http://our.api.com/Product/<id1>,<id2> :as James suggested can be an option since what comes after the Product tag is a parameter

Or the one I like most is:

You can use the the Hypermedia as the engine of application state (HATEOAS) property of a RestFul WS and do a call http://our.api.com/Product that should return the equivalent urls of http://our.api.com/Product/<id> and call them after this.

Second

When you have to do queries on the url calls. I would suggest using HATEOAS again.

1) Do a get call to http://our.api.com/term/pumas/productType/clothing/color/black

2) Do a get call to http://our.api.com/term/pumas/productType/clothing,bags/color/black,red

3) (Using HATEOAS) Do a get call to `http://our.api.com/term/pumas/productType/ -> receive the urls all clothing possible urls -> call the ones you want (clothing and bags) -> receive the possible color urls -> call the ones you want

Import error No module named skimage

You can use pip install scikit-image.

Also see the recommended procedure.

How can I match a string with a regex in Bash?

A Function To Do This

extract () {
  if [ -f $1 ] ; then
      case $1 in
          *.tar.bz2)   tar xvjf $1    ;;
          *.tar.gz)    tar xvzf $1    ;;
          *.bz2)       bunzip2 $1     ;;
          *.rar)       rar x $1       ;;
          *.gz)        gunzip $1      ;;
          *.tar)       tar xvf $1     ;;
          *.tbz2)      tar xvjf $1    ;;
          *.tgz)       tar xvzf $1    ;;
          *.zip)       unzip $1       ;;
          *.Z)         uncompress $1  ;;
          *.7z)        7z x $1        ;;
          *)           echo "don't know '$1'..." ;;
      esac
  else
      echo "'$1' is not a valid file!"
  fi
}

Other Note

In response to Aquarius Power in the comment above, We need to store the regex on a var

The variable BASH_REMATCH is set after you match the expression, and ${BASH_REMATCH[n]} will match the nth group wrapped in parentheses ie in the following ${BASH_REMATCH[1]} = "compressed" and ${BASH_REMATCH[2]} = ".gz"

if [[ "compressed.gz" =~ ^(.*)(\.[a-z]{1,5})$ ]]; 
then 
  echo ${BASH_REMATCH[2]} ; 
else 
  echo "Not proper format"; 
fi

(The regex above isn't meant to be a valid one for file naming and extensions, but it works for the example)

Inverse of matrix in R

Note that if you care about speed and do not need to worry about singularities, solve() should be preferred to ginv() because it is much faster, as you can check:

require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)

t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0 

t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1 

How to format a float in javascript?

var x = 0.3445434
x = Math.round (x*100) / 100 // this will make nice rounding

How to make the 'cut' command treat same sequental delimiters as one?

Try:

tr -s ' ' <text.txt | cut -d ' ' -f4

From the tr man page:

-s, --squeeze-repeats   replace each input sequence of a repeated character
                        that is listed in SET1 with a single occurrence
                        of that character

read input separated by whitespace(s) or newline...?

Use 'q' as the the optional argument to getline.

#include <iostream>
#include <sstream>

int main() {
    std::string numbers_str;
    getline( std::cin, numbers_str, 'q' );

    int number;
    for ( std::istringstream numbers_iss( numbers_str );
          numbers_iss >> number; ) {
        std::cout << number << ' ';
    }
}

http://ideone.com/I2vWl

Ruby: character to ascii from a string

You could also just call to_a after each_byte or even better String#bytes

=> 'hello world'.each_byte.to_a
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

=> 'hello world'.bytes
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

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

Not sure what you meant, but you can permanently turn showing whitespaces on and off in Settings -> Editor -> General -> Appearance -> Show whitespaces.

Also, you can set it for a current file only in View -> Active Editor -> Show WhiteSpaces.

Edit:

Had some free time since it looks like a popular issue, I had written a plugin to inspect the code for such abnormalities. It is called Zero Width Characters locator and you're welcome to give it a try.

Checking if a website is up via Python

I use requests for this, then it is easy and clean. Instead of print function you can define and call new function (notify via email etc.). Try-except block is essential, because if host is unreachable then it will rise a lot of exceptions so you need to catch them all.

import requests

URL = "https://api.github.com"

try:
    response = requests.head(URL)
except Exception as e:
    print(f"NOT OK: {str(e)}")
else:
    if response.status_code == 200:
        print("OK")
    else:
        print(f"NOT OK: HTTP response code {response.status_code}")

VBScript -- Using error handling

Note that On Error Resume Next is not set globally. You can put your unsafe part of code eg into a function, which will interrupted immediately if error occurs, and call this function from sub containing precedent OERN statement.

ErrCatch()

Sub ErrCatch()
    Dim Res, CurrentStep

    On Error Resume Next

    Res = UnSafeCode(20, CurrentStep)
    MsgBox "ErrStep " & CurrentStep & vbCrLf & Err.Description

End Sub

Function UnSafeCode(Arg, ErrStep)

    ErrStep = 1
    UnSafeCode = 1 / (Arg - 10)

    ErrStep = 2
    UnSafeCode = 1 / (Arg - 20)

    ErrStep = 3
    UnSafeCode = 1 / (Arg - 30)

    ErrStep = 0
End Function

Function to close the window in Tkinter

class App():
    def __init__(self):
        self.root = Tkinter.Tk()
        button = Tkinter.Button(self.root, text = 'root quit', command=self.quit)
        button.pack()
        self.root.mainloop()

    def quit(self):
        self.root.destroy()

app = App()

How to check if file already exists in the folder

Dim SourcePath As String = "c:\SomeFolder\SomeFileYouWantToCopy.txt" 'This is just an example string and could be anything, it maps to fileToCopy in your code.
Dim SaveDirectory As string = "c:\DestinationFolder"

Dim Filename As String = System.IO.Path.GetFileName(SourcePath) 'get the filename of the original file without the directory on it
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, Filename) 'combines the saveDirectory and the filename to get a fully qualified path.

If System.IO.File.Exists(SavePath) Then
   'The file exists
Else
    'the file doesn't exist
End If