Programs & Examples On #Human computer interface

href="javascript:" vs. href="javascript:void(0)"

This method seems ok in all browsers, if you set the onclick with a jQuery event:

<a href="javascript:;">Click me!</a>

As said before, href="#" with change the url hash and can trigger data re/load if you use a History (or ba-bbq) JS plugin.

How do I use hexadecimal color strings in Flutter?

If you need Hex color desperately in your application, there is one simple step you can follow:

  1. Convert your Hex color into RGB format simply from here

2. Get your RGB values. 3. In flutter, you have an simple option to use RGB color: Color.fromRGBO(r_value, g_value, b_value, opacity) will do the job for you. 4. Go ahead and tweek O_value to get the color you want.

How can I use Helvetica Neue Condensed Bold in CSS?

"Helvetica Neue Condensed Bold" get working with firefox:

.class {
  font-family: "Helvetica Neue";
  font-weight: bold;
  font-stretch: condensed;
}

But it's fail with Opera.

Web Service vs WCF Service

This answer is based on an article that no longer exists:

Summary of article:

"Basically, WCF is a service layer that allows you to build applications that can communicate using a variety of communication mechanisms. With it, you can communicate using Peer to Peer, Named Pipes, Web Services and so on.

You can’t compare them because WCF is a framework for building interoperable applications. If you like, you can think of it as a SOA enabler. What does this mean?

Well, WCF conforms to something known as ABC, where A is the address of the service that you want to communicate with, B stands for the binding and C stands for the contract. This is important because it is possible to change the binding without necessarily changing the code. The contract is much more powerful because it forces the separation of the contract from the implementation. This means that the contract is defined in an interface, and there is a concrete implementation which is bound to by the consumer using the same idea of the contract. The datamodel is abstracted out."

... later ...

"should use WCF when we need to communicate with other communication technologies (e,.g. Peer to Peer, Named Pipes) rather than Web Service"

Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

Following these steps solved my problem.

  1. Delete node_modules directory
  2. Delete package-lock.json file
  3. Start command prompt as Administrator <- important
  4. Run npm install
  5. Run npm run dev

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

I had this issue on Android 10,

Changed targetSdkVersion 29 to targetSdkVersion 28 issue resolved. Not sure what is the actual problem.

I think not a good practice, but it worked.

before:

compileSdkVersion 29

minSdkVersion 14

targetSdkVersion 29

Now:

compileSdkVersion 29

minSdkVersion 14

targetSdkVersion 28

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

My sphinx.conf

source post_source 
{
    type = mysql

    sql_host = localhost
    sql_user = ***
    sql_pass = ***
    sql_db =   ***
    sql_port = 3306

    sql_query_pre = SET NAMES utf8
    # query before fetching rows to index

    sql_query = SELECT *, id AS pid, CRC32(safetag) as safetag_crc32 FROM hb_posts


    sql_attr_uint = pid  
    # pid (as 'sql_attr_uint') is necessary for sphinx
    # this field must be unique

    # that is why I like sphinx
    # you can store custom string fields into indexes (memory) as well
    sql_field_string = title
    sql_field_string = slug
    sql_field_string = content
    sql_field_string = tags

    sql_attr_uint = category
    # integer fields must be defined as sql_attr_uint

    sql_attr_timestamp = date
    # timestamp fields must be defined as sql_attr_timestamp

    sql_query_info_pre = SET NAMES utf8
    # if you need unicode support for sql_field_string, you need to patch the source
    # this param. is not supported natively

    sql_query_info = SELECT * FROM my_posts WHERE id = $id
}

index posts 
{
    source = post_source
    # source above

    path = /var/data/posts
    # index location

    charset_type = utf-8
}

Test script:

<?php

    require "sphinxapi.php";

    $safetag = $_GET["my_post_slug"];
//  $safetag = preg_replace("/[^a-z0-9\-_]/i", "", $safetag);

    $conf = getMyConf();

    $cl = New SphinxClient();

    $cl->SetServer($conf["server"], $conf["port"]);
    $cl->SetConnectTimeout($conf["timeout"]);
    $cl->setMaxQueryTime($conf["max"]);

    # set search params
    $cl->SetMatchMode(SPH_MATCH_FULLSCAN);
    $cl->SetArrayResult(TRUE);

    $cl->setLimits(0, 1, 1); 
    # looking for the post (not searching a keyword)

    $cl->SetFilter("safetag_crc32", array(crc32($safetag)));

    # fetch results
    $post = $cl->Query(null, "post_1");

    echo "<pre>";
    var_dump($post);
    echo "</pre>";
    exit("done");
?>

Sample result:

[array] => 
  "id" => 123,
  "title" => "My post title.",
  "content" => "My <p>post</p> content.",
   ...
   [ and other fields ]

Sphinx query time:

0.001 sec.

Sphinx query time (1k concurrent):

=> 0.346 sec. (average)
=> 0.340 sec. (average of last 10 query)

MySQL query time:

"SELECT * FROM hb_posts WHERE id = 123;"
=> 0.001 sec.

MySQL query time (1k concurrent):

"SELECT * FROM my_posts WHERE id = 123;" 
=> 1.612 sec. (average)
=> 1.920 sec. (average of last 10 query)

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

How do I set the time zone of MySQL?

You have to set up the your location timezone. So that follow below process
Open your MSQLWorkbench write a simple sql command like this;

select now();

And also your url could be like this;

url = "jdbc:mysql://localhost:3306/your_database_name?serverTimezone=UTC";

What are the most common naming conventions in C?

You know, I like to keep it simple, but clear... So here's what I use, in C:

  • Trivial Variables: i,n,c,etc... (Only one letter. If one letter isn't clear, then make it a Local Variable)
  • Local Variables: lowerCamelCase
  • Global Variables: g_lowerCamelCase
  • Const Variables: ALL_CAPS
  • Pointer Variables: add a p_ to the prefix. For global variables it would be gp_var, for local variables p_var, for const variables p_VAR. If far pointers are used then use an fp_ instead of p_.
  • Structs: ModuleCamelCase (Module = full module name, or a 2-3 letter abbreviation, but still in CamelCase.)
  • Struct Member Variables: lowerCamelCase
  • Enums: ModuleCamelCase
  • Enum Values: ALL_CAPS
  • Public Functions: ModuleCamelCase
  • Private Functions: CamelCase
  • Macros: CamelCase

I typedef my structs, but use the same name for both the tag and the typedef. The tag is not meant to be commonly used. Instead it's preferrable to use the typedef. I also forward declare the typedef in the public module header for encapsulation and so that I can use the typedef'd name in the definition.

Full struct Example:

typdef struct TheName TheName;
struct TheName{
    int var;
    TheName *p_link;
};

Limiting double to 3 decimal places

If your purpose in truncating the digits is for display reasons, then you just just use an appropriate formatting when you convert the double to a string.

Methods like String.Format() and Console.WriteLine() (and others) allow you to limit the number of digits of precision a value is formatted with.

Attempting to "truncate" floating point numbers is ill advised - floating point numbers don't have a precise decimal representation in many cases. Applying an approach like scaling the number up, truncating it, and then scaling it down could easily change the value to something quite different from what you'd expected for the "truncated" value.

If you need precise decimal representations of a number you should be using decimal rather than double or float.

Set ImageView width and height programmatically?

The best and easiest way to set a button dynamically is

 Button index=new Button(this);
 int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, getResources().getDisplayMetrics());             
 int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 42, getResources().getDisplayMetrics());

The above height and width are in pixels px. 45 being the height in dp and 42 being the width in dp.

 index.setLayoutParams(new <Parent>.LayoutParams(width, height));

So, for example, if you've placed your button within a TableRow within a TableLayout, you should have it as TableRow.LayoutParams

 index.setLayoutParams(new TableRow.LayoutParams(width, height));

What is the Maximum Size that an Array can hold?

Since Length is an int I'd say Int.MaxValue

Sniffing/logging your own Android Bluetooth traffic

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

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

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

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

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

adb shell echo \$EXTERNAL_STORAGE

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

screenshot of wireshark capture using Android HCI Snoop

[source]

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

C++ Fatal Error LNK1120: 1 unresolved externals

I have faced this particular error when I didn't defined the main() function. Check if the main() function exists or check the name of the function letter by letter as Timothy described above or check if the file where the main function is located is included to your project.

Check if url contains string with JQuery

Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.

if (window.location.href.indexOf("?added-to-cart=555") > -1) {
    alert("found it");
}

How can I quantify difference between two images?

General idea

Option 1: Load both images as arrays (scipy.misc.imread) and calculate an element-wise (pixel-by-pixel) difference. Calculate the norm of the difference.

Option 2: Load both images. Calculate some feature vector for each of them (like a histogram). Calculate distance between feature vectors rather than images.

However, there are some decisions to make first.

Questions

You should answer these questions first:

  • Are images of the same shape and dimension?

    If not, you may need to resize or crop them. PIL library will help to do it in Python.

    If they are taken with the same settings and the same device, they are probably the same.

  • Are images well-aligned?

    If not, you may want to run cross-correlation first, to find the best alignment first. SciPy has functions to do it.

    If the camera and the scene are still, the images are likely to be well-aligned.

  • Is exposure of the images always the same? (Is lightness/contrast the same?)

    If not, you may want to normalize images.

    But be careful, in some situations this may do more wrong than good. For example, a single bright pixel on a dark background will make the normalized image very different.

  • Is color information important?

    If you want to notice color changes, you will have a vector of color values per point, rather than a scalar value as in gray-scale image. You need more attention when writing such code.

  • Are there distinct edges in the image? Are they likely to move?

    If yes, you can apply edge detection algorithm first (e.g. calculate gradient with Sobel or Prewitt transform, apply some threshold), then compare edges on the first image to edges on the second.

  • Is there noise in the image?

    All sensors pollute the image with some amount of noise. Low-cost sensors have more noise. You may wish to apply some noise reduction before you compare images. Blur is the most simple (but not the best) approach here.

  • What kind of changes do you want to notice?

    This may affect the choice of norm to use for the difference between images.

    Consider using Manhattan norm (the sum of the absolute values) or zero norm (the number of elements not equal to zero) to measure how much the image has changed. The former will tell you how much the image is off, the latter will tell only how many pixels differ.

Example

I assume your images are well-aligned, the same size and shape, possibly with different exposure. For simplicity, I convert them to grayscale even if they are color (RGB) images.

You will need these imports:

import sys

from scipy.misc import imread
from scipy.linalg import norm
from scipy import sum, average

Main function, read two images, convert to grayscale, compare and print results:

def main():
    file1, file2 = sys.argv[1:1+2]
    # read images as 2D arrays (convert to grayscale for simplicity)
    img1 = to_grayscale(imread(file1).astype(float))
    img2 = to_grayscale(imread(file2).astype(float))
    # compare
    n_m, n_0 = compare_images(img1, img2)
    print "Manhattan norm:", n_m, "/ per pixel:", n_m/img1.size
    print "Zero norm:", n_0, "/ per pixel:", n_0*1.0/img1.size

How to compare. img1 and img2 are 2D SciPy arrays here:

def compare_images(img1, img2):
    # normalize to compensate for exposure difference, this may be unnecessary
    # consider disabling it
    img1 = normalize(img1)
    img2 = normalize(img2)
    # calculate the difference and its norms
    diff = img1 - img2  # elementwise for scipy arrays
    m_norm = sum(abs(diff))  # Manhattan norm
    z_norm = norm(diff.ravel(), 0)  # Zero norm
    return (m_norm, z_norm)

If the file is a color image, imread returns a 3D array, average RGB channels (the last array axis) to obtain intensity. No need to do it for grayscale images (e.g. .pgm):

def to_grayscale(arr):
    "If arr is a color image (3D array), convert it to grayscale (2D array)."
    if len(arr.shape) == 3:
        return average(arr, -1)  # average over the last axis (color channels)
    else:
        return arr

Normalization is trivial, you may choose to normalize to [0,1] instead of [0,255]. arr is a SciPy array here, so all operations are element-wise:

def normalize(arr):
    rng = arr.max()-arr.min()
    amin = arr.min()
    return (arr-amin)*255/rng

Run the main function:

if __name__ == "__main__":
    main()

Now you can put this all in a script and run against two images. If we compare image to itself, there is no difference:

$ python compare.py one.jpg one.jpg
Manhattan norm: 0.0 / per pixel: 0.0
Zero norm: 0 / per pixel: 0.0

If we blur the image and compare to the original, there is some difference:

$ python compare.py one.jpg one-blurred.jpg 
Manhattan norm: 92605183.67 / per pixel: 13.4210411116
Zero norm: 6900000 / per pixel: 1.0

P.S. Entire compare.py script.

Update: relevant techniques

As the question is about a video sequence, where frames are likely to be almost the same, and you look for something unusual, I'd like to mention some alternative approaches which may be relevant:

  • background subtraction and segmentation (to detect foreground objects)
  • sparse optical flow (to detect motion)
  • comparing histograms or some other statistics instead of images

I strongly recommend taking a look at “Learning OpenCV” book, Chapters 9 (Image parts and segmentation) and 10 (Tracking and motion). The former teaches to use Background subtraction method, the latter gives some info on optical flow methods. All methods are implemented in OpenCV library. If you use Python, I suggest to use OpenCV = 2.3, and its cv2 Python module.

The most simple version of the background subtraction:

  • learn the average value µ and standard deviation s for every pixel of the background
  • compare current pixel values to the range of (µ-2s,µ+2s) or (µ-s,µ+s)

More advanced versions make take into account time series for every pixel and handle non-static scenes (like moving trees or grass).

The idea of optical flow is to take two or more frames, and assign velocity vector to every pixel (dense optical flow) or to some of them (sparse optical flow). To estimate sparse optical flow, you may use Lucas-Kanade method (it is also implemented in OpenCV). Obviously, if there is a lot of flow (high average over max values of the velocity field), then something is moving in the frame, and subsequent images are more different.

Comparing histograms may help to detect sudden changes between consecutive frames. This approach was used in Courbon et al, 2010:

Similarity of consecutive frames. The distance between two consecutive frames is measured. If it is too high, it means that the second frame is corrupted and thus the image is eliminated. The Kullback–Leibler distance, or mutual entropy, on the histograms of the two frames:

$$ d(p,q) = \sum_i p(i) \log (p(i)/q(i)) $$

where p and q are the histograms of the frames is used. The threshold is fixed on 0.2.

Java program to get the current date without timestamp

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

How To Convert A Number To an ASCII Character?

you can simply cast it.

char c = (char)100;

Is there a "null coalescing" operator in JavaScript?

Need to support old browser and have a object hierarchy

body.head.eyes[0]  //body, head, eyes  may be null 

may use this,

(((body||{}) .head||{}) .eyes||[])[0] ||'left eye'

installation app blocked by play protect

the only solution worked for me was using java keytool and generating a .keystore file the command line and then use that .keystore file to sign my app

you can find the java keytool at this directory C:\Program Files\Java\jre7\bin

open a command window and switch to that directory and enter a command like this

keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

Keytool prompts you to provide passwords for the keystore, your name , company etc . note that at the last prompt you need to enter yes.

It then generates the keystore as a file called my-release-key.keystore in the directory you're in. The keystore and key are protected by the passwords you entered. The keystore contains a single key, valid for 10000 days. The alias is a name that you — will use later, to refer to this keystore when signing your application.

For more information about Keytool, see the documentation at: http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html

and for more information on signing Android apps go here: http://developer.android.com/tools/publishing/app-signing.html

Best way to handle list.index(might-not-exist) in python?

There is nothing wrong with your code that uses ValueError. Here's yet another one-liner if you'd like to avoid exceptions:

thing_index = next((i for i, x in enumerate(thing_list) if x == thing), -1)

Find the number of columns in a table

SELECT COUNT(*)
  FROM INFORMATION_SCHEMA.COLUMNS
 WHERE table_catalog = 'database_name' -- the database
   AND table_name = 'table_name'

FromBody string parameter is giving null

Try the below code:

[Route("/test")]
[HttpPost]
public async Task Test()
{
   using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
   {
      var textFromBody = await reader.ReadToEndAsync();                    
   }            
}

The program can't start because libgcc_s_dw2-1.dll is missing

Can't you put it in system32 or something like you do with others dll files, so that every program you try to run won't have that problem on your machine?

I just need the path where to put it.

It is kinda annoying to put it in the directory every time I run a program I just built...

Edit: I found the solution:

Extract libgcc_s_dw2-1.dll to a location on your computer. We recommend you to unzip it to the directory of the program that is requesting libgcc_s_dw2-1.dll.

If that doesn't work, you will have to extract libgcc_s_dw2-1.dll to your system directory. By default, this is:

  • C:\Windows\System (Windows 95/98/Me)
  • C:\WINNT\System32 (Windows NT/2000)
  • C:\Windows\System32 (Windows XP, Vista, 7)

If you use a 64-bit version of Windows, you should also place libgcc_s_dw2-1.dll in C:\Windows\SysWOW64\

Make sure overwrite any existing files (but make a backup copy of the original file). Reboot your computer.

If the problem still occurs, try the following:

  • Open Windows Start menu and select "Run...".
  • Type CMD and press Enter (or if you use Windows ME, type COMMAND)).
  • Type regsvr32 libgcc_s_dw2-1.dll and press Enter.

How to get the <html> tag HTML with JavaScript / jQuery?

This is how to get the html DOM element purely with JS:

var htmlElement = document.getElementsByTagName("html")[0];

or

var htmlElement = document.querySelector("html");

And if you want to use jQuery to get attributes from it...

$(htmlElement).attr(INSERT-ATTRIBUTE-NAME);

How to convert an array of key-value tuples into an object

easiest way to do it where array is of your JSON data :

var obj = {};
array.forEach(function(Data){
obj[Data[0]] = Data[1]
})

UIScrollView Scrollable Content Size Ambiguity

This error took me a while to track down, initially I tried pinning the ScrollView's size but the error message clearly says "content size". I made sure everything I pinned from the top of the ScrollView was also pinned to the bottom. That way the ScrollView can calculate its content height by finding the height of all the objects & constraints. This solved the ambiguous content height, the width is pretty similar... Initially I had most things X centered in the ScrollView, but I had to also pin the objects to the side of the ScrollView. I don't like this because the iPhone6 might have a wider screen but it will remove the 'ambiguous content width' error.

javascript date to string

You will need to pad with "0" if its a single digit & note getMonth returns 0..11 not 1..12

function printDate() {
    var temp = new Date();
    var dateStr = padStr(temp.getFullYear()) +
                  padStr(1 + temp.getMonth()) +
                  padStr(temp.getDate()) +
                  padStr(temp.getHours()) +
                  padStr(temp.getMinutes()) +
                  padStr(temp.getSeconds());
    debug (dateStr );
}

function padStr(i) {
    return (i < 10) ? "0" + i : "" + i;
}

Regex for Comma delimited list

I had a slightly different requirement, to parse an encoded dictionary/hashtable with escaped commas, like this:

"1=This is something, 2=This is something,,with an escaped comma, 3=This is something else"

I think this is an elegant solution, with a trick that avoids a lot of regex complexity:

if (string.IsNullOrEmpty(encodedValues))
{
    return null;
}
else
{
    var retVal = new Dictionary<int, string>();
    var reFields = new Regex(@"([0-9]+)\=(([A-Za-z0-9\s]|(,,))+),");
    foreach (Match match in reFields.Matches(encodedValues + ","))
    {
        var id = match.Groups[1].Value;
        var value = match.Groups[2].Value;
        retVal[int.Parse(id)] = value.Replace(",,", ",");
    }
    return retVal;
}

I think it can be adapted to the original question with an expression like @"([0-9]+),\s?" and parse on Groups[0].

I hope it's helpful to somebody and thanks for the tips on getting it close to there, especially Asaph!

Is there a way to have printf() properly print out an array (of floats, say)?

you need to iterate through the array's elements

float foo[] = {1, 2, 3, 10};
int i;
for (i=0;i < (sizeof (foo) /sizeof (foo[0]));i++) {
    printf("%lf\n",foo[i]);
}

or create a function that returns stacked sn printf and then prints it with

printf("%s\n",function_that_makes_pretty_output(foo))

Remove Duplicate objects from JSON Array

Use this Pseudocode

var standardsList = [
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Geometry"},
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},
    {"Grade": "Math 1", "Domain": "Orders of Operation"},
    {"Grade": "Math 2", "Domain": "Geometry"},
    {"Grade": "Math 2", "Domain": "Geometry"}
];
var newArr =[]
for(var i in standardsList){
    newArr.push(JSON.stringify(standardsList[i]))
}
var obj = {};
newArr= newArr.filter((item)=>{
    return obj.hasOwnProperty(item) ? false : (obj[item] = true);
})
standardsList.length = 0
for(var i in newArr){
    standardsList.push(JSON.parse(newArr[i]))
}
console.log(standardsList)

I have choose a sample array similar to yours. Its easier to compare objects once you stringfy them. Then you just have to compare strings.

Convert a Python list with strings all to lowercase or uppercase

For this sample the comprehension is fastest

$ python -m timeit -s 's=["one","two","three"]*1000' '[x.upper for x in s]'
1000 loops, best of 3: 809 usec per loop

$ python -m timeit -s 's=["one","two","three"]*1000' 'map(str.upper,s)'
1000 loops, best of 3: 1.12 msec per loop

$ python -m timeit -s 's=["one","two","three"]*1000' 'map(lambda x:x.upper(),s)'
1000 loops, best of 3: 1.77 msec per loop

How to capture Enter key press?

<form action="#">
    <input type="text" id="txtBox" name="txt" onkeypress="handle" />
</form>






<script>
    $("#txtBox").keypress(function (e) {
            if (e.keyCode === 13) {
                alert("Enter was pressed was presses");
            }

            return false;
        });

    </script>

Python memory usage of numpy arrays

The field nbytes will give you the size in bytes of all the elements of the array in a numpy.array:

size_in_bytes = my_numpy_array.nbytes

Notice that this does not measures "non-element attributes of the array object" so the actual size in bytes can be a few bytes larger than this.

Change CSS class properties with jQuery

You can't change CSS properties directly with jQuery. But you can achieve the same effect in at least two ways.

Dynamically Load CSS from a File

function updateStyleSheet(filename) {
    newstylesheet = "style_" + filename + ".css";

    if ($("#dynamic_css").length == 0) {
        $("head").append("<link>")
        css = $("head").children(":last");

        css.attr({
          id: "dynamic_css",
          rel:  "stylesheet",
          type: "text/css",
          href: newstylesheet
        });
    } else {
        $("#dynamic_css").attr("href",newstylesheet);
    }
}

The example above is copied from:

Dynamically Add a Style Element

$("head").append('<style type="text/css"></style>');
var newStyleElement = $("head").children(':last');
newStyleElement.html('.red{background:green;}');

The example code is copied from this JSFiddle fiddle originally referenced by Alvaro in their comment.

Focus Next Element In Tab Index

Tabbable is a small JS package that gives you a list of all tabbable elements in tab order. So you could find your element within that list, then focus on the next list entry.

The package correctly handles the complicated edge cases mentioned in other answers (e.g., no ancestor can be display: none). And it doesn't depend on jQuery!

As of this writing (version 1.1.1), it has the caveats that it doesn't support IE8, and that browser bugs prevent it from handling contenteditable correctly.

What are some good SSH Servers for windows?

copssh - OpenSSH for Windows

http://www.itefix.no/i2/copssh

Packages essential Cygwin binaries.

JQuery - how to select dropdown item based on value

$('select#myselect option[value="ab"]').

How does the vim "write with sudo" trick work?

The only problem with cnoremap w!! is that it replaces w with ! (and hangs until you type the next char) whenever you type w! at the : command prompt. Like when you want to actually force-save with w!. Also, even if it's not the first thing after :.

Therefore I would suggest mapping it to something like <Fn>w. I personally have mapleader = F1, so I'm using <Leader>w.

If input value is blank, assign a value of "empty" with Javascript

You can do this:

var getValue  = function (input, defaultValue) {
    return input.value || defaultValue;
};

How best to determine if an argument is not sent to the JavaScript function

There are significant differences. Let's set up some test cases:

var unused; // value will be undefined
Test("test1", "some value");
Test("test2");
Test("test3", unused);
Test("test4", null);
Test("test5", 0);
Test("test6", "");

With the first method you describe, only the second test will use the default value. The second method will default all but the first (as JS will convert undefined, null, 0, and "" into the boolean false. And if you were to use Tom's method, only the fourth test will use the default!

Which method you choose really depends on your intended behavior. If values other than undefined are allowable for argument2, then you'll probably want some variation on the first; if a non-zero, non-null, non-empty value is desired, then the second method is ideal - indeed, it is often used to quickly eliminate such a wide range of values from consideration.

Regex using javascript to return just numbers

Here is the solution to convert the string to valid plain or decimal numbers using Regex:

//something123.777.321something to 123.777321
const str = 'something123.777.321something';
let initialValue = str.replace(/[^0-9.]+/, '');
//initialValue = '123.777.321';

//characterCount just count the characters in a given string
if (characterCount(intitialValue, '.') > 1) {
 const splitedValue = intitialValue.split('.');
 //splittedValue = ['123','777','321'];
 intitialValue = splitedValue.shift() + '.' + splitedValue.join('');
 //result i.e. initialValue = '123.777321'
}

Display Back Arrow on Toolbar

Simple and easy way to show back button on toolbar

Paste this code in onCreate method

 if (getSupportActionBar() != null){

            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

Paste this override method outside the onCreate method

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId()== android.R.id.home) {

        finish();
    }
    return super.onOptionsItemSelected(item);
}

How to build minified and uncompressed bundle with webpack?

You can format your webpack.config.js like this:

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');

module.exports = {
    context: __dirname,
    devtool: debug ? "inline-sourcemap" : null,
    entry: "./entry.js",
    output: {
        path: __dirname + "/dist",
        filename: "library.min.js"
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
    ],
};'

And then to build it unminified run (while in the project's main directory):

$ webpack

To build it minified run:

$ NODE_ENV=production webpack

Notes: Make sure that for the unminified version you change the output file name to library.js and for the minified library.min.js so they do not overwrite each other.

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Select Help->About

for 64 bit.. it would say version as 64 bit Edition.

I see this in IE 9.. may be true with lesser versions too..

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

C# "must declare a body because it is not marked abstract, extern, or partial"

You need to either provide a body for both the getter and setter, or neither. Since you have non-trivial logic in your setter, you need a manually-implemented getter like so:

get { return _hour; }

If you decide you don't need the logic in the setter, you could go with an automatically-implemented property like so:

public int Hour { get; set; }

Redirect all to index.php using htaccess

Your rewrite rule looks almost ok.

First make sure that your .htaccess file is in your document root (the same place as index.php) or it'll only affect the sub-folder it's in (and any sub-folders within that - recursively).

Next make a slight change to your rule so it looks something like:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]

At the moment you're just matching on . which is one instance of any character, you need at least .* to match any number of instances of any character.

The $_GET['path'] variable will contain the fake directory structure, so /mvc/module/test for instance, which you can then use in index.php to determine the Controller and actions you want to perform.


If you want the whole shebang installed in a sub-directory, such as /mvc/ or /framework/ the least complicated way to do it is to change the rewrite rule slightly to take that into account.

RewriteRule ^(.*)$ /mvc/index.php?path=$1 [NC,L,QSA]

And ensure that your index.php is in that folder whilst the .htaccess file is in the document root.


Alternative to $_GET['path'] (updated Feb '18 and Jan '19)

It's not actually necessary (nor even common now) to set the path as a $_GET variable, many frameworks will rely on $_SERVER['REQUEST_URI'] to retrieve the same information - normally to determine which Controller to use - but the principle is exactly the same.

This does simplify the RewriteRule slightly as you don't need to create the path parameter (which means the OP's original RewriteRule will now work):

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]

However, the rule about installing in a sub-directory still applies, e.g.

RewriteRule ^.*$ /mvc/index.php [L,QSA]



The flags:

NC = No Case (not case sensitive, not really necessary since there are no characters in the pattern)

L = Last (it'll stop rewriting at after this Rewrite so make sure it's the last thing in your list of rewrites)

QSA = Query String Append, just in case you've got something like ?like=penguins on the end which you want to keep and pass to index.php.

hasOwnProperty in JavaScript

hasOwnProperty expects the property name as a string, so it would be shape1.hasOwnProperty("name")

React.createElement: type is invalid -- expected a string

React.Fragment

fixed the issue for me

Error Code:

 return (
            <section className={classes.itemForm}>
             <Card>
             </Card> 
            </section>
      );

Fix

 return (
      <React.Fragment>
        <section className={classes.itemForm}>
         <Card>
         </Card> 
        </section>
      </React.Fragment>
  );

Editing specific line in text file in Python

You want to do something like this:

# with is like your try .. finally block in this case
with open('stats.txt', 'r') as file:
    # read a list of lines into data
    data = file.readlines()

print data
print "Your name: " + data[0]

# now change the 2nd line, note that you have to add a newline
data[1] = 'Mage\n'

# and write everything back
with open('stats.txt', 'w') as file:
    file.writelines( data )

The reason for this is that you can't do something like "change line 2" directly in a file. You can only overwrite (not delete) parts of a file - that means that the new content just covers the old content. So, if you wrote 'Mage' over line 2, the resulting line would be 'Mageior'.

Display date/time in user's locale format and time offset

You can use new Date().getTimezoneOffset()/60 for the timezone. There is also a toLocaleString() method for displaying a date using the user's locale.

Here's the whole list: Working with Dates

Create a directly-executable cross-platform GUI app using Python

PySimpleGUI wraps tkinter and works on Python 3 and 2.7. It also runs on Qt, WxPython and in a web browser, using the same source code for all platforms.

You can make custom GUIs that utilize all of the same widgets that you find in tkinter (sliders, checkboxes, radio buttons, ...). The code tends to be very compact and readable.

#!/usr/bin/env python
import sys
if sys.version_info[0] >= 3:
    import PySimpleGUI as sg
else:
    import PySimpleGUI27 as sg

layout = [[ sg.Text('My Window') ],
          [ sg.Button('OK')]]

window = sg.Window('My window').Layout(layout)
button, value = window.Read()

Image created from posted PySimpleGUI code

As explained in the PySimpleGUI Documentation, to build the .EXE file you run:

pyinstaller -wF MyGUIProgram.py

Set variable value to array of strings

-- create test table "Accounts"
create table Accounts (
  c_ID int primary key
 ,first_name varchar(100)
 ,last_name varchar(100)
 ,city varchar(100)
 );

insert into Accounts values (101, 'Sebastian', 'Volk', 'Frankfurt' );
insert into Accounts values (102, 'Beate',  'Mueller', 'Hamburg' );
insert into Accounts values (103, 'John',  'Walker', 'Washington' );
insert into Accounts values (104, 'Britney', 'Sears', 'Holywood' );
insert into Accounts values (105, 'Sarah', 'Schmidt', 'Mainz' );
insert into Accounts values (106, 'George', 'Lewis', 'New Jersey' );
insert into Accounts values (107, 'Jian-xin', 'Wang', 'Peking' );
insert into Accounts values (108, 'Katrina', 'Khan', 'Bolywood' );

-- declare table variable
declare @tb_FirstName table(name varchar(100));
insert into  @tb_FirstName values ('John'), ('Sarah'), ('George');

SELECT * 
FROM Accounts
WHERE first_name in (select name from @tb_FirstName);

SELECT * 
FROM Accounts
WHERE first_name not in (select name from @tb_FirstName);
go

drop table Accounts;
go

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

Copy file or directories recursively in Python

The python shutil.copytree method its a mess. I've done one that works correctly:

def copydirectorykut(src, dst):
    os.chdir(dst)
    list=os.listdir(src)
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)
    fitx.close()

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
        else:
            if not os.path.exists(dst+'/'+line[:-1]):
                os.makedirs(dst+'/'+line[:-1])
                copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
            copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
    f.close()
    os.remove(nom)
    os.chdir('..')

Case insensitive access for generic dictionary

There is much simpler way:

using System;
using System.Collections.Generic;
....
var caseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

How to get all columns' names for all the tables in MySQL?

<?php
        $table = 'orders';
        $query = "SHOW COLUMNS FROM $table";
        if($output = mysql_query($query)):
            $columns = array();
            while($result = mysql_fetch_assoc($output)):
                $columns[] = $result['Field'];
            endwhile;
        endif;
        echo '<pre>';
        print_r($columns);
        echo '</pre>';
?>

Execute an action when an item on the combobox is selected

this is how you do it with ActionLIstener

import java.awt.FlowLayout;
import java.awt.event.*;

import javax.swing.*;

public class MyWind extends JFrame{

    public MyWind() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTextField field = new JTextField();
        field.setSize(200, 50);
        field.setText("              ");

        JComboBox comboBox = new JComboBox();
        comboBox.setEditable(true);
        comboBox.addItem("item1");
        comboBox.addItem("item2");

        //
        // Create an ActionListener for the JComboBox component.
        //
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                //
                // Get the source of the component, which is our combo
                // box.
                //
                JComboBox comboBox = (JComboBox) event.getSource();

                Object selected = comboBox.getSelectedItem();
                if(selected.toString().equals("item1"))
                field.setText("30");
                else if(selected.toString().equals("item2"))
                    field.setText("40");

            }
        });
        getContentPane().add(comboBox);
        getContentPane().add(field);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MyWind().setVisible(true);
            }
        });
    }
}

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Since you're using PHP, you will probably need to use the CURLOPT_PORT option, like so:

curl_setopt($ch, CURLOPT_PORT, 11740);

Bear in mind, you may face problems with SELinux:

Unable to make php curl request with port number

Getting list of tables, and fields in each, in a database

I tested a few solutions an found that

Select *
From INFORMATION_SCHEMA.COLUMNS

gives you the column info for your CURRENT/default database.

Select *
From <DBNAME>.INFORMATION_SCHEMA.COLUMNS

, without the < and >, gives you the column info for the database DBNAME.

Using DISTINCT inner join in SQL

I believe your 1:m relationships should already implicitly create DISTINCT JOINs.

But, if you're goal is just C's in each A, it might be easier to just use DISTINCT on the outer-most query.

SELECT DISTINCT a.valueA, c.valueC
FROM C
    INNER JOIN B ON B.lookupC = C.id
    INNER JOIN A ON A.lookupB = B.id
ORDER BY a.valueA, c.valueC

PHP Session timeout

Just check first the session is not already created and if not create one. Here i am setting it for 1 minute only.

<?php 
   if(!isset($_SESSION["timeout"])){
     $_SESSION['timeout'] = time();
   };
   $st = $_SESSION['timeout'] + 60; //session time is 1 minute
?>

<?php 
  if(time() < $st){
    echo 'Session will last 1 minute';
  }
?>

How to clear all input fields in a specific div with jQuery?

For some who wants to reset the form can also use type="reset" inside any form.

<form action="/action_page.php">
Email: <input type="text" name="email"><br>
Pin: <input type="text" name="pin" maxlength="4"><br>
<input type="reset" value="Reset">
<input type="submit" value="Submit">
</form>

ValidateAntiForgeryToken purpose, explanation and example

In ASP.Net Core anti forgery token is automatically added to forms, so you don't need to add @Html.AntiForgeryToken() if you use razor form element or if you use IHtmlHelper.BeginForm and if the form's method isn't GET.

It will generate input element for your form similar to this:

<input name="__RequestVerificationToken" type="hidden" 
       value="CfDJ8HSQ_cdnkvBPo-jales205VCq9ISkg9BilG0VXAiNm3Fl5Lyu_JGpQDA4_CLNvty28w43AL8zjeR86fNALdsR3queTfAogif9ut-Zd-fwo8SAYuT0wmZ5eZUYClvpLfYm4LLIVy6VllbD54UxJ8W6FA">

And when user submits form this token is verified on server side if validation is enabled.

[ValidateAntiForgeryToken] attribute can be used against actions. Requests made to actions that have this filter applied are blocked unless the request includes a valid antiforgery token.

[AutoValidateAntiforgeryToken] attribute can be used against controllers. This attribute works identically to the ValidateAntiForgeryToken attribute, except that it doesn't require tokens for requests made using the following HTTP methods: GET HEAD OPTIONS TRACE

Additional information: docs.microsoft.com/aspnet/core/security/anti-request-forgery

Remove numbers from string sql server

Quoting part of @Jatin answer with some modifications,

use this in your where statement:

    SELECT * FROM .... etc.
        Where 
         REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE (Name, '0', ''),
        '1', ''),
        '2', ''),
        '3', ''),
        '4', ''),
        '5', ''),
        '6', ''),
        '7', ''),
        '8', ''),
        '9', '') = P_SEARCH_KEY

Environment variable to control java.io.tmpdir?

Use below command on UNIX terminal :

java -XshowSettings

This will display all java properties and system settings. In this look for java.io.tmpdir value.

Is there a printf converter to print in binary format?

Here's a version of the function that does not suffer from reentrancy issues or limits on the size/type of the argument:

#define FMT_BUF_SIZE (CHAR_BIT*sizeof(uintmax_t)+1)

char *binary_fmt(uintmax_t x, char buf[static FMT_BUF_SIZE])
{
    char *s = buf + FMT_BUF_SIZE;
    *--s = 0;
    if (!x) *--s = '0';
    for (; x; x /= 2) *--s = '0' + x%2;
    return s;
}

Note that this code would work just as well for any base between 2 and 10 if you just replace the 2's by the desired base. Usage is:

char tmp[FMT_BUF_SIZE];
printf("%s\n", binary_fmt(x, tmp));

Where x is any integral expression.

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

when you want to use your data existing in your data frame as y value, you must add stat = "identity" in mapping parameter. Function geom_bar have default y value. For example,

ggplot(data_country)+
  geom_bar(mapping = aes(x = country, y = conversion_rate), stat = "identity")

remove borders around html input

It's simple

input {border:0;outline:0;}
input:focus {outline:none!important;}

Adjusting and image Size to fit a div (bootstrap)

If any of you looking for Bootstrap-4. Here it is

<div class="row no-gutters">
    <div class="col-10">
        <img class="img-fluid" src="/resources/img1.jpg" alt="">
    </div>
</div>

PHP: Read Specific Line From File

you can use the following to get all the lines in the file

$handle = @fopen('test.txt', "r");

if ($handle) { 
   while (!feof($handle)) { 
       $lines[] = fgets($handle, 4096); 
   } 
   fclose($handle); 
} 


print_r($lines);

and $lines[1] for your second line

jQuery Scroll to bottom of page/iframe

After this thread didn't work out for me for my specific need (scrolling inside a particular element, in my case a textarea) I found this out in the great beyond, which could prove helpful to someone else reading this discussion:

Alternative on planetcloud

Since I already had a cached version of my jQuery object (the myPanel in the code below is the jQuery object), the code I added to my event handler was simply this:

myPanel.scrollTop(myPanel[0].scrollHeight - myPanel.height());

(thanks Ben)

How to communicate between Docker containers via "hostname"

As far as I know, by using only Docker this is not possible. You need some DNS to map container ip:s to hostnames.

If you want out of the box solution. One solution is to use for example Kontena. It comes with network overlay technology from Weave and this technology is used to create virtual private LAN networks for each service and every service can be reached by service_name.kontena.local-address.

Here is simple example of Wordpress application's YAML file where Wordpress service connects to MySQL server with wordpress-mysql.kontena.local address:

wordpress:                                                                         
  image: wordpress:4.1                                                             
  stateful: true                                                                   
  ports:                                                                           
    - 80:80                                                                      
  links:                                                                           
    - mysql:wordpress-mysql                                                        
  environment:                                                                     
    - WORDPRESS_DB_HOST=wordpress-mysql.kontena.local                              
    - WORDPRESS_DB_PASSWORD=secret                                                 
mysql:                                                                             
  image: mariadb:5.5                                                               
  stateful: true                                                                   
  environment:                                                                     
    - MYSQL_ROOT_PASSWORD=secret

`IF` statement with 3 possible answers each based on 3 different ranges

=IF(X2>=85,0.559,IF(X2>=80,0.327,IF(X2>=75,0.255,-1)))

Explanation:

=IF(X2>=85,                  'If the value is in the highest bracket
      0.559,                 'Use the appropriate number
      IF(X2>=80,             'Otherwise, if the number is in the next highest bracket
           0.327,            'Use the appropriate number
           IF(X2>=75,        'Otherwise, if the number is in the next highest bracket
              0.255,         'Use the appropriate number
              -1             'Otherwise, we're not in any of the ranges (Error)
             )
        )
   )

Creating a "Hello World" WebSocket example

I couldnt find a simple working example anywhere (as of Jan 19), so here is an updated version. I have chrome version 71.0.3578.98.

C# Websocket server :

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;

namespace WebSocketServer
{
    class Program
    {
    static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

    static void Main(string[] args)
    {
        serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
        serverSocket.Listen(1); //just one socket
        serverSocket.BeginAccept(null, 0, OnAccept, null);
        Console.Read();
    }

    private static void OnAccept(IAsyncResult result)
    {
        byte[] buffer = new byte[1024];
        try
        {
            Socket client = null;
            string headerResponse = "";
            if (serverSocket != null && serverSocket.IsBound)
            {
                client = serverSocket.EndAccept(result);
                var i = client.Receive(buffer);
                headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0, i);
                // write received data to the console
                Console.WriteLine(headerResponse);
                Console.WriteLine("=====================");
            }
            if (client != null)
            {
                /* Handshaking and managing ClientSocket */
                var key = headerResponse.Replace("ey:", "`")
                          .Split('`')[1]                     // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
                          .Replace("\r", "").Split('\n')[0]  // dGhlIHNhbXBsZSBub25jZQ==
                          .Trim();

                // key should now equal dGhlIHNhbXBsZSBub25jZQ==
                var test1 = AcceptKey(ref key);

                var newLine = "\r\n";

                var response = "HTTP/1.1 101 Switching Protocols" + newLine
                     + "Upgrade: websocket" + newLine
                     + "Connection: Upgrade" + newLine
                     + "Sec-WebSocket-Accept: " + test1 + newLine + newLine
                     //+ "Sec-WebSocket-Protocol: chat, superchat" + newLine
                     //+ "Sec-WebSocket-Version: 13" + newLine
                     ;

                client.Send(System.Text.Encoding.UTF8.GetBytes(response));
                var i = client.Receive(buffer); // wait for client to send a message
                string browserSent = GetDecodedData(buffer, i);
                Console.WriteLine("BrowserSent: " + browserSent);

                Console.WriteLine("=====================");
                //now send message to client
                client.Send(GetFrameFromString("This is message from server to client."));
                System.Threading.Thread.Sleep(10000);//wait for message to be sent
            }
        }
        catch (SocketException exception)
        {
            throw exception;
        }
        finally
        {
            if (serverSocket != null && serverSocket.IsBound)
            {
                serverSocket.BeginAccept(null, 0, OnAccept, null);
            }
        }
    }

    public static T[] SubArray<T>(T[] data, int index, int length)
    {
        T[] result = new T[length];
        Array.Copy(data, index, result, 0, length);
        return result;
    }

    private static string AcceptKey(ref string key)
    {
        string longKey = key + guid;
        byte[] hashBytes = ComputeHash(longKey);
        return Convert.ToBase64String(hashBytes);
    }

    static SHA1 sha1 = SHA1CryptoServiceProvider.Create();
    private static byte[] ComputeHash(string str)
    {
        return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));
    }

    //Needed to decode frame
    public static string GetDecodedData(byte[] buffer, int length)
    {
        byte b = buffer[1];
        int dataLength = 0;
        int totalLength = 0;
        int keyIndex = 0;

        if (b - 128 <= 125)
        {
            dataLength = b - 128;
            keyIndex = 2;
            totalLength = dataLength + 6;
        }

        if (b - 128 == 126)
        {
            dataLength = BitConverter.ToInt16(new byte[] { buffer[3], buffer[2] }, 0);
            keyIndex = 4;
            totalLength = dataLength + 8;
        }

        if (b - 128 == 127)
        {
            dataLength = (int)BitConverter.ToInt64(new byte[] { buffer[9], buffer[8], buffer[7], buffer[6], buffer[5], buffer[4], buffer[3], buffer[2] }, 0);
            keyIndex = 10;
            totalLength = dataLength + 14;
        }

        if (totalLength > length)
            throw new Exception("The buffer length is small than the data length");

        byte[] key = new byte[] { buffer[keyIndex], buffer[keyIndex + 1], buffer[keyIndex + 2], buffer[keyIndex + 3] };

        int dataIndex = keyIndex + 4;
        int count = 0;
        for (int i = dataIndex; i < totalLength; i++)
        {
            buffer[i] = (byte)(buffer[i] ^ key[count % 4]);
            count++;
        }

        return Encoding.ASCII.GetString(buffer, dataIndex, dataLength);
    }

    //function to create  frames to send to client 
    /// <summary>
    /// Enum for opcode types
    /// </summary>
    public enum EOpcodeType
    {
        /* Denotes a continuation code */
        Fragment = 0,

        /* Denotes a text code */
        Text = 1,

        /* Denotes a binary code */
        Binary = 2,

        /* Denotes a closed connection */
        ClosedConnection = 8,

        /* Denotes a ping*/
        Ping = 9,

        /* Denotes a pong */
        Pong = 10
    }

    /// <summary>Gets an encoded websocket frame to send to a client from a string</summary>
    /// <param name="Message">The message to encode into the frame</param>
    /// <param name="Opcode">The opcode of the frame</param>
    /// <returns>Byte array in form of a websocket frame</returns>
    public static byte[] GetFrameFromString(string Message, EOpcodeType Opcode = EOpcodeType.Text)
    {
        byte[] response;
        byte[] bytesRaw = Encoding.Default.GetBytes(Message);
        byte[] frame = new byte[10];

        int indexStartRawData = -1;
        int length = bytesRaw.Length;

        frame[0] = (byte)(128 + (int)Opcode);
        if (length <= 125)
        {
            frame[1] = (byte)length;
            indexStartRawData = 2;
        }
        else if (length >= 126 && length <= 65535)
        {
            frame[1] = (byte)126;
            frame[2] = (byte)((length >> 8) & 255);
            frame[3] = (byte)(length & 255);
            indexStartRawData = 4;
        }
        else
        {
            frame[1] = (byte)127;
            frame[2] = (byte)((length >> 56) & 255);
            frame[3] = (byte)((length >> 48) & 255);
            frame[4] = (byte)((length >> 40) & 255);
            frame[5] = (byte)((length >> 32) & 255);
            frame[6] = (byte)((length >> 24) & 255);
            frame[7] = (byte)((length >> 16) & 255);
            frame[8] = (byte)((length >> 8) & 255);
            frame[9] = (byte)(length & 255);

            indexStartRawData = 10;
        }

        response = new byte[indexStartRawData + length];

        int i, reponseIdx = 0;

        //Add the frame bytes to the reponse
        for (i = 0; i < indexStartRawData; i++)
        {
            response[reponseIdx] = frame[i];
            reponseIdx++;
        }

        //Add the data bytes to the response
        for (i = 0; i < length; i++)
        {
            response[reponseIdx] = bytesRaw[i];
            reponseIdx++;
        }

        return response;
    }
}
}

Client html and javascript:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"_x000D_
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <script type="text/javascript">_x000D_
        var socket = new WebSocket('ws://localhost:8080/websession');_x000D_
        socket.onopen = function() {_x000D_
           // alert('handshake successfully established. May send data now...');_x000D_
     socket.send("Hi there from browser.");_x000D_
        };_x000D_
  socket.onmessage = function (evt) {_x000D_
                //alert("About to receive data");_x000D_
                var received_msg = evt.data;_x000D_
                alert("Message received = "+received_msg);_x000D_
            };_x000D_
        socket.onclose = function() {_x000D_
            alert('connection closed');_x000D_
        };_x000D_
    </script>_x000D_
</head>_x000D_
<body>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Find a file with a certain extension in folder

It's quite easy, actually. You can use the System.IO.Directory class in conjunction with System.IO.Path. Something like (using LINQ makes it even easier):

var allFilenames = Directory.EnumerateFiles(path).Select(p => Path.GetFileName(p));

// Get all filenames that have a .txt extension, excluding the extension
var candidates = allFilenames.Where(fn => Path.GetExtension(fn) == ".txt")
                             .Select(fn => Path.GetFileNameWithoutExtension(fn));

There are many variations on this technique too, of course. Some of the other answers are simpler if your filter is simpler. This one has the advantage of the delayed enumeration (if that matters) and more flexible filtering at the expense of more code.

WordPress is giving me 404 page not found for all pages except the homepage

If you have FTP access to your account:

First, login to your wp-admin and go to Settings > Permalinks

You should see something at the bottom that says:

"If your .htaccess file were writable, we could do this automatically, but it isn’t so these are the mod_rewrite rules you should have in your .htaccess file. Click in the field and press CTRL + a to select all."

If this is true do the following:

  1. Go into preferences for your FTP client and make sure hidden files are displayed (varies depending on your FTP client) - If you don't do this you won't be able to find your htaccess file

  2. Go to the folder that your wp-admin, wp-content, wp-includes directories are located. Check for .htaccess file. If it exists skip to step 4

  3. If it does not exist, create a new blank file in your FTP program called .htaccess

  4. Change the CHMOD for your .htaccess file to 666 (your preference on how you want to do this)

  5. Go back to your Permalinks page and edit the link structure you want. Problem should be solved!

  6. Make sure to change the chmod of the htaccess file back to 644 after you are done.

Just had the same problem and it seemed to fix it instantly! Good luck!

Choose Git merge strategy for specific files ("ours", "mine", "theirs")

Even though this question is answered, providing an example as to what "theirs" and "ours" means in the case of git rebase vs merge. See this link

Git Rebase
theirs is actually the current branch in the case of rebase. So the below set of commands are actually accepting your current branch changes over the remote branch.

# see current branch
$ git branch
... 
* branch-a
# rebase preferring current branch changes during conflicts
$ git rebase -X theirs branch-b

Git Merge
For merge, the meaning of theirs and ours is reversed. So, to get the same effect during a merge, i.e., keep your current branch changes (ours) over the remote branch being merged (theirs).

# assuming branch-a is our current version
$ git merge -X ours branch-b  # <- ours: branch-a, theirs: branch-b

How do I run a simple bit of code in a new thread?

Try using the BackgroundWorker class. You give it delegates for what to run, and to be notified when work has finished. There is an example on the MSDN page that I linked to.

What is the optimal way to compare dates in Microsoft SQL server?

Here is an example:

I've an Order table with a DateTime field called OrderDate. I want to retrieve all orders where the order date is equals to 01/01/2006. there are next ways to do it:

1) WHERE DateDiff(dd, OrderDate, '01/01/2006') = 0
2) WHERE Convert(varchar(20), OrderDate, 101) = '01/01/2006'
3) WHERE Year(OrderDate) = 2006 AND Month(OrderDate) = 1 and Day(OrderDate)=1
4) WHERE OrderDate LIKE '01/01/2006%'
5) WHERE OrderDate >= '01/01/2006'  AND OrderDate < '01/02/2006'

Is found here

Oracle 11g SQL to get unique values in one column of a multi-column query

This will be more efficient, plus you have control over the ordering it uses to pick a value:

SELECT DISTINCT
       FIRST_VALUE(person)
          OVER(PARTITION BY language
               ORDER BY person)
      ,language
FROM   tableA;

If you really don't care which person is picked for each language, you can omit the ORDER BY clause:

SELECT DISTINCT
       FIRST_VALUE(person)
          OVER(PARTITION BY language)
      ,language
FROM   tableA;

How to convert all tables in database to one collation?

For phpMyAdmin I figured this out:

SELECT GROUP_CONCAT("ALTER TABLE ", TABLE_SCHEMA, '.', TABLE_NAME," CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" SEPARATOR ' ') AS    OneSQLString
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="yourtableschemaname"
AND TABLE_TYPE="BASE TABLE"

Just change yourtableschemaname and you're fine.

What is the difference between signed and unsigned int

Sometimes we know in advance that the value stored in a given integer variable will always be positive-when it is being used to only count things, for example. In such a case we can declare the variable to be unsigned, as in, unsigned int num student;. With such a declaration, the range of permissible integer values (for a 32-bit compiler) will shift from the range -2147483648 to +2147483647 to range 0 to 4294967295. Thus, declaring an integer as unsigned almost doubles the size of the largest possible value that it can otherwise hold.

How to store directory files listing into an array?

I'd use

files=(*)

And then if you need data about the file, such as size, use the stat command on each file.

Is background-color:none valid CSS?

.class {
    background-color:none;
}

This is not a valid property. W3C validator will display following error:

Value Error : background-color none is not a background-color value : none

transparent may have been selected as better term instead of 0 or none values during the development of specification of CSS.

how can I display tooltip or item information on mouse over?

Use the title attribute while alt is important for SEO stuff.

How can I get the height of an element using css only

Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.

Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY(); rule.


The CSS Route

If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?

This can be achieved by using the following CSS:

.dynamic-height {
    -webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    transform: translateY(100%);         //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    margin-top: -10px;
}

In this instance, it is important to remember that translateY(100%) will move the element in question downwards by a total of it's own length.

The problem with this route is that it will not push element below it out of the way, where a margin would.


The jQuery Route

If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.

jQuery(document).ready(function($){ //wait for the document to load
    $('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
        $(this).css({
            'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
        });
    });
});

Class file has wrong version 52.0, should be 50.0

Select "File" -> "Project Structure".

Under "Project Settings" select "Project"

From there you can select the "Project SDK".

how to get selected row value in the KendoUI

There is better way. I'm using it in pages where I'm using kendo angularJS directives and grids has'nt IDs...

change: function (e) {
   var selectedDataItem = e != null ? e.sender.dataItem(e.sender.select()) : null;
}

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

I have faced the same issue with you, then solved it, Here are solutions, I wish it maybe can help
First

In the IIS modules Configuration, loop up the WebDAVModule, if your web server has it, then remove it

Second

In the IIS handler mappings configuration, you can see the list of enabling handler, to choose the PHP item, edit it, on the edit page, click request restrictions button, then select the verbs tab in the modal, in the specify the verbs to be handle label, check the all verbs radio, then click ok, you also maybe see a warning, it shows us that use double quotation marks to PHP-CGI execution, then do it

if done it, then restart IIS server, it will be ok

enter image description here

Server configuration by allow_url_fopen=0 in

Edit your php.ini, find allow_url_fopen and set it to allow_url_fopen = 1

SQL ORDER BY date problem

This may help you in mysql, php.

//your date in any format
$date = $this->input->post('txtCouponExpiry');

$day = (int)substr($date, 3, 2);
$month = (int)substr($date, 0, 2);
$year = (int)substr($date, 7, 4);

$unixTimestamp = mktime(0, 0, 0, $year, $day, $month);

// insert it into database
'date'->$unixTimestamp;

//query for selecting  order by date ASC or DESC
select * from table order_by date asc;

Error: " 'dict' object has no attribute 'iteritems' "

As answered by RafaelC, Python 3 renamed dict.iteritems -> dict.items. Try a different package version. This will list available packages:

python -m pip install yourOwnPackageHere==

Then rerun with the version you will try after == to install/switch version

How to vertically align text in input type="text"?

IF vertical align won't work use padding. padding-top: 10px; it will shift the text to the bottom or padding-bottom: 10px; to shift the text in the text box to top

adjust the padding size till it suit the size you want. Thats the hack

How to print instances of a class using print()?

Just to add my two cents to @dbr's answer, following is an example of how to implement this sentence from the official documentation he's cited:

"[...] to return a string that would yield an object with the same value when passed to eval(), [...]"

Given this class definition:

class Test(object):
    def __init__(self, a, b):
        self._a = a
        self._b = b

    def __str__(self):
        return "An instance of class Test with state: a=%s b=%s" % (self._a, self._b)

    def __repr__(self):
        return 'Test("%s","%s")' % (self._a, self._b)

Now, is easy to serialize instance of Test class:

x = Test('hello', 'world')
print 'Human readable: ', str(x)
print 'Object representation: ', repr(x)
print

y = eval(repr(x))
print 'Human readable: ', str(y)
print 'Object representation: ', repr(y)
print

So, running last piece of code, we'll get:

Human readable:  An instance of class Test with state: a=hello b=world
Object representation:  Test("hello","world")

Human readable:  An instance of class Test with state: a=hello b=world
Object representation:  Test("hello","world")

But, as I said in my last comment: more info is just here!

Excel VBA Check if directory exists error

To be certain that a folder exists (and not a file) I use this function:

Public Function FolderExists(strFolderPath As String) As Boolean
    On Error Resume Next
    FolderExists = ((GetAttr(strFolderPath) And vbDirectory) = vbDirectory)
    On Error GoTo 0
End Function

It works both, with \ at the end and without.

create unique id with javascript

I think if you really want to have a unique ID then the best approach is to use a library like:
uuid or uniqueid

Note: Unique ID is not the same as Random ID

To use only date time milliseconds approach is wrong.
Nowadays computers are fast enough and able to run more than one iteration of a loop in a single millisecond.

npm install uuid

Importing the library:

If you are using ES modules

import { v4 as uuidv4 } from 'uuid';

And for CommonJS:

const { v4: uuidv4 } = require('uuid');

Usage:

uuidv4();

// This will output something like: 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d

Breaking out of nested loops

Use itertools.product!

from itertools import product
for x, y in product(range(10), range(10)):
    #do whatever you want
    break

Here's a link to itertools.product in the python documentation: http://docs.python.org/library/itertools.html#itertools.product

You can also loop over an array comprehension with 2 fors in it, and break whenever you want to.

>>> [(x, y) for y in ['y1', 'y2'] for x in ['x1', 'x2']]
[
    ('x1', 'y1'), ('x2', 'y1'),
    ('x1', 'y2'), ('x2', 'y2')
]

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

I assume that you have a .cer file containing PKCS#7-encoded certificate data and you want to convert it to PEM-encoded certificate data (typically a .crt or .pem file). For instance, a .cer file containing PKCS#7-encoded data looks like this:

-----BEGIN PKCS7-----
MIIW4gYJKoZIhvcNAQcCoIIW0zCCFs8CAQExADALBgkqhkiG9w0BBwGggha1MIIH
...
POI9n9cd2cNgQ4xYDiKWL2KjLB+6rQXvqzJ4h6BUcxm1XAX5Uj5tLUUL9wqT6u0G
+bKhADEA
-----END PKCS7-----

PEM certificate data looks like this:

-----BEGIN CERTIFICATE-----
MIIHNjCCBh6gAwIBAgIQAlBxtqKazsxUSR9QdWWxaDANBgkqhkiG9w0BAQUFADBm
...
nv72c/OV4nlyrvBLPoaS5JFUJvFUG8RfAEY=
-----END CERTIFICATE-----

There is an OpenSSL command that will convert .cer files (with PKCS#7 data) to the PEM data you may be expecting to encounter (the BEGIN CERTIFICATE block in the example above). You can coerce PKCS#7 data into PEM format by this command on a file we'll call certfile.cer:

openssl pkcs7 -text -in certfile.cer -print_certs -outform PEM -out certfile.pem

Note that a .cer or .pem file might contain one or more certificates (possibly the entire certificate chain).

How can I stop python.exe from closing immediately after I get an output?

You can't - globally, i.e. for every python program. And this is a good thing - Python is great for scripting (automating stuff), and scripts should be able to run without any user interaction at all.

However, you can always ask for input at the end of your program, effectively keeping the program alive until you press return. Use input("prompt: ") in Python 3 (or raw_input("promt: ") in Python 2). Or get used to running your programs from the command line (i.e. python mine.py), the program will exit but its output remains visible.

How to read a PEM RSA private key from .NET

I've created the PemUtils library that does exactly that. The code is available on GitHub and can be installed from NuGet:

PM> Install-Package PemUtils

or if you only want a DER converter:

PM> Install-Package DerConverter

Usage for reading a RSA key from PEM data:

using (var stream = File.OpenRead(path))
using (var reader = new PemReader(stream))
{
    var rsaParameters = reader.ReadRsaKey();
    // ...
}

What are "named tuples" in Python?

Named tuples are basically easy-to-create, lightweight object types. Named tuple instances can be referenced using object-like variable dereferencing or the standard tuple syntax. They can be used similarly to struct or other common record types, except that they are immutable. They were added in Python 2.6 and Python 3.0, although there is a recipe for implementation in Python 2.4.

For example, it is common to represent a point as a tuple (x, y). This leads to code like the following:

pt1 = (1.0, 5.0)
pt2 = (2.5, 1.5)

from math import sqrt
line_length = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)

Using a named tuple it becomes more readable:

from collections import namedtuple
Point = namedtuple('Point', 'x y')
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)

from math import sqrt
line_length = sqrt((pt1.x-pt2.x)**2 + (pt1.y-pt2.y)**2)

However, named tuples are still backwards compatible with normal tuples, so the following will still work:

Point = namedtuple('Point', 'x y')
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)

from math import sqrt
# use index referencing
line_length = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)
 # use tuple unpacking
x1, y1 = pt1

Thus, you should use named tuples instead of tuples anywhere you think object notation will make your code more pythonic and more easily readable. I personally have started using them to represent very simple value types, particularly when passing them as parameters to functions. It makes the functions more readable, without seeing the context of the tuple packing.

Furthermore, you can also replace ordinary immutable classes that have no functions, only fields with them. You can even use your named tuple types as base classes:

class Point(namedtuple('Point', 'x y')):
    [...]

However, as with tuples, attributes in named tuples are immutable:

>>> Point = namedtuple('Point', 'x y')
>>> pt1 = Point(1.0, 5.0)
>>> pt1.x = 2.0
AttributeError: can't set attribute

If you want to be able change the values, you need another type. There is a handy recipe for mutable recordtypes which allow you to set new values to attributes.

>>> from rcdtype import *
>>> Point = recordtype('Point', 'x y')
>>> pt1 = Point(1.0, 5.0)
>>> pt1 = Point(1.0, 5.0)
>>> pt1.x = 2.0
>>> print(pt1[0])
    2.0

I am not aware of any form of "named list" that lets you add new fields, however. You may just want to use a dictionary in this situation. Named tuples can be converted to dictionaries using pt1._asdict() which returns {'x': 1.0, 'y': 5.0} and can be operated upon with all the usual dictionary functions.

As already noted, you should check the documentation for more information from which these examples were constructed.

SSL InsecurePlatform error when using Requests package

In fact, you can try this.

requests.post("https://www.google.com", verify=False)

you can read the code for requests.

"C:\Python27\Lib\site-packages\requests\sessions.py"

class Session(SessionRedirectMixin):
......
 def request(self, method, url,
    params=None,
    data=None,
    headers=None,
    cookies=None,
    files=None,
    auth=None,
    timeout=None,
    allow_redirects=True,
    proxies=None,
    hooks=None,
    stream=None,
    verify=None,  # <========
    cert=None):
    """
    ...
    :param verify: (optional) if True, the SSL cert will be verified.
         A CA_BUNDLE path can also be provided.
    ...
    """

How do I create a constant in Python?

Here is an implementation of a "Constants" class, which creates instances with read-only (constant) attributes. E.g. can use Nums.PI to get a value that has been initialized as 3.14159, and Nums.PI = 22 raises an exception.

# ---------- Constants.py ----------
class Constants(object):
    """
    Create objects with read-only (constant) attributes.
    Example:
        Nums = Constants(ONE=1, PI=3.14159, DefaultWidth=100.0)
        print 10 + Nums.PI
        print '----- Following line is deliberate ValueError -----'
        Nums.PI = 22
    """

    def __init__(self, *args, **kwargs):
        self._d = dict(*args, **kwargs)

    def __iter__(self):
        return iter(self._d)

    def __len__(self):
        return len(self._d)

    # NOTE: This is only called if self lacks the attribute.
    # So it does not interfere with get of 'self._d', etc.
    def __getattr__(self, name):
        return self._d[name]

    # ASSUMES '_..' attribute is OK to set. Need this to initialize 'self._d', etc.
    #If use as keys, they won't be constant.
    def __setattr__(self, name, value):
        if (name[0] == '_'):
            super(Constants, self).__setattr__(name, value)
        else:
            raise ValueError("setattr while locked", self)

if (__name__ == "__main__"):
    # Usage example.
    Nums = Constants(ONE=1, PI=3.14159, DefaultWidth=100.0)
    print 10 + Nums.PI
    print '----- Following line is deliberate ValueError -----'
    Nums.PI = 22

Thanks to @MikeGraham 's FrozenDict, which I used as a starting point. Changed, so instead of Nums['ONE'] the usage syntax is Nums.ONE.

And thanks to @Raufio's answer, for idea to override __ setattr __.

Or for an implementation with more functionality, see @Hans_meine 's named_constants at GitHub

Convert Swift string to array

An easy way to do this is to map the variable and return each Character as a String:

let someText = "hello"

let array = someText.map({ String($0) }) // [String]

The output should be ["h", "e", "l", "l", "o"].

check if a key exists in a bucket in s3 using boto3

Boto 2's boto.s3.key.Key object used to have an exists method that checked if the key existed on S3 by doing a HEAD request and looking at the the result, but it seems that that no longer exists. You have to do it yourself:

import boto3
import botocore

s3 = boto3.resource('s3')

try:
    s3.Object('my-bucket', 'dootdoot.jpg').load()
except botocore.exceptions.ClientError as e:
    if e.response['Error']['Code'] == "404":
        # The object does not exist.
        ...
    else:
        # Something else has gone wrong.
        raise
else:
    # The object does exist.
    ...

load() does a HEAD request for a single key, which is fast, even if the object in question is large or you have many objects in your bucket.

Of course, you might be checking if the object exists because you're planning on using it. If that is the case, you can just forget about the load() and do a get() or download_file() directly, then handle the error case there.

How can I get the browser's scrollbar sizes?

From David Walsh's blog:

_x000D_
_x000D_
// Create the measurement node_x000D_
var scrollDiv = document.createElement("div");_x000D_
scrollDiv.className = "scrollbar-measure";_x000D_
document.body.appendChild(scrollDiv);_x000D_
_x000D_
// Get the scrollbar width_x000D_
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;_x000D_
console.info(scrollbarWidth); // Mac:  15_x000D_
_x000D_
// Delete the DIV _x000D_
document.body.removeChild(scrollDiv);
_x000D_
.scrollbar-measure {_x000D_
 width: 100px;_x000D_
 height: 100px;_x000D_
 overflow: scroll;_x000D_
 position: absolute;_x000D_
 top: -9999px;_x000D_
}
_x000D_
_x000D_
_x000D_

Gives me 17 on my website, 14 here on Stackoverflow.

What is the role of "Flatten" in Keras?

I came across this recently, it certainly helped me understand: https://www.cs.ryerson.ca/~aharley/vis/conv/

So there's an input, a Conv2D, MaxPooling2D etc, the Flatten layers are at the end and show exactly how they are formed and how they go on to define the final classifications (0-9).

How to save the output of a console.log(object) to a file?

Update: You can now just right click

Right click > Save as in the Console panel to save the logged messages to a file.

Original Answer:

You can use this devtools snippet shown below to create a console.save method. It creates a FileBlob from the input, and then automatically downloads it.

(function(console){

console.save = function(data, filename){

    if(!data) {
        console.error('Console.save: No data')
        return;
    }

    if(!filename) filename = 'console.json'

    if(typeof data === "object"){
        data = JSON.stringify(data, undefined, 4)
    }

    var blob = new Blob([data], {type: 'text/json'}),
        e    = document.createEvent('MouseEvents'),
        a    = document.createElement('a')

    a.download = filename
    a.href = window.URL.createObjectURL(blob)
    a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
    a.dispatchEvent(e)
 }
})(console)

Source: http://bgrins.github.io/devtools-snippets/#console-save

Get css top value as number not as string?

You can use the parseInt() function to convert the string to a number, e.g:

parseInt($('#elem').css('top'));

Update: (as suggested by Ben): You should give the radix too:

parseInt($('#elem').css('top'), 10);

Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).

Checking if sys.argv[x] is defined

You can simply append the value of argv[1] to argv and then check if argv[1] doesn't equal the string you inputted Example:

from sys import argv
argv.append('SomeString')
if argv[1]!="SomeString":
            print(argv[1])

getting the X/Y coordinates of a mouse click on an image with jQuery

Here is a better script:

$('#mainimage').click(function(e)
{   
    var offset_t = $(this).offset().top - $(window).scrollTop();
    var offset_l = $(this).offset().left - $(window).scrollLeft();

    var left = Math.round( (e.clientX - offset_l) );
    var top = Math.round( (e.clientY - offset_t) );

    alert("Left: " + left + " Top: " + top);

});

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

Split string in C every white space

http://www.cplusplus.com/reference/clibrary/cstring/strtok/

Take a look at this, and use whitespace characters as the delimiter. If you need more hints let me know.

From the website:

char * strtok ( char * str, const char * delimiters );

On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.

Once the terminating null character of str is found in a call to strtok, all subsequent calls to this function (with a null pointer as the first argument) return a null pointer.

Parameters

  • str
    • C string to truncate.
    • Notice that this string is modified by being broken into smaller strings (tokens). Alternativelly [sic], a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
  • delimiters
    • C string containing the delimiter characters.
    • These may vary from one call to another.

Return Value

A pointer to the last token found in string. A null pointer is returned if there are no tokens left to retrieve.

Example

/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

Importing from a relative path in Python

Funny enough, a same problem I just met, and I get this work in following way:

combining with linux command ln , we can make thing a lot simper:

1. cd Proj/Client
2. ln -s ../Common ./

3. cd Proj/Server
4. ln -s ../Common ./

And, now if you want to import some_stuff from file: Proj/Common/Common.py into your file: Proj/Client/Client.py, just like this:

# in Proj/Client/Client.py
from Common.Common import some_stuff

And, the same applies to Proj/Server, Also works for setup.py process, a same question discussed here, hope it helps !

Error: Can't set headers after they are sent to the client

In my case, In a loop, I put res.render() so might have been tried to call multiple times.

Listing contents of a bucket with boto3

My s3 keys utility function is essentially an optimized version of @Hephaestus's answer:

import boto3


s3_paginator = boto3.client('s3').get_paginator('list_objects_v2')


def keys(bucket_name, prefix='/', delimiter='/', start_after=''):
    prefix = prefix[1:] if prefix.startswith(delimiter) else prefix
    start_after = (start_after or prefix) if prefix.endswith(delimiter) else start_after
    for page in s3_paginator.paginate(Bucket=bucket_name, Prefix=prefix, StartAfter=start_after):
        for content in page.get('Contents', ()):
            yield content['Key']

In my tests (boto3 1.9.84), it's significantly faster than the equivalent (but simpler) code:

import boto3


def keys(bucket_name, prefix='/', delimiter='/'):
    prefix = prefix[1:] if prefix.startswith(delimiter) else prefix
    bucket = boto3.resource('s3').Bucket(bucket_name)
    return (_.key for _ in bucket.objects.filter(Prefix=prefix))

As S3 guarantees UTF-8 binary sorted results, a start_after optimization has been added to the first function.

Understanding Fragment's setRetainInstance(boolean)

First of all, check out my post on retained Fragments. It might help.

Now to answer your questions:

Does the fragment also retain its view state, or will this be recreated on configuration change - what exactly is "retained"?

Yes, the Fragment's state will be retained across the configuration change. Specifically, "retained" means that the fragment will not be destroyed on configuration changes. That is, the Fragment will be retained even if the configuration change causes the underlying Activity to be destroyed.

Will the fragment be destroyed when the user leaves the activity?

Just like Activitys, Fragments may be destroyed by the system when memory resources are low. Whether you have your fragments retain their instance state across configuration changes will have no effect on whether or not the system will destroy the Fragments once you leave the Activity. If you leave the Activity (i.e. by pressing the home button), the Fragments may or may not be destroyed. If you leave the Activity by pressing the back button (thus, calling finish() and effectively destroying the Activity), all of the Activitys attached Fragments will also be destroyed.

Why doesn't it work with fragments on the back stack?

There are probably multiple reasons why it's not supported, but the most obvious reason to me is that the Activity holds a reference to the FragmentManager, and the FragmentManager manages the backstack. That is, no matter if you choose to retain your Fragments or not, the Activity (and thus the FragmentManager's backstack) will be destroyed on a configuration change. Another reason why it might not work is because things might get tricky if both retained fragments and non-retained fragments were allowed to exist on the same backstack.

Which are the use cases where it makes sense to use this method?

Retained fragments can be quite useful for propagating state information — especially thread management — across activity instances. For example, a fragment can serve as a host for an instance of Thread or AsyncTask, managing its operation. See my blog post on this topic for more information.

In general, I would treat it similarly to using onConfigurationChanged with an Activity... don't use it as a bandaid just because you are too lazy to implement/handle an orientation change correctly. Only use it when you need to.

Nested iframes, AKA Iframe Inception

Hey I got something that seems to be doing what you want a do. It involves some dirty copying but works. You can find the working code here

So here is the main html file :

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function(){
            Iframe = $('#frame1');

            Iframe.on('load', function(){
                IframeInner = Iframe.contents().find('iframe');

                IframeInnerClone = IframeInner.clone();

                IframeInnerClone.insertAfter($('#insertIframeAfter')).css({display:'none'});

                IframeInnerClone.on('load', function(){
                    IframeContents = IframeInner.contents();

                    YourNestedEl = IframeContents.find('div');

                    $('<div>Yeepi! I can even insert stuff!</div>').insertAfter(YourNestedEl)
                });
            });
        });
    </script>
</head>
<body>
    <div id="insertIframeAfter">Hello!!!!</div>
    <iframe id="frame1" src="Test_Iframe.html">

    </iframe>
</body>
</html>

As you can see, once the first Iframe is loaded, I get the second one and clone it. I then reinsert it in the dom, so I can get access to the onload event. Once this one is loaded, I retrieve the content from non-cloned one (must have loaded as well, since they use the same src). You can then do wathever you want with the content.

Here is the Test_Iframe.html file :

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div>Test_Iframe</div>
    <iframe src="Test_Iframe2.html">
    </iframe>
</body>
</html>

and the Test_Iframe2.html file :

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div>I am the second nested iframe</div>
</body>
</html>

How to hide soft keyboard on android after clicking outside EditText?

Method for show / hide soft keyboard

InputMethodManager inputMethodManager = (InputMethodManager) currentActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
    if (isShow) {
        if (currentActivity.getCurrentFocus() == null) {
            inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        } else {
            inputMethodManager.showSoftInput(currentActivity.getCurrentFocus(), InputMethodManager.SHOW_FORCED);    
        }

    } else {
        if (currentActivity.getCurrentFocus() == null) {
            inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, 0);
        } else {
            inputMethodManager.hideSoftInputFromInputMethod(currentActivity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);    
        }

    }

I hope they have been useful

Transmitting newline character "\n"

late to the party, but if anyone comes across this, javascript has a encodeURI method

Best way to "negate" an instanceof

Usually you don't want just an if but an else clause as well.

if(!(str instanceof String)) { /* do Something */ } 
else { /* do something else */ }

can be written as

if(str instanceof String) { /* do Something else */ } 
else { /* do something */ }

Or you can write the code so you don't need to know if its a String or not. e.g.

if(!(str instanceof String)) { str = str.toString(); } 

can be written as

str = str.toString();

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

Remove the standard.jar. It's apparently of old JSTL 1.0 version when the TLD URIs were without the /jsp path. With JSTL 1.2 as available here you don't need a standard.jar at all. Just the jstl-1.2.jar in /WEB-INF/lib is sufficient.

See also:

Calculate logarithm in python

From the documentation:

With one argument, return the natural logarithm of x (to base e).

With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base).

But the log10 is made available as math.log10(), which does not resort to log division if possible.

Transpose/Unzip Function (inverse of zip)?

>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> tuple([list(tup) for tup in zip(*original)])
(['a', 'b', 'c', 'd'], [1, 2, 3, 4])

Gives a tuple of lists as in the question.

list1, list2 = [list(tup) for tup in zip(*original)]

Unpacks the two lists.

Nuget connection attempt failed "Unable to load the service index for source"

If you are behind a company proxy and on Mac, just make sure your http/https checkboxes are checked and applied.

Rules for C++ string literals escape character

ascii is a package on linux you could download. for example sudo apt-get install ascii ascii

Usage: ascii [-dxohv] [-t] [char-alias...]
-t = one-line output  -d = Decimal table  -o = octal table  -x = hex table
-h = This help screen -v = version information
Prints all aliases of an ASCII character. Args may be chars, C \-escapes,
English names, ^-escapes, ASCII mnemonics, or numerics in decimal/octal/hex.`

This code can help you with C/C++ escape codes like \x0A

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

Differences in In python 2 and 3 version:

If you already have a default method in a class with same name and you re-declare as a same name it will appear as unbound-method call of that class instance when you wanted to instantiated it.

If you wanted class methods, but you declared them as instance methods instead.

An instance method is a method that is used when to create an instance of the class.

An example would be

   def user_group(self):   #This is an instance method
        return "instance method returning group"

Class label method:

   @classmethod
   def user_group(groups):   #This is an class-label method
        return "class method returning group"

In python 2 and 3 version differ the class @classmethod to write in python 3 it automatically get that as a class-label method and don't need to write @classmethod I think this might help you.

Java maximum memory on Windows XP

I got this error message when running a java program from a (limited memory) virtuozzo VPS. I had not specified any memory arguments, and found I had to explicitly set a small amount as the default must have been too high. E.g. -Xmx32m (obviously needs to be tuned depending on the program you run).

Just putting this here in case anyone else gets the above error message without specifying a large amount of memory like the questioner did.

Excel VBA to Export Selected Sheets to PDF

this is what i came up with as i was having issues with @asp8811 answer(maybe my own difficulties)

' this will do the put the first 2 sheets in a pdf ' Note each ws should be controlled with page breaks for printing which is a bit fiddly ' this will explicitly put the pdf in the current dir

Sub luxation2()
    Dim Filename As String
    Filename = "temp201"



Dim shtAry()
ReDim shtAry(1) ' this is an array of length 2
For i = 1 To 2
shtAry(i - 1) = Sheets(i).Name
Debug.Print Sheets(i).Name
Next i
Sheets(shtAry).Select
Debug.Print ThisWorkbook.Path & "\"


    ActiveSheet.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "/" & Filename & ".pdf", , , False

End Sub

A server with the specified hostname could not be found

I received A server with the specified hostname could not be found.. I figured out my MacOS app had turned on App Sandboxing. The easiest way to avoid problem is to turn off Sandbox.

How to set timeout on python's socket recv method?

As mentioned in previous replies, you can use something like: .settimeout() For example:

import socket

s = socket.socket()

s.settimeout(1) # Sets the socket to timeout after 1 second of no activity

host, port = "somehost", 4444
s.connect((host, port))

s.send("Hello World!\r\n")

try:
    rec = s.recv(100) # try to receive 100 bytes
except socket.timeout: # fail after 1 second of no activity
    print("Didn't receive data! [Timeout]")
finally:
    s.close()

I hope this helps!!

How to test if parameters exist in rails

I am a fan of

params[:one].present?

Just because it keeps the params[sym] form so it's easier to read.

How to change ProgressBar's progress indicator color in Android

In xml:

<ProgressBar
                    android:id="@+id/progressBar"
                    style="?android:attr/progressBarStyleInverse"
                    android:layout_width="60dp"
                    android:layout_height="60dp"
                    android:layout_margin="@dimen/dimen_10dp"


                 android:indeterminateTint="@{viewModel.getComplainStatusUpdate(position)}"
                    android:indeterminate="true"
                    android:indeterminateOnly="false"
                    android:max="100"
                    android:clickable="false"
                    android:indeterminateDrawable="@drawable/round_progress"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

ViewModel:

fun getComplainStatusUpdate(position: Int):Int{

                val list = myAllComplainList!!.getValue()
                if (list!!.get(position).complainStatus.equals("P")) {
                  //  progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));
                   // progressBar.setBackgroundResource(R.drawable.circle_shape)
                    return Color.RED
                } else if (list!!.get(position).complainStatus.equals("I")) {

                    return Color.GREEN
                } else {

                    return Color.GREEN
                }


return Color.CYAN
    }

How to get JSON from URL in JavaScript?

ES8(2017) try

obj = await (await fetch(url)).json();

_x000D_
_x000D_
async function load() {_x000D_
    let url = 'https://my-json-server.typicode.com/typicode/demo/db';_x000D_
    let obj = await (await fetch(url)).json();_x000D_
    console.log(obj);_x000D_
}_x000D_
_x000D_
load();
_x000D_
_x000D_
_x000D_

you can handle errors by try-catch

_x000D_
_x000D_
async function load() {_x000D_
    let url = 'http://query.yahooapis.com/v1/publ...';_x000D_
    let obj = null;_x000D_
    _x000D_
    try {_x000D_
        obj = await (await fetch(url)).json();_x000D_
    } catch(e) {_x000D_
        console.log('error');_x000D_
    }_x000D_
    _x000D_
    console.log(obj);_x000D_
}_x000D_
_x000D_
load();
_x000D_
_x000D_
_x000D_

How do I format a number to a dollar amount in PHP

If you just want something simple:

'$' . number_format($money, 2);

number_format()

How do I install cygwin components from the command line?

There is no tool specifically in the 'setup.exe' installer that offers the functionality of apt-get. There is, however, a command-line package installer for Cygwin that can be downloaded separately, but it is not entirely stable and relies on workarounds.

apt-cyg: http://github.com/transcode-open/apt-cyg

Check out the issues tab for the project to see the known problems.

Save string to the NSUserDefaults?

FirstView

    {
    NSMutableArray *array; }
- (void)viewDidLoad {
    [super viewDidLoad];
    array = [[NSMutableArray alloc]init];
    array = [[NSUserDefaults  standardUserDefaults]objectForKey:@"userlist"];

     NSLog(@"%lu",(unsigned long)array.count);
    if (array>0)
    {
        for (int i=0; i<array.count; i++)
        {
            NSDictionary *dict1 = @{@"Username":[[array valueForKey:@"Username"] objectAtIndex:i],@"Mobilenumber":[[array valueForKey:@"Mobilenumber"] objectAtIndex:i],@"Firstname":[[array valueForKey:@"Firstname"] objectAtIndex:i],@"Lastname":[[array valueForKey:@"Lastname"] objectAtIndex:i],@"dob":[[array valueForKey:@"dob"] objectAtIndex:i],@"image":[[array valueForKey:@"image"] objectAtIndex:i]};
            NSLog(@"%@",dict1);
            NSArray *array1 = [[NSArray alloc]initWithObjects:dict1, nil];
            [[NSUserDefaults standardUserDefaults] setObject:array1 forKey:@"UserList"];
        }

    }
     }

ImagePicker

     - (void)imagePickerController:(UIImagePickerController *)picker         didFinishPickingMediaWithInfo:(NSDictionary *)info {

    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    self.imaGe.image = chosenImage;

    [picker dismissViewControllerAnimated:YES completion:NULL];
     }
  • (IBAction)submitBton:(id)sender {

    NSMutableArray *array2 = [[NSMutableArray alloc]initWithArray: 
    [[NSUserDefaults standardUserDefaults]objectForKey:     
        @"userlist"]];                                
    
    UIImage *ima = _imaGe.image;
    NSData *imagedata = UIImageJPEGRepresentation(ima,100);
    
    NSDictionary *dict =  @{@"Username":_userTxt.text,@"Lastname":_lastTxt.text,@"Firstname":_firstTxt.text,@"Mobilenumber":_mobTxt.text,@"dob":_dobTxt.text,@"image":imagedata};
    
       [array2 addObject:dict];
      [[NSUserDefaults standardUserDefaults]setObject:array2    
      forKey:@"userlist"];
       NSLog(@"%@",array2);
    
      [self performSegueWithIdentifier:@"second" sender:self];
    
     }
    
    • (IBAction)chooseImg:(id)sender {

      UIImagePickerController *picker = [[UIImagePickerController
      alloc] init]; picker.delegate = self; picker.allowsEditing = YES; picker.sourceType =
      UIImagePickerControllerSourceTypePhotoLibrary; [self presentViewController:picker animated:YES completion:NULL];

      }


second View { NSMutableArray *arr; }

- (void)viewDidLoad {
    [super viewDidLoad];

     arr =[[NSMutableArray alloc]init];
    arr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userlist"]; }

#pragma mark- TableView DataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1; }

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return arr.count; }

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"tablecell";
    TableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellId];
    cell.userLbl.text =[[arr valueForKey:@"username"] objectAtIndex:indexPath.row];
    cell.ageLbl.text =[[arr valueForKey:@"dob"] objectAtIndex:indexPath.row];
    cell.profileImg.image =[UIImage imageNamed:[[arr valueForKey:@"image"] objectAtIndex:indexPath.row]];
    return cell; }

python plot normal distribution

import math  
import matplotlib.pyplot as plt
import numpy
import pandas as pd


def normal_pdf(x, mu=0, sigma=1):
    sqrt_two_pi = math.sqrt(math.pi * 2)
    return math.exp(-(x - mu) ** 2 / 2 / sigma ** 2) / (sqrt_two_pi * sigma)


df = pd.DataFrame({'x1': numpy.arange(-10, 10, 0.1), 'y1': map(normal_pdf, numpy.arange(-10, 10, 0.1))})

plt.plot('x1', 'y1', data=df, marker='o', markerfacecolor='blue', markersize=5, color='skyblue', linewidth=1)
plt.show()

enter image description here

Pass Javascript Array -> PHP

You could use JSON.stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it.

Oracle SQL update based on subquery between two tables

There are two ways to do what you are trying

One is a Multi-column Correlated Update

UPDATE PRODUCTION a
SET (name, count) = (
  SELECT name, count
  FROM STAGING b
  WHERE a.ID = b.ID);

DEMO

You can use merge

MERGE INTO PRODUCTION a
USING ( select id, name, count 
          from STAGING ) b
ON ( a.id = b.id )
WHEN MATCHED THEN 
UPDATE SET  a.name = b.name,
            a.count = b.count

DEMO

Read response headers from API response - Angular 5 + TypeScript

You can get headers using below code

let main_headers = {}
this.http.post(url,
  {email: this.username, password: this.password},
  {'headers' : new HttpHeaders ({'Content-Type' : 'application/json'}), 'responseType': 'text', observe:'response'})
  .subscribe(response => {
    const keys = response.headers.keys();
    let headers = keys.map(key => {
      `${key}: ${response.headers.get(key)}`
        main_headers[key] = response.headers.get(key)
       }
      );
  });

later we can get the required header form the json object.

header_list['X-Token']

Blocks and yields in Ruby

There are two points I want to make about yield here. First, while a lot of answers here talk about different ways to pass a block to a method which uses yield, let's also talk about the control flow. This is especially relevant since you can yield MULTIPLE times to a block. Let's take a look at an example:

class Fruit
  attr_accessor :kinds

  def initialize 
    @kinds = %w(orange apple pear banana)
  end

  def each 
    puts 'inside each'
    3.times { yield (@kinds.tap {|kinds| puts "selecting from #{kinds}"} ).sample }
  end  
end

f = Fruit.new
f.each do |kind|
  puts 'inside block'
end    

=> inside each
=> selecting from ["orange", "apple", "pear", "banana"]
=> inside block
=> selecting from ["orange", "apple", "pear", "banana"]
=> inside block
=> selecting from ["orange", "apple", "pear", "banana"]
=> inside block

When the each method is invoked, it executes line by line. Now when we get to the 3.times block, this block will be invoked 3 times. Each time it invokes yield. That yield is linked to the block associated with the method that called the each method. It is important to notice that each time yield is invoked, it returns control back to the block of the each method in client code. Once the block is finished executing, it returns back to the 3.times block. And this happens 3 times. So that block in client code is invoked on 3 separate occasions since yield is explicitly called 3 separate times.

My second point is about enum_for and yield. enum_for instantiates the Enumerator class and this Enumerator object also responds to yield.

class Fruit
  def initialize
    @kinds = %w(orange apple)
  end

  def kinds
    yield @kinds.shift
    yield @kinds.shift
  end
end

f = Fruit.new
enum = f.to_enum(:kinds)
enum.next
 => "orange" 
enum.next
 => "apple" 

So notice every time we invoke kinds with the external iterator, it will invoke yield only once. The next time we call it, it will invoke the next yield and so on.

There's an interesting tidbit with regards to enum_for. The documentation online states the following:

enum_for(method = :each, *args) ? enum
Creates a new Enumerator which will enumerate by calling method on obj, passing args if any.

str = "xyz"
enum = str.enum_for(:each_byte)
enum.each { |b| puts b }    
# => 120
# => 121
# => 122

If you do not specify a symbol as an argument to enum_for, ruby will hook the enumerator to the receiver's each method. Some classes do not have an each method, like the String class.

str = "I like fruit"
enum = str.to_enum
enum.next
=> NoMethodError: undefined method `each' for "I like fruit":String

Thus, in the case of some objects invoked with enum_for, you must be explicit as to what your enumerating method will be.

Create a .txt file if doesn't exist, and if it does append a new line

File.AppendAllText adds a string to a file. It also creates a text file if the file does not exist. If you don't need to read content, it's very efficient. The use case is logging.

File.AppendAllText("C:\\log.txt", "hello world\n");

XAMPP Object not found error

well, i had a similar problem, so when i entered, lets say: localhost/test.php I would got Object not found warning! I solved my problem when i realized that windows changed my test.php into this test.php.txt. I changed my extension and voila! problem solved I could finaly acceses localhost/test.php.

Returning IEnumerable<T> vs. IQueryable<T>

The top answer is good but it doesn't mention expression trees which explain "how" the two interfaces differ. Basically, there are two identical sets of LINQ extensions. Where(), Sum(), Count(), FirstOrDefault(), etc all have two versions: one that accepts functions and one that accepts expressions.

  • The IEnumerable version signature is: Where(Func<Customer, bool> predicate)

  • The IQueryable version signature is: Where(Expression<Func<Customer, bool>> predicate)

You've probably been using both of those without realizing it because both are called using identical syntax:

e.g. Where(x => x.City == "<City>") works on both IEnumerable and IQueryable

  • When using Where() on an IEnumerable collection, the compiler passes a compiled function to Where()

  • When using Where() on an IQueryable collection, the compiler passes an expression tree to Where(). An expression tree is like the reflection system but for code. The compiler converts your code into a data structure that describes what your code does in a format that's easily digestible.

Why bother with this expression tree thing? I just want Where() to filter my data. The main reason is that both the EF and Linq2SQL ORMs can convert expression trees directly into SQL where your code will execute much faster.

Oh, that sounds like a free performance boost, should I use AsQueryable() all over the place in that case? No, IQueryable is only useful if the underlying data provider can do something with it. Converting something like a regular List to IQueryable will not give you any benefit.

Key existence check in HashMap

Do you mean that you've got code like

if(map.containsKey(key)) doSomethingWith(map.get(key))

all over the place ? Then you should simply check whether map.get(key) returned null and that's it. By the way, HashMap doesn't throw exceptions for missing keys, it returns null instead. The only case where containsKey is needed is when you're storing null values, to distinguish between a null value and a missing value, but this is usually considered bad practice.

Java: Date from unix timestamp

Sometimes you need to work with adjustments.

Don't use cast to long! Use nanoadjustment.

For example, using Oanda Java API for trading you can get datetime as UNIX format.

For example: 1592523410.590566943

    System.out.println("instant with nano = " + Instant.ofEpochSecond(1592523410, 590566943));
    System.out.println("instant = " + Instant.ofEpochSecond(1592523410));

you get:

instant with nano = 2020-06-18T23:36:50.590566943Z
instant = 2020-06-18T23:36:50Z

Also, use:

 Date date = Date.from( Instant.ofEpochSecond(1592523410, 590566943) );

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

The MySQL dependency should be like the following syntax in the pom.xml file.

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>

Make sure the syntax, groupId, artifactId, Version has included in the dependancy.

socket.error: [Errno 48] Address already in use

You can allow the server to reuse an address with allow_reuse_address.

Whether the server will allow the reuse of an address. This defaults to False, and can be set in subclasses to change the policy.

import SimpleHTTPServer, SocketServer
PORT = 8000
httpd = SocketServer.TCPServer(("", PORT), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.allow_reuse_address = True
print "Serving at port", PORT
httpd.serve_forever()

How to use pip on windows behind an authenticating proxy

This is how I set it up:

  1. Open the command prompt(CMD) as administrator.
  2. Export the proxy settings :

    set http_proxy=http://username:password@proxyAddress:port

    set https_proxy=https://username:password@proxyAddress:port

  3. Install the package you want to install:

    pip install PackageName

For example:

Example

Find object by its property in array of objects with AngularJS way

For complete M B answer, if you want to access to an specific attribute of this object already filtered from the array in your HTML, you will have to do it in this way:

{{ (myArray | filter : {'id':73})[0].name }}

So, in this case, it will print john in the HTML.

Regards!

Github: Can I see the number of downloads for a repo?

Update 2019:

Ustin's answer points to:


Update 2017

You still can use the GitHub API to get the download count for your releases (which is not exactly what was asked)
See "Get a single release", the download_count field.

There is no longer a traffic screen mentioning the number of repo clones.
Instead, you have to rely on third-party services like:

Git 2.14.2 release


Update August 2014

GitHub also proposes the number of clones for repo in its Traffic Graph:
See "Clone Graphs"

http://i.stack.imgur.com/uycEZ.png


Update October 2013

As mentioned below by andyberry88, and as I detailed last July, GitHub now proposes releases (see its API), which has a download_count field.

Michele Milidoni, in his (upvoted) answer, does use that field in his python script.
(very small extract)

c.setopt(c.URL, 'https://api.github.com/repos/' + full_name + '/releases')
for p in myobj:
    if "assets" in p:
        for asset in p['assets']:
            print (asset['name'] + ": " + str(asset['download_count']) +
                   " downloads")

Original answer (December 2010)

I am not sure you can see that information (if it is recorded at all), because I don't see it in the GitHub Repository API:

$ curl http://github.com/api/v2/yaml/repos/show/schacon/grit
---
repository:
  :name: grit
  :owner: schacon
  :source: mojombo/grit # The original repo at top of the pyramid
  :parent: defunkt/grit # This repo's direct parent
  :description: Grit is a Ruby library for extracting information from a
  git repository in an object oriented manner - this fork tries to
  intergrate as much pure-ruby functionality as possible
  :forks: 4
  :watchers: 67
  :private: false
  :url: http://github.com/schacon/grit
  :fork: true
  :homepage: http://grit.rubyforge.org/
  :has_wiki: true
  :has_issues: false
  :has_downloads: true

You can only see if it has downloads or not.


Adam Jagosz reports in the comments:

I got it to work with

 curl -H "Accept: application/vnd.github.v3+json"   https://api.github.com/repos/:user/:repo/releases

A couple of things that I had wrong:

  • I needed an actual Github release (not just git tag, even though Github does display those under releases, ugh).
  • And the release needs an asset file other than the zipped source that is added automatically in order to get the download count.

Making interface implementations async

An abstract class can be used instead of an interface (in C# 7.3).

// Like interface
abstract class IIO
{
    public virtual async Task<string> DoOperation(string Name)
    {
        throw new NotImplementedException(); // throwing exception
        // return await Task.Run(() => { return ""; }); // or empty do
    }
}

// Implementation
class IOImplementation : IIO
{
    public override async Task<string> DoOperation(string Name)
    {
        return await await Task.Run(() =>
        {
            if(Name == "Spiderman")
                return "ok";
            return "cancel";
        }); 
    }
}

Implicit type conversion rules in C++ operators

Whole chapter 4 talks about conversions, but I think you should be mostly interested in these :

4.5 Integral promotions [conv.prom]
An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; other-
wise, the source rvalue can be converted to an rvalue of type unsigned int.
An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2) can be converted to an rvalue of the first
of the following types that can represent all the values of its underlying type: int, unsigned int,
long, or unsigned long.
An rvalue for an integral bit-field (9.6) can be converted to an rvalue of type int if int can represent all
the values of the bit-field; otherwise, it can be converted to unsigned int if unsigned int can rep-
resent all the values of the bit-field. If the bit-field is larger yet, no integral promotion applies to it. If the
bit-field has an enumerated type, it is treated as any other value of that type for promotion purposes.
An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true
becoming one.
These conversions are called integral promotions.

4.6 Floating point promotion [conv.fpprom]
An rvalue of type float can be converted to an rvalue of type double. The value is unchanged.
This conversion is called floating point promotion.

Therefore, all conversions involving float - the result is float.

Only the one involving both int - the result is int : int / int = int

Linux error while loading shared libraries: cannot open shared object file: No such file or directory

All I had to do was run:

sudo apt-get install libfontconfig1

I was in the folder located at /usr/lib/x86_64-linux-gnu and it worked perfectly.

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

jQuery/Javascript function to clear all the fields of a form

Set the val to ""

function clear_form_elements(ele) {

        $(ele).find(':input').each(function() {
            switch(this.type) {
                case 'password':
                case 'select-multiple':
                case 'select-one':
                case 'text':
                case 'textarea':
                    $(this).val('');
                    break;
                case 'checkbox':
                case 'radio':
                    this.checked = false;
            }
        });

    }

<input onclick="clear_form_elements(this.form)" type="button" value="Clear All" />  
<input onclick="clear_form_elements('#example_1')" type="button" value="Clear Section 1" />
<input onclick="clear_form_elements('#example_2')" type="button" value="Clear Section 2" />
<input onclick="clear_form_elements('#example_3')" type="button" value="Clear Section 3" />

You could also try something like this:

  function clearForm(form) {

    // iterate over all of the inputs for the form

    // element that was passed in

    $(':input', form).each(function() {

      var type = this.type;

      var tag = this.tagName.toLowerCase(); // normalize case

      // it's ok to reset the value attr of text inputs,

      // password inputs, and textareas

      if (type == 'text' || type == 'password' || tag == 'textarea')

        this.value = "";

      // checkboxes and radios need to have their checked state cleared

      // but should *not* have their 'value' changed

      else if (type == 'checkbox' || type == 'radio')

        this.checked = false;

      // select elements need to have their 'selectedIndex' property set to -1

      // (this works for both single and multiple select elements)

      else if (tag == 'select')

        this.selectedIndex = -1;

    });

  };

More info here and here

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

How do I get the path and name of the file that is currently executing?

import os
os.path.dirname(os.path.abspath(__file__))

No need for inspect or any other library.

This worked for me when I had to import a script (from a different directory then the executed script), that used a configuration file residing in the same folder as the imported script.

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

Difference between numpy dot() and Python 3.5+ matrix multiplication @

Just FYI, @ and its numpy equivalents dot and matmul are all equally fast. (Plot created with perfplot, a project of mine.)

enter image description here

Code to reproduce the plot:

import perfplot
import numpy


def setup(n):
    A = numpy.random.rand(n, n)
    x = numpy.random.rand(n)
    return A, x


def at(data):
    A, x = data
    return A @ x


def numpy_dot(data):
    A, x = data
    return numpy.dot(A, x)


def numpy_matmul(data):
    A, x = data
    return numpy.matmul(A, x)


perfplot.show(
    setup=setup,
    kernels=[at, numpy_dot, numpy_matmul],
    n_range=[2 ** k for k in range(15)],
)

Bootstrap 3 Navbar with Logo

Add the following to the .navbar-brand class

.navbar-brand
{
  padding: 0px; // this allows the image to occupy all the padding space of the navbar--brand
}

.navbar-brand > img
{
   height: 100%; // set height to occupy full height space on the navbar-brand
   width: auto; // width should be auto to allow img to scale accordingly
   max-height: 100%; // optional
   mrgin: 0 auto; // optional
}

What is the difference between IQueryable<T> and IEnumerable<T>?

IEnumerable is refering to a collection but IQueryable is just a query and it will be generated inside a Expression Tree.we will run this query to get data from database.

How to add `style=display:"block"` to an element using jQuery?

$("#YourElementID").css("display","block");

Edit: or as dave thieben points out in his comment below, you can do this as well:

$("#YourElementID").css({ display: "block" });

Passing Objects By Reference or Value in C#

I guess its clearer when you do it like this. I recommend downloading LinqPad to test things like this.

void Main()
{
    var Person = new Person(){FirstName = "Egli", LastName = "Becerra"};

    //Will update egli
    WontUpdate(Person);
    Console.WriteLine("WontUpdate");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");

    UpdateImplicitly(Person);
    Console.WriteLine("UpdateImplicitly");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");

    UpdateExplicitly(ref Person);
    Console.WriteLine("UpdateExplicitly");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");
}

//Class to test
public class Person{
    public string FirstName {get; set;}
    public string LastName {get; set;}

    public string printName(){
        return $"First name: {FirstName} Last name:{LastName}";
    }
}

public static void WontUpdate(Person p)
{
    //New instance does jack...
    var newP = new Person(){FirstName = p.FirstName, LastName = p.LastName};
    newP.FirstName = "Favio";
    newP.LastName = "Becerra";
}

public static void UpdateImplicitly(Person p)
{
    //Passing by reference implicitly
    p.FirstName = "Favio";
    p.LastName = "Becerra";
}

public static void UpdateExplicitly(ref Person p)
{
    //Again passing by reference explicitly (reduntant)
    p.FirstName = "Favio";
    p.LastName = "Becerra";
}

And that should output

WontUpdate

First name: Egli, Last name: Becerra

UpdateImplicitly

First name: Favio, Last name: Becerra

UpdateExplicitly

First name: Favio, Last name: Becerra

.NET DateTime to SqlDateTime Conversion

Also please remember resolutions [quantum of time] are different.

http://msdn.microsoft.com/en-us/library/system.data.sqltypes.sqldatetime.aspx

SQL one is 3.33 ms and .net one is 100 ns.

Setting an environment variable before a command in Bash is not working for the second command in a pipe

A simple approach is to make use of ;

For example:

ENV=prod; ansible-playbook -i inventories/$ENV --extra-vars "env=$ENV"  deauthorize_users.yml --check

Finding second occurrence of a substring in a string in Java

int first = string.indexOf("is");
int second = string.indexOf("is", first + 1);

This overload starts looking for the substring from the given index.

Simple pagination in javascript

So you can use a library for pagination logic https://github.com/pagino/pagino-js

How to build query string with Javascript

2k20 update: use Josh's solution with URLSearchParams.toString().

Old answer:


Without jQuery

var params = {
    parameter1: 'value_1',
    parameter2: 'value 2',
    parameter3: 'value&3' 
};

var esc = encodeURIComponent;
var query = Object.keys(params)
    .map(k => esc(k) + '=' + esc(params[k]))
    .join('&');

For browsers that don't support arrow function syntax which requires ES5, change the .map... line to

    .map(function(k) {return esc(k) + '=' + esc(params[k]);})

Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

This should do the trick!

// convert object => json
$json = json_encode($myObject);

// convert json => object
$obj = json_decode($json);

Here's an example

$foo = new StdClass();
$foo->hello = "world";
$foo->bar = "baz";

$json = json_encode($foo);
echo $json;
//=> {"hello":"world","bar":"baz"}

print_r(json_decode($json));
// stdClass Object
// (
//   [hello] => world
//   [bar] => baz
// )

If you want the output as an Array instead of an Object, pass true to json_decode

print_r(json_decode($json, true));
// Array
// (
//   [hello] => world
//   [bar] => baz
// )    

More about json_encode()

See also: json_decode()

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

These are use in ruby on rails :-

<% %> :-

The <% %> tags are used to execute Ruby code that does not return anything, such as conditions, loops or blocks. Eg :-

<h1>Names of all the people</h1>
<% @people.each do |person| %>
  Name: <%= person.name %><br>
<% end %>

<%= %> :-

use to display the content .

Name: <%= person.name %><br>

<% -%>:-

Rails extends ERB, so that you can suppress the newline simply by adding a trailing hyphen to tags in Rails templates

<%# %>:-

comment out the code

<%# WRONG %>
Hi, Mr. <% puts "Frodo" %>

Paramiko's SSHClient with SFTP

paramiko.SFTPClient

Sample Usage:

import paramiko
paramiko.util.log_to_file("paramiko.log")

# Open a transport
host,port = "example.com",22
transport = paramiko.Transport((host,port))

# Auth    
username,password = "bar","foo"
transport.connect(None,username,password)

# Go!    
sftp = paramiko.SFTPClient.from_transport(transport)

# Download
filepath = "/etc/passwd"
localpath = "/home/remotepasswd"
sftp.get(filepath,localpath)

# Upload
filepath = "/home/foo.jpg"
localpath = "/home/pony.jpg"
sftp.put(localpath,filepath)

# Close
if sftp: sftp.close()
if transport: transport.close()

Get HTML code from website in C#

Getting HTML code from a website. You can use code like this.

string urlAddress = "http://google.com";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

if (response.StatusCode == HttpStatusCode.OK)
{
  Stream receiveStream = response.GetResponseStream();
  StreamReader readStream = null;

  if (String.IsNullOrWhiteSpace(response.CharacterSet))
     readStream = new StreamReader(receiveStream);
  else
     readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));

  string data = readStream.ReadToEnd();

  response.Close();
  readStream.Close();
}

This will give you the returned HTML code from the website. But find text via LINQ is not that easy. Perhaps it is better to use regular expression but that does not play well with HTML code

Resize background image in div using css

With the background-size property in those browsers which support this very new feature of CSS.

How to enable MySQL Query Log?

Not exactly an answer to the question because the question already has great answers. This is a side info. Enabling general_log really put a dent on MySQL performance. I left general_log =1 accidentally on a production server and spent hours finding out why performance was not comparable to a similar setup on other servers. Then I found this which explains the impact of enabling general log. http://www.fromdual.com/general_query_log_vs_mysql_performance.

Gist of the story, don't put general_log=1 in the .cnf file. Instead use set global general_log =1 for a brief duration just to log enough to find out what you are trying to find out and then turn it off.

use mysql SUM() in a WHERE clause

When using aggregate functions to filter, you must use a HAVING statement.

SELECT *
FROM tblMoney
HAVING Sum(CASH) > 500

How to generate xsd from wsdl

You can use SoapUI: http://www.soapui.org/ This is a generally handy program. Make a new project, connect to the WSDL link, then right click on the project and say "Show interface viewer". Under "Schemas" on the left you can see the XSD.

SoapUI can do many things though!

What's the best way to limit text length of EditText in Android

This is a custom EditText Class that allow Length filter to live along with other filters. Thanks to Tim Gallagher's Answer (below)

import android.content.Context;
import android.text.InputFilter;
import android.util.AttributeSet;
import android.widget.EditText;


public class EditTextMultiFiltering extends EditText{

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

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

    public EditTextMultiFiltering(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setMaxLength(int length) {
        InputFilter curFilters[];
        InputFilter.LengthFilter lengthFilter;
        int idx;

        lengthFilter = new InputFilter.LengthFilter(length);

        curFilters = this.getFilters();
        if (curFilters != null) {
            for (idx = 0; idx < curFilters.length; idx++) {
                if (curFilters[idx] instanceof InputFilter.LengthFilter) {
                    curFilters[idx] = lengthFilter;
                    return;
                }
            }

            // since the length filter was not part of the list, but
            // there are filters, then add the length filter
            InputFilter newFilters[] = new InputFilter[curFilters.length + 1];
            System.arraycopy(curFilters, 0, newFilters, 0, curFilters.length);
            newFilters[curFilters.length] = lengthFilter;
            this.setFilters(newFilters);
        } else {
            this.setFilters(new InputFilter[] { lengthFilter });
        }
    }
}

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

I fixed this problem employing the two procedures of :

  1. In Eclipse->'Project' menu -> 'Java Compiler' -> set 'Compiler compliance level' = 1.6 check on 'Use default compliance settings' Set 'Generated .class compatibility' = 1.6 Set 'Source compatibilty' = 1.6

  2. Then go to 'Windows' menu --> 'Preferences' -->'Java' , expand 'Java' --> 'Compiler' -->Set 'Compiler compliance level' = 1.6

Hint: Source compatibility must be equal to or less than compliance level.

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

CSS table-cell equal width

Replace

  <div style="display:table;">
    <div style="display:table-cell;"></div>
    <div style="display:table-cell;"></div>
  </div>

with

  <table>
    <tr><td>content cell1</td></tr>
    <tr><td>content cell1</td></tr>
  </table>

Look at all the issues surrounding trying to make divs perform like tables. They had to add table-xxx to mimic table layouts

Tables are supported and work very well in all browsers. Why ditch them? the fact that they had to mimic them is proof they did their job and well.

In my opinion use the best tool for the job and if you want tabulated data or something that resembles tabulated data tables just work.

Very Late reply I know but worth voicing.

How to fetch the row count for all tables in a SQL SERVER database

select all rows from the information_schema.tables view, and issue a count(*) statement for each entry that has been returned from that view.

declare c_tables cursor fast_forward for
select table_name from information_schema.tables

open c_tables
declare @tablename varchar(255)
declare @stmt nvarchar(2000)
declare @rowcount int
fetch next from c_tables into @tablename

while @@fetch_status = 0
begin

    select @stmt = 'select @rowcount = count(*) from ' + @tablename

    exec sp_executesql @stmt, N'@rowcount int output', @rowcount=@rowcount OUTPUT

    print N'table: ' + @tablename + ' has ' + convert(nvarchar(1000),@rowcount) + ' rows'

    fetch next from c_tables into @tablename

end

close c_tables
deallocate c_tables

Using HTML5 file uploads with AJAX and jQuery

With jQuery (and without FormData API) you can use something like this:

function readFile(file){
   var loader = new FileReader();
   var def = $.Deferred(), promise = def.promise();

   //--- provide classic deferred interface
   loader.onload = function (e) { def.resolve(e.target.result); };
   loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
   loader.onerror = loader.onabort = function (e) { def.reject(e); };
   promise.abort = function () { return loader.abort.apply(loader, arguments); };

   loader.readAsBinaryString(file);

   return promise;
}

function upload(url, data){
    var def = $.Deferred(), promise = def.promise();
    var mul = buildMultipart(data);
    var req = $.ajax({
        url: url,
        data: mul.data,
        processData: false,
        type: "post",
        async: true,
        contentType: "multipart/form-data; boundary="+mul.bound,
        xhr: function() {
            var xhr = jQuery.ajaxSettings.xhr();
            if (xhr.upload) {

                xhr.upload.addEventListener('progress', function(event) {
                    var percent = 0;
                    var position = event.loaded || event.position; /*event.position is deprecated*/
                    var total = event.total;
                    if (event.lengthComputable) {
                        percent = Math.ceil(position / total * 100);
                        def.notify(percent);
                    }                    
                }, false);
            }
            return xhr;
        }
    });
    req.done(function(){ def.resolve.apply(def, arguments); })
       .fail(function(){ def.reject.apply(def, arguments); });

    promise.abort = function(){ return req.abort.apply(req, arguments); }

    return promise;
}

var buildMultipart = function(data){
    var key, crunks = [], bound = false;
    while (!bound) {
        bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
        for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
    }

    for (var key = 0, l = data.length; key < l; key++){
        if (typeof(data[key].value) !== "string") {
            crunks.push("--"+bound+"\r\n"+
                "Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
                "Content-Type: application/octet-stream\r\n"+
                "Content-Transfer-Encoding: binary\r\n\r\n"+
                data[key].value[0]);
        }else{
            crunks.push("--"+bound+"\r\n"+
                "Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
                data[key].value);
        }
    }

    return {
        bound: bound,
        data: crunks.join("\r\n")+"\r\n--"+bound+"--"
    };
};

//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
   var formData = form.find(":input:not('#file')").serializeArray();
   formData.file = [fileData, $file[0].files[0].name];
   upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});

With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})

How do I replicate a \t tab space in HTML?

You can enter the tab character (U+0009 CHARACTER TABULATION, commonly known as TAB or HT) using the character reference &#9;. It is equivalent to the tab character as such. Thus, from the HTML viewpoint, there is no need to “escape” it using the character reference; but you may do so e.g. if your editing program does not let you enter the character conveniently.

On the other hand, the tab character is in most contexts equivalent to a normal space in HTML. It does not “tabulate”, it’s just a word space.

The tab character has, however, special handling in pre elements and (although this not that well described in specifications) in textarea and xmp element (in the latter, character references cannot be used, only the tab character as such). This is described somewhat misleadingly in HTML specifications, e.g. in HTML 4.01: “[Inside the pre element, ] the horizontal tab character (decimal 9 in [ISO10646] and [ISO88591] ) is usually interpreted by visual user agents as the smallest non-zero number of spaces necessary to line characters up along tab stops that are every 8 characters. We strongly discourage using horizontal tabs in preformatted text since it is common practice, when editing, to set the tab-spacing to other values, leading to misaligned documents.”

The warnings are unnecessary except as regards to the potential mismatch of tabbing in your authoring software and HTML rendering in browsers. The real reason for avoiding horizontal tab is that it a coarse and simplistic tool as compared with tables for presenting tabular material. And in displaying computer source programs, it is better to use just spaces inside pre, since the default tab stops at every 8 characters are quite unsuitable for any normal code indentation style.

In addition, in CSS, you can specify white-space: pre (or, with slightly more limited browser support, white-space: pre-wrap) to make a normal HTML element, like div or p, rendered like pre, so that all whitespace is preserved and horizontal tab has the “tabbing” effect.

In CSS Text Module Level 3 (Last Call working draft, i.e. proceeding towards maturity), there is also the tab-size property, which can be used to set the distance between tab stops, e.g. tab-size: 3. It’s supported by newest versions of most browsers, but not IE (not even IE 11).

Best way to import Observable from rxjs

Rxjs v 6.*

It got simplified with newer version of rxjs .

1) Operators

import {map} from 'rxjs/operators';

2) Others

import {Observable,of, from } from 'rxjs';

Instead of chaining we need to pipe . For example

Old syntax :

source.map().switchMap().subscribe()

New Syntax:

source.pipe(map(), switchMap()).subscribe()

Note: Some operators have a name change due to name collisions with JavaScript reserved words! These include:

do -> tap,

catch -> catchError

switch -> switchAll

finally -> finalize


Rxjs v 5.*

I am writing this answer partly to help myself as I keep checking docs everytime I need to import an operator . Let me know if something can be done better way.

1) import { Rx } from 'rxjs/Rx';

This imports the entire library. Then you don't need to worry about loading each operator . But you need to append Rx. I hope tree-shaking will optimize and pick only needed funcionts( need to verify ) As mentioned in comments , tree-shaking can not help. So this is not optimized way.

public cache = new Rx.BehaviorSubject('');

Or you can import individual operators .

This will Optimize your app to use only those files :

2) import { _______ } from 'rxjs/_________';

This syntax usually used for main Object like Rx itself or Observable etc.,

Keywords which can be imported with this syntax

 Observable, Observer, BehaviorSubject, Subject, ReplaySubject

3) import 'rxjs/add/observable/__________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

import { empty } from 'rxjs/observable/empty';
import { concat} from 'rxjs/observable/concat';

These are usually accompanied with Observable directly. For example

Observable.from()
Observable.of()

Other such keywords which can be imported using this syntax:

concat, defer, empty, forkJoin, from, fromPromise, if, interval, merge, of, 
range, throw, timer, using, zip

4) import 'rxjs/add/operator/_________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

import { filter } from 'rxjs/operators/filter';
import { map } from 'rxjs/operators/map';

These usually come in the stream after the Observable is created. Like flatMap in this code snippet:

Observable.of([1,2,3,4])
          .flatMap(arr => Observable.from(arr));

Other such keywords using this syntax:

audit, buffer, catch, combineAll, combineLatest, concat, count, debounce, delay, 
distinct, do, every, expand, filter, finally, find , first, groupBy,
ignoreElements, isEmpty, last, let, map, max, merge, mergeMap, min, pluck, 
publish, race, reduce, repeat, scan, skip, startWith, switch, switchMap, take, 
takeUntil, throttle, timeout, toArray, toPromise, withLatestFrom, zip

FlatMap: flatMap is alias to mergeMap so we need to import mergeMap to use flatMap.


Note for /add imports :

We only need to import once in whole project. So its advised to do it at a single place. If they are included in multiple files, and one of them is deleted, the build will fail for wrong reasons.

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

There are some good answers for it. I want to explain it through demo per Doc

  • CMD defines default commands and/or parameters for a container. CMD is an instruction that is best to use if you need a default command which users can easily override. If a Dockerfile has multiple CMDs, it only applies the instructions from the last one.
  • ENTRYPOINT is preferred when you want to define a container with a specific executable.

You cannot override an ENTRYPOINT when starting a container unless you add the --entrypoint flag.

  1. CMD

Docker file

  FROM centos:8.1.1911

  CMD ["echo", "Hello Docker"]

Run result

$ sudo docker run <image-id>
Hello Docker
$ sudo docker run <image-id> hostname   # hostname is exec to override CMD
244be5006f32
  1. ENTRYPOINT

Docker file

  FROM centos:8.1.1911

  ENTRYPOINT ["echo", "Hello Docker"]

Run result

$ sudo docker run <image-id>
Hello Docker
$ sudo docker run <image-id> hostname   # hostname as parameter to exec
Hello Docker hostname
  1. There are many situations in which combining CMD and ENTRYPOINT would be the best solution for your Docker container. In such cases, the executable is defined with ENTRYPOINT, while CMD specifies the default parameter.

Docker file

  FROM centos:8.1.1911

  ENTRYPOINT ["echo", "Hello"]
  CMD ["Docker"]

Run result

$ sudo docker run <image-id>
Hello Docker
$ sudo docker run <image-id> Ben
Hello Ben

List all files and directories in a directory + subdirectories

The following example the fastest (not parallelized) way list files and sub-folders in a directory tree handling exceptions. It would be faster to use Directory.EnumerateDirectories using SearchOption.AllDirectories to enumerate all directories, but this method will fail if hits a UnauthorizedAccessException or PathTooLongException.

Uses the generic Stack collection type, which is a last in first out (LIFO) stack and does not use recursion. From https://msdn.microsoft.com/en-us/library/bb513869.aspx, allows you to enumerate all sub-directories and files and deal effectively with those exceptions.

    public class StackBasedIteration
{
    static void Main(string[] args)
    {
        // Specify the starting folder on the command line, or in 
        // Visual Studio in the Project > Properties > Debug pane.
        TraverseTree(args[0]);

        Console.WriteLine("Press any key");
        Console.ReadKey();
    }

    public static void TraverseTree(string root)
    {
        // Data structure to hold names of subfolders to be
        // examined for files.
        Stack<string> dirs = new Stack<string>(20);

        if (!System.IO.Directory.Exists(root))
        {
            throw new ArgumentException();
        }
        dirs.Push(root);

        while (dirs.Count > 0)
        {
            string currentDir = dirs.Pop();
            string[] subDirs;
            try
            {
                subDirs = System.IO.Directory.EnumerateDirectories(currentDir); //TopDirectoryOnly
            }
            // An UnauthorizedAccessException exception will be thrown if we do not have
            // discovery permission on a folder or file. It may or may not be acceptable 
            // to ignore the exception and continue enumerating the remaining files and 
            // folders. It is also possible (but unlikely) that a DirectoryNotFound exception 
            // will be raised. This will happen if currentDir has been deleted by
            // another application or thread after our call to Directory.Exists. The 
            // choice of which exceptions to catch depends entirely on the specific task 
            // you are intending to perform and also on how much you know with certainty 
            // about the systems on which this code will run.
            catch (UnauthorizedAccessException e)
            {                    
                Console.WriteLine(e.Message);
                continue;
            }
            catch (System.IO.DirectoryNotFoundException e)
            {
                Console.WriteLine(e.Message);
                continue;
            }

            string[] files = null;
            try
            {
                files = System.IO.Directory.EnumerateFiles(currentDir);
            }

            catch (UnauthorizedAccessException e)
            {

                Console.WriteLine(e.Message);
                continue;
            }

            catch (System.IO.DirectoryNotFoundException e)
            {
                Console.WriteLine(e.Message);
                continue;
            }
            // Perform the required action on each file here.
            // Modify this block to perform your required task.
            foreach (string file in files)
            {
                try
                {
                    // Perform whatever action is required in your scenario.
                    System.IO.FileInfo fi = new System.IO.FileInfo(file);
                    Console.WriteLine("{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime);
                }
                catch (System.IO.FileNotFoundException e)
                {
                    // If file was deleted by a separate application
                    //  or thread since the call to TraverseTree()
                    // then just continue.
                    Console.WriteLine(e.Message);
                    continue;
                }
                catch (UnauthorizedAccessException e)
                {                    
                    Console.WriteLine(e.Message);
                    continue;
                }
            }

            // Push the subdirectories onto the stack for traversal.
            // This could also be done before handing the files.
            foreach (string str in subDirs)
                dirs.Push(str);
        }
    }
}

Jquery mouseenter() vs mouseover()

Though they operate the same way, however, the mouseenter event only triggers when the mouse pointer enters the selected element. The mouseover event is triggered if a mouse pointer enters any child elements as well.

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

Django templates: If false?

In old version you can only use the ifequal or ifnotequal

{% ifequal YourVariable ExpectValue %}
    # Do something here.
{% endifequal %}

Example:

{% ifequal userid 1 %}
  Hello No.1
{% endifequal %}

{% ifnotequal username 'django' %}
  You are not django!
{% else %}
  Hi django!
{% endifnotequal %}

As in the if tag, an {% else %} clause is optional.

The arguments can be hard-coded strings, so the following is valid:

{% ifequal user.username "adrian" %} ... {% endifequal %} An alternative to the ifequal tag is to use the if tag and the == operator.

ifnotequal Just like ifequal, except it tests that the two arguments are not equal.

An alternative to the ifnotequal tag is to use the if tag and the != operator.

However, now we can use if/else easily

{% if somevar >= 1 %}
{% endif %}

{% if "bc" in "abcdef" %}
  This appears since "bc" is a substring of "abcdef"
{% endif %}

Complex expressions

All of the above can be combined to form complex expressions. For such expressions, it can be important to know how the operators are grouped when the expression is evaluated - that is, the precedence rules. The precedence of the operators, from lowest to highest, is as follows:

  • or
  • and
  • not
  • in
  • ==, !=, <, >, <=, >=

More detail

https://docs.djangoproject.com/en/dev/ref/templates/builtins/

How do I disable a Pylint warning?

There are several ways to disable warnings & errors from Pylint. Which one to use has to do with how globally or locally you want to apply the disablement -- an important design decision.

Multiple Approaches

  1. In one or more pylintrc files.

This involves more than the ~/.pylintrc file (in your $HOME directory) as described by Chris Morgan. Pylint will search for rc files, with a precedence that values "closer" files more highly:

  • A pylintrc file in the current working directory; or

  • If the current working directory is in a Python module (i.e. it contains an __init__.py file), searching up the hierarchy of Python modules until a pylintrc file is found; or

  • The file named by the environment variable PYLINTRC; or

  • If you have a home directory that isn’t /root:

    • ~/.pylintrc; or

    • ~/.config/pylintrc; or

    • /etc/pylintrc

Note that most of these files are named pylintrc -- only the file in ~ has a leading dot.

To your pylintrc file, add lines to disable specific pylint messages. For example:

[MESSAGES CONTROL]
disable=locally-disabled
  1. Further disables from the pylint command line, as described by Aboo and Cairnarvon. This looks like pylint --disable=bad-builtin. Repeat --disable to suppress additional items.

  2. Further disables from individual Python code lines, as described by Imolit. These look like some statement # pylint: disable=broad-except (extra comment on the end of the original source line) and apply only to the current line. My approach is to always put these on the end of other lines of code so they won't be confused with the block style, see below.

  3. Further disables defined for larger blocks of Python code, up to complete source files.

    • These look like # pragma pylint: disable=bad-whitespace (note the pragma key word).

    • These apply to every line after the pragma. Putting a block of these at the top of a file makes the suppressions apply to the whole file. Putting the same block lower in the file makes them apply only to lines following the block. My approach is to always put these on a line of their own so they won't be confused with the single-line style, see above.

    • When a suppression should only apply within a span of code, use # pragma pylint: enable=bad-whitespace (now using enable not disable) to stop suppressing.

Note that disabling for a single line uses the # pylint syntax while disabling for this line onward uses the # pragma pylint syntax. These are easy to confuse especially when copying & pasting.

Putting It All Together

I usually use a mix of these approaches.

  • I use ~/.pylintrc for absolutely global standards -- very few of these.

  • I use project-level pylintrc at different levels within Python modules when there are project-specific standards. Especially when you're taking in code from another person or team, you may find they use conventions that you don't prefer, but you don't want to rework the code. Keeping the settings at this level helps not spread those practices to other projects.

  • I use the block style pragmas at the top of single source files. I like to turn the pragmas off (stop suppressing messages) in the heat of development even for Pylint standards I don't agree with (like "too few public methods" -- I always get that warning on custom Exception classes) -- but it's helpful to see more / maybe all Pylint messages while you're developing. That way you can find the cases you want to address with single-line pragmas (see below), or just add comments for the next developer to explain why that warning is OK in this case.

  • I leave some of the block-style pragmas enabled even when the code is ready to check in. I try to use few of those, but when it makes sense for the module, it's OK to do as documentation. However I try to leave as few on as possible, preferably none.

  • I use the single-line-comment style to address especially potent errors. For example, if there's a place where it actually makes sense to do except Exception as exc, I put the # pylint: disable=broad-except on that line instead of a more global approach because this is a strange exception and needs to be called out, basically as a form of documentation.


Like everything else in Python, you can act at different levels of indirection. My advice is to think about what belongs at what level so you don't end up with a too-lenient approach to Pylint.

python list by value not by reference

To create a copy of a list do this:

b = a[:]

Subtract two dates in SQL and get days of the result

SELECT DATEDIFF(day,'2014-06-05','2014-08-05') AS DiffDate

diffdate is column name.

result:

DiffDate

23