Programs & Examples On #Unsigned integer

A specific data type that uses all its bits to represent an integer value, consequently only 0 or a positive number.

What is the benefit of zerofill in MySQL?

If you specify ZEROFILL for a numeric column, MySQL automatically adds the UNSIGNED attribute to the column.

Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.

Above description is taken from MYSQL official website.

Convert unsigned int to signed int C

To answer the question posted in the comment above - try something like this:

unsigned short int x = 65529U;
short int y = (short int)x;

printf("%d\n", y);

or

unsigned short int x = 65529U;
short int y = 0;

memcpy(&y, &x, sizeof(short int);
printf("%d\n", y);

What is the difference between signed and unsigned int

As you are probably aware, ints are stored internally in binary. Typically an int contains 32 bits, but in some environments might contain 16 or 64 bits (or even a different number, usually but not necessarily a power of two).

But for this example, let's look at 4-bit integers. Tiny, but useful for illustration purposes.

Since there are four bits in such an integer, it can assume one of 16 values; 16 is two to the fourth power, or 2 times 2 times 2 times 2. What are those values? The answer depends on whether this integer is a signed int or an unsigned int. With an unsigned int, the value is never negative; there is no sign associated with the value. Here are the 16 possible values of a four-bit unsigned int:

bits  value
0000    0
0001    1
0010    2
0011    3
0100    4
0101    5
0110    6
0111    7
1000    8
1001    9
1010   10
1011   11
1100   12
1101   13
1110   14
1111   15

... and Here are the 16 possible values of a four-bit signed int:

bits  value
0000    0
0001    1
0010    2
0011    3
0100    4
0101    5
0110    6
0111    7
1000   -8
1001   -7
1010   -6
1011   -5
1100   -4
1101   -3
1110   -2
1111   -1

As you can see, for signed ints the most significant bit is 1 if and only if the number is negative. That is why, for signed ints, this bit is known as the "sign bit".

Calculating bits required to store decimal number

The short answer is:

int nBits = ceil(log2(N));

That's simply because pow(2, nBits) is slightly bigger than N.

A warning - comparison between signed and unsigned integer expressions

It is usually a good idea to declare variables as unsigned or size_t if they will be compared to sizes, to avoid this issue. Whenever possible, use the exact type you will be comparing against (for example, use std::string::size_type when comparing with a std::string's length).

Compilers give warnings about comparing signed and unsigned types because the ranges of signed and unsigned ints are different, and when they are compared to one another, the results can be surprising. If you have to make such a comparison, you should explicitly convert one of the values to a type compatible with the other, perhaps after checking to ensure that the conversion is valid. For example:

unsigned u = GetSomeUnsignedValue();
int i = GetSomeSignedValue();

if (i >= 0)
{
    // i is nonnegative, so it is safe to cast to unsigned value
    if ((unsigned)i >= u)
        iIsGreaterThanOrEqualToU();
    else
        iIsLessThanU();
}
else
{
    iIsNegative();
}

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

What is a difference between unsigned int and signed int in C?

ISO C states what the differences are.

The int data type is signed and has a minimum range of at least -32767 through 32767 inclusive. The actual values are given in limits.h as INT_MIN and INT_MAX respectively.

An unsigned int has a minimal range of 0 through 65535 inclusive with the actual maximum value being UINT_MAX from that same header file.

Beyond that, the standard does not mandate twos complement notation for encoding the values, that's just one of the possibilities. The three allowed types would have encodings of the following for 5 and -5 (using 16-bit data types):

        two's complement  |  ones' complement   |   sign/magnitude
    +---------------------+---------------------+---------------------+
 5  | 0000 0000 0000 0101 | 0000 0000 0000 0101 | 0000 0000 0000 0101 |
-5  | 1111 1111 1111 1011 | 1111 1111 1111 1010 | 1000 0000 0000 0101 |
    +---------------------+---------------------+---------------------+
  • In two's complement, you get a negative of a number by inverting all bits then adding 1.
  • In ones' complement, you get a negative of a number by inverting all bits.
  • In sign/magnitude, the top bit is the sign so you just invert that to get the negative.

Note that positive values have the same encoding for all representations, only the negative values are different.

Note further that, for unsigned values, you do not need to use one of the bits for a sign. That means you get more range on the positive side (at the cost of no negative encodings, of course).

And no, 5 and -5 cannot have the same encoding regardless of which representation you use. Otherwise, there'd be no way to tell the difference.


As an aside, there are currently moves underway, in both C and C++ standards, to nominate two's complement as the only encoding for negative integers.

Automatically resize images with browser size using CSS

To make the images flexible, simply add max-width:100% and height:auto. Image max-width:100% and height:auto works in IE7, but not in IE8 (yes, another weird IE bug). To fix this, you need to add width:auto\9 for IE8.

source: http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries

for example :

img {
    max-width: 100%;
    height: auto;
    width: auto\9; /* ie8 */
}

and then any images you add simply using the img tag will be flexible

JSFiddle example here. No JavaScript required. Works in latest versions of Chrome, Firefox and IE (which is all I've tested).

Get current location of user in Android without using GPS or internet

Have you take a look Google Maps Geolocation Api? Google Map Geolocation

This is simple RestApi, you just need POST a request, the the service will return a location with accuracy in meters.

Removing elements by class name?

I prefer using forEach over for/while looping. In order to use it's necessary to convert HTMLCollection to Array first:

Array.from(document.getElementsByClassName("post-text"))
    .forEach(element => element.remove());

Pay attention, it's not necessary the most efficient way. Just much more elegant for me.

Display fullscreen mode on Tkinter

This creates a fullscreen window. Pressing Escape resizes the window to '200x200+0+0' by default. If you move or resize the window, Escape toggles between the current geometry and the previous geometry.

import Tkinter as tk

class FullScreenApp(object):
    def __init__(self, master, **kwargs):
        self.master=master
        pad=3
        self._geom='200x200+0+0'
        master.geometry("{0}x{1}+0+0".format(
            master.winfo_screenwidth()-pad, master.winfo_screenheight()-pad))
        master.bind('<Escape>',self.toggle_geom)            
    def toggle_geom(self,event):
        geom=self.master.winfo_geometry()
        print(geom,self._geom)
        self.master.geometry(self._geom)
        self._geom=geom

root=tk.Tk()
app=FullScreenApp(root)
root.mainloop()

NSNotificationCenter addObserver in Swift

Swift 5 & Xcode 10.2:

NotificationCenter.default.addObserver(
            self,
            selector: #selector(batteryLevelDidChangeNotification),
            name: UIDevice.batteryLevelDidChangeNotification,
            object: nil)

Python: finding an element in a list

If you just want to find out if an element is contained in the list or not:

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> 'example' in li
True
>>> 'damn' in li
False

How to manually trigger click event in ReactJS?

Try this and let me know if it does not work on your end:

<input type="checkbox" name='agree' ref={input => this.inputElement = input}/>
<div onClick={() => this.inputElement.click()}>Click</div>

Clicking on the div should simulate a click on the input element

How to repeat a string a variable number of times in C++?

Use one of the forms of string::insert:

std::string str("lolcat");
str.insert(0, 5, '.');

This will insert "....." (five dots) at the start of the string (position 0).

How to get user name using Windows authentication in asp.net?

I think because of the below code you are not getting new credential

string fullName = Request.ServerVariables["LOGON_USER"];

You can try custom login page.

How do I disable a Button in Flutter?

You can also use the AbsorbPointer, and you can use it in the following way:

AbsorbPointer(
      absorbing: true, // by default is true
      child: RaisedButton(
        onPressed: (){
          print('pending to implement onPressed function');
        },
        child: Text("Button Click!!!"),
      ),
    ),

If you want to know more about this widget, you can check the following link Flutter Docs

DROP IF EXISTS VS DROP?

Standard SQL syntax is

DROP TABLE table_name;

IF EXISTS is not standard; different platforms might support it with different syntax, or not support it at all. In PostgreSQL, the syntax is

DROP TABLE IF EXISTS table_name;

The first one will throw an error if the table doesn't exist, or if other database objects depend on it. Most often, the other database objects will be foreign key references, but there may be others, too. (Views, for example.) The second will not throw an error if the table doesn't exist, but it will still throw an error if other database objects depend on it.

To drop a table, and all the other objects that depend on it, use one of these.

DROP TABLE table_name CASCADE;
DROP TABLE IF EXISTS table_name CASCADE;

Use CASCADE with great care.

How to change port for jenkins window service when 8080 is being used

In linux,

sudo vi /etc/sysconfig/jenkins

set following configuration with any available port

JENKINS_PORT="8082"

How to check if internet connection is present in Java?

I usually break it down into three steps.

  1. I first see if I can resolve the domain name to an IP address.
  2. I then try to connect via TCP (port 80 and/or 443) and close gracefully.
  3. Finally, I'll issue an HTTP request and check for a 200 response back.

If it fails at any point, I provide the appropriate error message to the user.

Populate XDocument from String

You can use XDocument.Parse(string) instead of Load(string).

Enable vertical scrolling on textarea

You can try adding:

#aboutDescription
{
    height: 100px;
    max-height: 100px;  
}

Keystore change passwords

[How can I] Change the password, so I can share it with others and let them sign

Using keytool:

keytool -storepasswd -keystore /path/to/keystore
Enter keystore password:  changeit
New keystore password:  new-password
Re-enter new keystore password:  new-password

Why does this AttributeError in python occur?

The default namespace in Python is "__main__". When you use import scipy, Python creates a separate namespace as your module name. The rule in Pyhton is: when you want to call an attribute from another namespaces you have to use the fully qualified attribute name.

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

id selector can be used to more elements. here is the example:

css:

#t_color{
    color: red;
}
#f_style{
    font-family: arial;
    font-size: 20px;
}

html:

<p id="t_color"> test only </p>
<div id="t_color">the box text</div>

I tested on internet explorer (ver. 11.0) and Chrome (ver.47.0). it works on both of them.

The "unique" only means one element can not have more than one id attributes like class selector. Neither

<p id="t_color f_style">...</p>

nor

<p id="t_color" id="f_style">...</p>

How do you test a public/private DSA keypair?

I always compare an MD5 hash of the modulus using these commands:

Certificate: openssl x509 -noout -modulus -in server.crt | openssl md5
Private Key: openssl rsa -noout -modulus -in server.key | openssl md5
CSR: openssl req -noout -modulus -in server.csr | openssl md5

If the hashes match, then those two files go together.

Gradle to execute Java class (without modifying build.gradle)

You can parameterise it and pass gradle clean build -Pprokey=goodbye

task choiceMyMainClass(type: JavaExec) {
     group = "Execution"
    description = "Run Option main class with JavaExecTask"
    classpath = sourceSets.main.runtimeClasspath

    if (project.hasProperty('prokey')){
        if (prokey == 'hello'){
            main = 'com.sam.home.HelloWorld'
        } 
        else if (prokey == 'goodbye'){
            main = 'com.sam.home.GoodBye'
        }
    } else {
            println 'Invalid value is enterrd';

       // println 'Invalid value is enterrd'+ project.prokey;
    }

Round to at most 2 decimal places (only if necessary)

I wrote the following set of functions for myself. Maybe it will help you too.

function float_exponent(number) {
    exponent = 1;
    while (number < 1.0) {
        exponent += 1
        number *= 10
    }
    return exponent;
}
function format_float(number, extra_precision) {
    precision = float_exponent(number) + (extra_precision || 0)
    return number.toFixed(precision).split(/\.?0+$/)[0]
}

Usage:

format_float(1.01); // 1
format_float(1.06); // 1.1
format_float(0.126); // 0.13
format_float(0.000189); // 0.00019

For you case:

format_float(10, 1); // 10
format_float(9.1, 1); // 9.1
format_float(1.77777, 1); // 1.78

Best way to format integer as string with leading zeros?

The standard way is to use format string modifiers. These format string methods are available in most programming languages (via the sprintf function in c for example) and are a handy tool to know about.

To output a string of length 5:

... in Python 3.5 and above:

i = random.randint(0, 99999)
print(f'{i:05d}')

... Python 2.6 and above:

print '{0:05d}'.format(i)

... before Python 2.6:

print "%05d" % i

See: https://docs.python.org/3/library/string.html

Unable to Resolve Module in React Native App

If you recently had a name change in git that only includes changing the case of file. MacOS will ignore the change. So, you will have to go to the file in console and change the name. for example if name change is menu.js -> Menu.js use terminal to do a manual rename after the pull.

mv menu.js Menu.js

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

In the case you are on something else then windows and your boss is forcing you to use azure devops, and you don't want to use SSH, and you want to use to plain old way, do the following.

You have to enable 'Alternate credentials' (I know it's annoying) or you need to create an access token. Creating an access token in this case is more like a temporary random password. If you use the windows tooling it is done for you.

Any way, go to Security in the profile context menu in the right upper corner.

Security settings

Then if your boss/manager/dude that has the admin rights is favoring you the 'Alternate credentials' are enabled. Otherwise accept your fate and generate a 'Personal access token'.

Security settings

What is the use of the square brackets [] in sql statements?

In addition Some Sharepoint databases contain hyphens in their names. Using square brackets in SQL Statements allow the names to be parsed correctly.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

NullPointerExceptions are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.

Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerExceptions is accidentally declaring an object with local scope when there is an instance variable with the same name.

In your case, the exception occurred in your constructor for Workshop on line 75. <init> means the constructor for a class. If you look on that line in your code, you'll see the line

denimjeansButton.addItemListener(this);

There are fairly clearly two objects on this line: denimjeansButton and this. this is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this. denimjeansButton is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton or instantiate it.

Add text at the end of each line

You could try using something like:

sed -n 's/$/:80/' ips.txt > new-ips.txt

Provided that your file format is just as you have described in your question.

The s/// substitution command matches (finds) the end of each line in your file (using the $ character) and then appends (replaces) the :80 to the end of each line. The ips.txt file is your input file... and new-ips.txt is your newly-created file (the final result of your changes.)


Also, if you have a list of IP numbers that happen to have port numbers attached already, (as noted by Vlad and as given by aragaer,) you could try using something like:

sed '/:[0-9]*$/ ! s/$/:80/' ips.txt > new-ips.txt

So, for example, if your input file looked something like this (note the :80):

127.0.0.1
128.0.0.0:80
121.121.33.111

The final result would look something like this:

127.0.0.1:80
128.0.0.0:80
121.121.33.111:80

CSS vertical-align: text-bottom;

Modern solution

Flexbox was created for exactly these kind of problems:

_x000D_
_x000D_
#container {_x000D_
    height: 150px;/*Only for the demo.*/_x000D_
    background-color:green;/*Only for the demo.*/_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
    align-items: flex-end;_x000D_
}
_x000D_
<div id="container">_x000D_
    <span>Text align to center bottom.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Old school solution

If you don't want to mess with table displays, then you can create a <div> inside a relatively positioned parent container, place it to the bottom with absolute positioning, then make it 100% wide, so you can text-align it to the center:

_x000D_
_x000D_
#container {_x000D_
    height: 150px;/*Only for the demo.*/_x000D_
    background-color:green;/*Only for the demo.*/_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
#text {_x000D_
    position: absolute;_x000D_
    bottom: 0;_x000D_
    width: 100%;_x000D_
    text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
    <span id="text">Text align to center bottom.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

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")

How to give color to each class in scatter plot in R?

Here is an example that I built based on this page.

library(e1071); library(ggplot2)

mysvm      <- svm(Species ~ ., iris)
Predicted  <- predict(mysvm, iris)

mydf = cbind(iris, Predicted)
qplot(Petal.Length, Petal.Width, colour = Species, shape = Predicted, 
   data = iris)

This gives you the output. You can easily spot the misclassified species from this figure.

enter image description here

Server.MapPath - Physical path given, virtual path expected

if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...

Trigger event when user scroll to specific element - with jQuery

I think your best bet would be to leverage an existing library that does that very thing:

http://imakewebthings.com/waypoints/

You can add listeners to your elements that will fire off when your element hits the top of the viewport:

$('#scroll-to').waypoint(function() {
 alert('you have scrolled to the h1!');
});

For an amazing demo of it in use:

http://tympanus.net/codrops/2013/07/16/on-scroll-header-effects/

Get the size of the screen, current web page and browser window

To check height and width of your current loaded page of any website using "console" or after clicking "Inspect".

step 1: Click the right button of mouse and click on 'Inspect' and then click 'console'

step 2: Make sure that your browser screen should be not in 'maximize' mode. If the browser screen is in 'maximize' mode, you need to first click the maximize button (present either at right or left top corner) and un-maximize it.

step 3: Now, write the following after the greater than sign ('>') i.e.

       > window.innerWidth
            output : your present window width in px (say 749)

       > window.innerHeight
            output : your present window height in px (say 359)

java.net.UnknownHostException: Invalid hostname for server: local

What the exception is really saying is that there is no known server with the name "local". My guess is that you're trying to connect to your local computer. Try with the hostname "localhost" instead, or perhaps 127.0.0.1 or ::1 (the last one is IPv6).

From the javadocs:

Thrown to indicate that the IP address of a host could not be determined.

127.0.0.1or ::1 or "localhost" should always be the loopback interface, so if that doesn't work I'd be really surprised.

If there really is a server called "local" on your network - examine your DNS settings or add it to your hosts file.

Alternate background colors for list items

You can achieve this by adding alternating style classes to each list item

<ul>
    <li class="odd"><a href="link">Link 1</a></li>
    <li><a href="link">Link 2</a></li>
    <li class="odd"><a href="link">Link 2</a></li>
    <li><a href="link">Link 2</a></li>
</ul>

And then styling it like

li { backgorund:white; }
li.odd { background:silver; }

You can further automate this process with javascript (jQuery example below)

$(document).ready(function() {
  $('table tbody tr:odd').addClass('odd');
});

Dismissing a Presented View Controller

Updated for Swift 3

I came here just wanting to dismiss the current (presented) View Controller. I'm making this answer for anyone coming here with the same purpose.

Navigation Controller

If you are using a navigation controller, then it is quite easy.

Go back to the previous view controller:

// Swift
self.navigationController?.popViewController(animated: true)

// Objective-C
[self.navigationController popViewControllerAnimated:YES];

Go back to the root view controller:

// Swift
self.navigationController?.popToRootViewController(animated: true)

// Objective-C
[self.navigationController popToRootViewControllerAnimated:YES];

(Thanks to this answer for the Objective-C.)

Modal View Controller

When a View Controller is presented modally, you can dismiss it (from the second view controller) by calling

// Swift
self.dismiss(animated: true, completion: nil)

// Objective-C
[self dismissViewControllerAnimated:YES completion:nil];

The documentation says,

The presenting view controller is responsible for dismissing the view controller it presented. If you call this method on the presented view controller itself, UIKit asks the presenting view controller to handle the dismissal.

So it works for the presented view controller to call it on itself. Here is a full example.

Delegates

The OP's question was about the complexity of using delegates to dismiss a view.

To this point I have not needed to use delegates since I usually have a navigation controller or modal view controllers, but if I do need to use the delegate pattern in the future, I will add an update.

How to get a enum value from string in C#?

var value = (uint) Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE");  

Programmatically stop execution of python script?

sys.exit() will do exactly what you want.

import sys
sys.exit("Error message")

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]

It's a warning, not an error. It occurs because fsevents is an optional dependency, used only when project is run on macOS environment (the package provides 'Native Access to Mac OS-X FSEvents').

And since you're running your project on Windows, fsevents is skipped as irrelevant.

There is a PR to fix this behaviour here: https://github.com/npm/cli/pull/169

Regular expression search replace in Sublime Text 2

Important: Use the ( ) parentheses in your search string

While the previous answer is correct there is an important thing to emphasize! All the matched segments in your search string that you want to use in your replacement string must be enclosed by ( ) parentheses, otherwise these matched segments won't be accessible to defined variables such as $1, $2 or \1, \2 etc.

For example we want to replace 'em' with 'px' but preserve the digit values:

    margin: 10em;  /* Expected: margin: 10px */
    margin: 2em;   /* Expected: margin: 2px */
  • Replacement string: margin: $1px or margin: \1px
  • Search string (CORRECT): margin: ([0-9]*)em // with parentheses
  • Search string (INCORRECT): margin: [0-9]*em

CORRECT CASE EXAMPLE: Using margin: ([0-9]*)em search string (with parentheses). Enclose the desired matched segment (e.g. $1 or \1) by ( ) parentheses as following:

  • Find: margin: ([0-9]*)em (with parentheses)
  • Replace to: margin: $1px or margin: \1px
  • Result:
    margin: 10px;
    margin: 2px;

INCORRECT CASE EXAMPLE: Using margin: [0-9]*em search string (without parentheses). The following regex pattern will match the desired lines but matched segments will not be available in replaced string as variables such as $1 or \1:

  • Find: margin: [0-9]*em (without parentheses)
  • Replace to: margin: $1px or margin: \1px
  • Result:
    margin: px; /* `$1` is undefined */
    margin: px; /* `$1` is undefined */

How can I start an interactive console for Perl?

You can use the perl debugger on a trivial program, like so:

perl -de1

Alternatively there's Alexis Sukrieh's Perl Console application, but I haven't used it.

Find an object in array?

For example, if we had an array of numbers:

let numbers = [2, 4, 6, 8, 9, 10]

We could find the first odd number like this:

let firstOdd = numbers.index { $0 % 2 == 1 }

That will send back 4 as an optional integer, because the first odd number (9) is at index four.

C# '@' before a String

Prefixing the string with an @ indicates that it should be treated as a literal, i.e. no escaping.

For example if your string contains a path you would typically do this:

string path = "c:\\mypath\\to\\myfile.txt";

The @ allows you to do this:

string path = @"c:\mypath\to\myfile.txt";

Notice the lack of double slashes (escaping)

Getting current directory in .NET web application

The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.

You want HttpRuntime.AppDomainAppPath.

If you're in an HTTP request, you can also call Server.MapPath("~/Whatever").

SQL-Server: The backup set holds a backup of a database other than the existing

This helped me to import the back-up file from the system drive

  1. Create a database with the same name(preferably) as your .bak file database name
  2. Right click the database > Tasks > Restore > Database
  3. Under "Source for restore" select "From Device"
  4. Select the .bak file selecting the path from the system
  5. Select the check box for the database in the list box below
  6. Under "Select a Page" on the right Select "Options"
  7. Select the checkbox labeled "Preserve the replication settings(WITH KEEP_REPLICATION)
  8. Select the checkbox for Overwrite the existing database(WITH REPLACE) Now Go back to the General page and click OK to restore the database...

Show/Hide Multiple Divs with Jquery

Assign each div a class. Then you can perform actions on all of them:

$(".divClass").hide();

So each button can do:

$(".divClass").hide()
$("#specificDiv").show();

You can make this more generic, and use the obvious convention - the button and the div with the same number in the id are related. So:

$(".button").click(function() {
  var divId = "#div" + $(this).attr("id").replace("showdiv", "");
  $(".divClass").hide(); 
  $(divId).show();
}

How to generate javadoc comments in Android Studio

Here is an example of a JavaDoc comment from Oracle:

/**
 * Returns an Image object that can then be painted on the screen. 
 * The url argument must specify an absolute {@link URL}. The name
 * argument is a specifier that is relative to the url argument. 
 * <p>
 * This method always returns immediately, whether or not the 
 * image exists. When this applet attempts to draw the image on
 * the screen, the data will be loaded. The graphics primitives 
 * that draw the image will incrementally paint on the screen. 
 *
 * @param  url  an absolute URL giving the base location of the image
 * @param  name the location of the image, relative to the url argument
 * @return      the image at the specified URL
 * @see         Image
 */
 public Image getImage(URL url, String name) {
        try {
            return getImage(new URL(url, name));
        } catch (MalformedURLException e) {
            return null;
        }
 }

The basic format can be auto generated in either of the following ways:

  • Position the cursor above the method and type /** + Enter
  • Position the cursor on the method name and press Alt + Enter > click Add JavaDoc enter image description here

How do I style (css) radio buttons and labels?

For any CSS3-enabled browser you can use an adjacent sibling selector for styling your labels

input:checked + label {
    color: white;
}  

MDN's browser compatibility table says essentially all of the current, popular browsers (Chrome, IE, Firefox, Safari), on both desktop and mobile, are compatible.

Difference between Destroy and Delete

Basically "delete" sends a query directly to the database to delete the record. In that case Rails doesn't know what attributes are in the record it is deleting nor if there are any callbacks (such as before_destroy).

The "destroy" method takes the passed id, fetches the model from the database using the "find" method, then calls destroy on that. This means the callbacks are triggered.

You would want to use "delete" if you don't want the callbacks to be triggered or you want better performance. Otherwise (and most of the time) you will want to use "destroy".

What is the maximum possible length of a query string?

RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). RFC 3986 (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).

While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at Internet Archive Of Boutell.com:

  • Microsoft Internet Explorer (Browser)
    Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.

  • Microsoft Edge (Browser)
    The limit appears to be around 81578 characters. See URL Length limitation of Microsoft Edge

  • Chrome
    It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.

  • Firefox (Browser)
    After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.

  • Safari (Browser)
    At least 80,000 characters will work. Testing was not tried beyond that.

  • Opera (Browser)
    At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable, copyable and pasteable URL in the location bar even at 190,000 characters.

  • Apache (Server)
    Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.

  • Microsoft Internet Information Server (Server)
    The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.

  • Perl HTTP::Daemon (Server)
    Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.

How to take MySQL database backup using MySQL Workbench?

  1. On ‘HOME’ page -- > select 'Manage Import / Export' under 'Server Administration'

  2. A box comes up... choose which server holds the data you want to back up.

  3. On the 'Export to Disk' tab, then select which databases you want to export.

  4. If you want all the tables, select option ‘Export to self-contained file’, otherwise choose the other option for a selective restore

  5. If you need advanced options, see other post, otherwise then click ‘Start Export’

htaccess remove index.php from url

Assuming the existent url is

http://example.com/index.php/foo/bar

and we want to convert it into

 http://example.com/foo/bar

You can use the following rule :

RewriteEngine on
#1) redirect the client from "/index.php/foo/bar" to "/foo/bar"
RewriteCond %{THE_REQUEST} /index\.php/(.+)\sHTTP [NC]
RewriteRule ^ /%1 [NE,L,R]
#2)internally map "/foo/bar" to "/index.php/foo/bar"
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /index.php/$1 [L]

In the spep #1 we first match against the request string and capture everything after the /index.php/ and the captured value is saved in %1 var. We then send the browser to a new url. The #2 processes the request internally. When the browser arrives at /foo/bar , #2rule rewrites the new url to the orignal location.

How to use querySelectorAll only for elements that have a specific attribute set?

Extra Tips:

Multiple "nots", input that is NOT hidden and NOT disabled:

:not([type="hidden"]):not([disabled])

Also did you know you can do this:

node.parentNode.querySelectorAll('div');

This is equivelent to jQuery's:

$(node).parent().find('div');

Which will effectively find all divs in "node" and below recursively, HOT DAMN!

How to perform a for loop on each character in a string in Bash?

I believe there is still no ideal solution that would correctly preserve all whitespace characters and is fast enough, so I'll post my answer. Using ${foo:$i:1} works, but is very slow, which is especially noticeable with large strings, as I will show below.

My idea is an expansion of a method proposed by Six, which involves read -n1, with some changes to keep all characters and work correctly for any string:

while IFS='' read -r -d '' -n 1 char; do
        # do something with $char
done < <(printf %s "$string")

How it works:

  • IFS='' - Redefining internal field separator to empty string prevents stripping of spaces and tabs. Doing it on a same line as read means that it will not affect other shell commands.
  • -r - Means "raw", which prevents read from treating \ at the end of the line as a special line concatenation character.
  • -d '' - Passing empty string as a delimiter prevents read from stripping newline characters. Actually means that null byte is used as a delimiter. -d '' is equal to -d $'\0'.
  • -n 1 - Means that one character at a time will be read.
  • printf %s "$string" - Using printf instead of echo -n is safer, because echo treats -n and -e as options. If you pass "-e" as a string, echo will not print anything.
  • < <(...) - Passing string to the loop using process substitution. If you use here-strings instead (done <<< "$string"), an extra newline character is appended at the end. Also, passing string through a pipe (printf %s "$string" | while ...) would make the loop run in a subshell, which means all variable operations are local within the loop.

Now, let's test the performance with a huge string. I used the following file as a source:
https://www.kernel.org/doc/Documentation/kbuild/makefiles.txt
The following script was called through time command:

#!/bin/bash

# Saving contents of the file into a variable named `string'.
# This is for test purposes only. In real code, you should use
# `done < "filename"' construct if you wish to read from a file.
# Using `string="$(cat makefiles.txt)"' would strip trailing newlines.
IFS='' read -r -d '' string < makefiles.txt

while IFS='' read -r -d '' -n 1 char; do
        # remake the string by adding one character at a time
        new_string+="$char"
done < <(printf %s "$string")

# confirm that new string is identical to the original
diff -u makefiles.txt <(printf %s "$new_string")

And the result is:

$ time ./test.sh

real    0m1.161s
user    0m1.036s
sys     0m0.116s

As we can see, it is quite fast.
Next, I replaced the loop with one that uses parameter expansion:

for (( i=0 ; i<${#string}; i++ )); do
    new_string+="${string:$i:1}"
done

The output shows exactly how bad the performance loss is:

$ time ./test.sh

real    2m38.540s
user    2m34.916s
sys     0m3.576s

The exact numbers may very on different systems, but the overall picture should be similar.

How to check if a map contains a key in Go?

better way here

if _, ok := dict["foo"]; ok {
    //do something here
}

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

For me, running the ad-hoc network on Windows 8.1, it was two things:

  • I had to set a static IP on my Android (under Advanced Options under where you type the Wifi password)
  • I had to use a password 8 characters long

Any IP will allow you to connect, but if you want internet access the static IP should match the subnet from the shared internet connection.

I'm not sure why I couldn't get a longer password to work, but it's worth a try. Maybe a more knowledgeable person could fill us in.

How to get time (hour, minute, second) in Swift 3 using NSDate?

In Swift 3.0 Apple removed 'NS' prefix and made everything simple. Below is the way to get hour, minute and second from 'Date' class (NSDate alternate)

let date = Date()
let calendar = Calendar.current

let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("hours = \(hour):\(minutes):\(seconds)")

Like these you can get era, year, month, date etc. by passing corresponding.

How to check if a stored procedure exists before creating it

I wonder! Why i don't write the whole query like

GO
create procedure [dbo].[spAddNewClass] @ClassName varchar(20),@ClassFee int
as
begin
insert into tblClass values (@ClassName,@ClassFee)
end

GO
create procedure [dbo].[spAddNewSection] @SectionName varchar(20),@ClassID       int
as
begin
insert into tblSection values(@SectionName,@ClassID)
end

Go
create procedure test
as
begin 
select * from tblstudent
end

i already know that first two procedures are already exist sql will run the query will give the error of first two procedures but still it will create the last procedure SQl is itself taking care of what is already exist this is what i always do to all my clients!

Is there a WebSocket client implemented for Python?

Autobahn has a good websocket client implementation for Python as well as some good examples. I tested the following with a Tornado WebSocket server and it worked.

from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS


class EchoClientProtocol(WebSocketClientProtocol):

   def sendHello(self):
      self.sendMessage("Hello, world!")

   def onOpen(self):
      self.sendHello()

   def onMessage(self, msg, binary):
      print "Got echo: " + msg
      reactor.callLater(1, self.sendHello)


if __name__ == '__main__':

   factory = WebSocketClientFactory("ws://localhost:9000")
   factory.protocol = EchoClientProtocol
   connectWS(factory)
   reactor.run()

How to pattern match using regular expression in Scala?

To expand a little on Andrew's answer: The fact that regular expressions define extractors can be used to decompose the substrings matched by the regex very nicely using Scala's pattern matching, e.g.:

val Process = """([a-cA-C])([^\s]+)""".r // define first, rest is non-space
for (p <- Process findAllIn "aha bah Cah dah") p match {
  case Process("b", _) => println("first: 'a', some rest")
  case Process(_, rest) => println("some first, rest: " + rest)
  // etc.
}

Labeling file upload button

Take a step back! Firstly, you're assuming the user is using a foreign locale on their device, which is not a sound assumption for justifying taking over the button text of the file picker, and making it say what you want it to.

It is reasonable that you want to control every item of language visible on your page. The content of the File Upload control is not part of the HTML though. There is more content behind this control, for example, in WebKit, it also says "No file chosen" next to the button.

There are very hacky workarounds that attempt this (e.g. like those mentioned in @ChristopheD's answer), but none of them truly succeed:

  • To a screen reader, the file control will still say "Browse..." or "Choose File", and a custom file upload will not be announced as a file upload control, but just a button or a text input.
  • Many of them fail to display the chosen file, or to show that the user has no longer chosen a file
  • Many of them look nothing like the native control, so might look strange on non-standard devices.
  • Keyboard support is typically poor.
  • An author-created UI component can never be as fully functional as its native equivalent (and the closer you get it to behave to suppose IE10 on Windows 7, the more it will deviate from other Browser and Operating System combinations).
  • Modern browsers support drag & drop into the native file upload control.
  • Some techniques may trigger heuristics in security software as a potential ‘click-jacking’ attempt to trick the user into uploading file.

Deviating from the native controls is always a risky thing, there is a whole host of different devices your users could be using, and whatever workaround you choose, you will not have tested it in every one of those devices.

However, there is an even bigger reason why all attempts fail from a User Experience perspective: there is even more non-localized content behind this control, the file selection dialog itself. Once the user is subject to traversing their file system or what not to select a file to upload, they will be subjected to the host Operating System locale.

Are you sure you're doing your user any justice by deviating from the native control, just to localize the text, when as soon as they click it, they're just going to get the Operating System locale anyway?

The best you can do for your users is to ensure you have adequate localised guidance surrounding your file input control. (e.g. Form field label, hint text, tooltip text).

Sorry. :-(

--

This answer is for those looking for any justification not to localise the file upload control.

How to detect shake event with android?

There are a lot of solutions to this question already, but I wanted to post one that:

  • Doesn't use a library depricated in API 3
  • Calculates the magnitude of the acceleration correctly
  • Correctly applies a timeout between shake events

Here is such a solution:

// variables for shake detection
private static final float SHAKE_THRESHOLD = 3.25f; // m/S**2
private static final int MIN_TIME_BETWEEN_SHAKES_MILLISECS = 1000;
private long mLastShakeTime;
private SensorManager mSensorMgr;

To initialize the timer:

// Get a sensor manager to listen for shakes
mSensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);

// Listen for shakes
Sensor accelerometer = mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (accelerometer != null) {
    mSensorMgr.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}

SensorEventListener methods to override:

@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        long curTime = System.currentTimeMillis();
        if ((curTime - mLastShakeTime) > MIN_TIME_BETWEEN_SHAKES_MILLISECS) {

            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];

            double acceleration = Math.sqrt(Math.pow(x, 2) +
                    Math.pow(y, 2) +
                    Math.pow(z, 2)) - SensorManager.GRAVITY_EARTH;
            Log.d(APP_NAME, "Acceleration is " + acceleration + "m/s^2");

            if (acceleration > SHAKE_THRESHOLD) {
                mLastShakeTime = curTime;
                Log.d(APP_NAME, "Shake, Rattle, and Roll");
            }
        }
    }
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // Ignore
}

When you are all done

// Stop listening for shakes
mSensorMgr.unregisterListener(this);

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

Try changing the second parameter in the SaveAs call to Excel.XlFileFormat.xlWorkbookDefault.

When I did that, I generated an xlsx file that I was able to successfully open. (Before making the change, I could produce an xlsx file, but I was unable to open it.)

Also, I'm not sure if it matters or not, but I'm using the Excel 12.0 object library.

How to use document.getElementByName and getElementByTag?

It's getElementsByName() and getElementsByTagName() - note the "s" in "Elements", indicating that both functions return a list of elements, i.e., a NodeList, which you will access like an array. Note that the second function ends with "TagName" not "Tag".

Even if the function only returns one element it will still be in a NodeList of length one. So:

var els = document.getElementsByName('frmMain');
// els.length will be the number of elements returned
// els[0] will be the first element returned
// els[1] the second, etc.

Assuming your form is the first (or only) form on the page you can do this:

document.getElementsByName('frmMain')[0].elements
document.getElementsByTagName('table')[0].elements

How do I make a branch point at a specific commit?

You can make master point at 1258f0d0aae this way:

git checkout master
git reset --hard 1258f0d0aae

But you have to be careful about doing this. It may well rewrite the history of that branch. That would create problems if you have published it and other people are working on the branch.

Also, the git reset --hard command will throw away any uncommitted changes (i.e. those just in your working tree or the index).

You can also force an update to a branch with:

git branch -f master 1258f0d0aae

... but git won't let you do that if you're on master at the time.

Simple WPF RadioButton Binding?

I came up with a simple solution.

I have a model.cs class with:

private int _isSuccess;
public int IsSuccess { get { return _isSuccess; } set { _isSuccess = value; } }

I have Window1.xaml.cs file with DataContext set to model.cs. The xaml contains the radiobuttons:

<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=1}" Content="one" />
<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=2}" Content="two" />
<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=3}" Content="three" />

Here is my converter:

public class RadioBoolToIntConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int integer = (int)value;
        if (integer==int.Parse(parameter.ToString()))
            return true;
        else
            return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return parameter;
    }
}

And of course, in Window1's resources:

<Window.Resources>
    <local:RadioBoolToIntConverter x:Key="radioBoolToIntConverter" />
</Window.Resources>

import httplib ImportError: No module named httplib

You are running Python 2 code on Python 3. In Python 3, the module has been renamed to http.client.

You could try to run the 2to3 tool on your code, and try to have it translated automatically. References to httplib will automatically be rewritten to use http.client instead.

How to get CSS to select ID that begins with a string (not in Javascript)?

I'd do it like this:

[id^="product"] {
  ...
}

Ideally, use a class. This is what classes are for:

<div id="product176" class="product"></div>
<div id="product177" class="product"></div>
<div id="product178" class="product"></div>

And now the selector becomes:

.product {
  ...
}

How to detect scroll direction

I managed to figure it out in the end, so if anyone is looking for the answer:

 //Firefox
 $('#elem').bind('DOMMouseScroll', function(e){
     if(e.originalEvent.detail > 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

 //IE, Opera, Safari
 $('#elem').bind('mousewheel', function(e){
     if(e.originalEvent.wheelDelta < 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

make image( not background img) in div repeat?

You have use to repeat-y as style="background-repeat:repeat-y;width: 200px;" instead of style="repeat-y".

Try this inside the image tag or you can use the below css for the div

.div_backgrndimg
{
    background-repeat: repeat-y;
    background-image: url("/image/layout/lotus-dreapta.png");
    width:200px;
}

How to use "like" and "not like" in SQL MSAccess for the same field?

Simply restate the target field & condition;

where (field like "*AA*" and field not like "*BB*")

/lib/ld-linux.so.2: bad ELF interpreter: No such file or directory

I had the same issue, the following commands can resolve:

sudo yum install  glibc-common glibc  (mutual dependency)
sudo yum install  glibc.i686  (the missing version)

How to get length of a string using strlen function

Use std::string::size or std::string::length (both are the same).

As you insist to use strlen, you can:

int size = strlen( str.c_str() );

note the usage of std::string::c_str, which returns const char*.

BUT strlen counts untill it hit \0 char and std::string can store such chars. In other words, strlen could sometimes lie for the size.

How do I use this JavaScript variable in HTML?

You can create a <p> element:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <script>_x000D_
  var name = prompt("What's your name?");_x000D_
  var lengthOfName = name.length_x000D_
  p = document.createElement("p");_x000D_
  p.innerHTML = "Your name is "+lengthOfName+" characters long.";_x000D_
  document.body.appendChild(p);_x000D_
  </script>_x000D_
  <body>_x000D_
  </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

Retrieve list of tasks in a queue in Celery

To retrieve tasks from backend, use this

from amqplib import client_0_8 as amqp
conn = amqp.Connection(host="localhost:5672 ", userid="guest",
                       password="guest", virtual_host="/", insist=False)
chan = conn.channel()
name, jobs, consumers = chan.queue_declare(queue="queue_name", passive=True)

Add a new column to existing table in a migration

If you're using Laravel 5, the command would be;

php artisan make:migration add_paid_to_users

All of the commands for making things (controllers, models, migrations etc) have been moved under the make: command.

php artisan migrate is still the same though.

How to read a local text file?

You need to check for status 0 (as when loading files locally with XMLHttpRequest, you don't get a status returned because it's not from a Webserver)

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

And specify file:// in your filename:

readTextFile("file:///C:/your/path/to/file.txt");

Why can't non-default arguments follow default arguments?

Required arguments (the ones without defaults), must be at the start to allow client code to only supply two. If the optional arguments were at the start, it would be confusing:

fun1("who is who", 3, "jack")

What would that do in your first example? In the last, x is "who is who", y is 3 and a = "jack".

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

try these

sudo chown -R $(whoami) ~/.npm

sudo chown -R $(whoami) /usr/local/lib

sudo chown -R $(whoami) /usr/local/bin

Then try your command again without sudo. e.g.

npm install -g npm@latest

Check this link for more details

Constructors in Go

If you want to emulate ___.new() syntax you can do something along the lines of:

type Thing struct {
    Name string
    Num int
}
type Constructor_Thing struct {}
func (c CThing) new(<<CONSTRUCTOR ARGS>>) Thing {
  var thing Thing
  //initiate thing from constructor args
  return thing
}
var cThing CThing

func main(){
  var myThing Thing
  myThing = cThing.new(<<CONSTRUCTOR ARGS>>)
  //...
}

Granted, it is a shame that Thing.new() cannot be implemented without CThing.new() also being implemented (iirc) which is a bit of a shame...

Getting Access Denied when calling the PutObject operation with bucket-level permission

I was having the same error message for a mistake I made: Make sure you use a correct s3 uri such as: s3://my-bucket-name/

(If my-bucket-name is at the root of your aws s3 obviously)

I insist on that because when copy pasting the s3 bucket from your browser you get something like https://s3.console.aws.amazon.com/s3/buckets/my-bucket-name/?region=my-aws-regiontab=overview

Thus I made the mistake to use s3://buckets/my-bucket-name which raises:

An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

Run cron job only if it isn't already running

You can also do it as a one-liner directly in your crontab:

* * * * * [ `ps -ef|grep -v grep|grep <command>` -eq 0 ] && <command>

How to comment multiple lines in Visual Studio Code?

Shift+Alt+A

Here you can find all the keyboard shortcuts.

All VSCode Shortcuts

PS: I prefer Ctrl+Shift+/ for toggling block comments because Ctrl+/ is shortcut for toggling line comments so it's naturally easier to remember. To do so, just click on the settings icon in the bottom left of the screen and click 'Keyboard Shortcuts' and find "toggle block...". Then click and enter your desired combination.

How do I remove objects from an array in Java?

Use:

list.removeAll(...);
//post what char you need in the ... section

How to list all installed packages and their versions in Python?

If this is needed to run from within python you can just invoke subprocess

from subprocess import PIPE, Popen

pip_process = Popen(["pip freeze"], stdout=PIPE,
                   stderr=PIPE, shell=True)
stdout, stderr = pip_process.communicate()
print(stdout.decode("utf-8"))

The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

I get this error when my project .net framework version does not match the framework version of the DLL I am linking to. In my case, I was getting:

"The type or namespace name 'UserVoice' could not be found (are you missing a using directive or an assembly reference?).

UserVoice was .Net 4.0, and my project properties were set to ".Net 4.0 Client Profile". Changing to .Net 4.0 on the project cleared the error. I hope this helps someone.

Change drive in git bash for windows

Just consider your drive as a folder so do cd e:

Get yesterday's date in bash on Linux, DST-safe

If you are certain that the script runs in the first hours of the day, you can simply do

  date -d "12 hours ago" '+%Y-%m-%d'

BTW, if the script runs daily at 00:35 (via crontab?) you should ask yourself what will happen if a DST change falls in that hour; the script could not run, or run twice in some cases. Modern implementations of cron are quite clever in this regard, though.

Rename Pandas DataFrame Index

The rename method takes a dictionary for the index which applies to index values.
You want to rename to index level's name:

df.index.names = ['Date']

A good way to think about this is that columns and index are the same type of object (Index or MultiIndex), and you can interchange the two via transpose.

This is a little bit confusing since the index names have a similar meaning to columns, so here are some more examples:

In [1]: df = pd.DataFrame([[1, 2, 3], [4, 5 ,6]], columns=list('ABC'))

In [2]: df
Out[2]: 
   A  B  C
0  1  2  3
1  4  5  6

In [3]: df1 = df.set_index('A')

In [4]: df1
Out[4]: 
   B  C
A      
1  2  3
4  5  6

You can see the rename on the index, which can change the value 1:

In [5]: df1.rename(index={1: 'a'})
Out[5]: 
   B  C
A      
a  2  3
4  5  6

In [6]: df1.rename(columns={'B': 'BB'})
Out[6]: 
   BB  C
A       
1   2  3
4   5  6

Whilst renaming the level names:

In [7]: df1.index.names = ['index']
        df1.columns.names = ['column']

Note: this attribute is just a list, and you could do the renaming as a list comprehension/map.

In [8]: df1
Out[8]: 
column  B  C
index       
1       2  3
4       5  6

How can I use pickle to save a dict?

import pickle

your_data = {'foo': 'bar'}

# Store data (serialize)
with open('filename.pickle', 'wb') as handle:
    pickle.dump(your_data, handle, protocol=pickle.HIGHEST_PROTOCOL)

# Load data (deserialize)
with open('filename.pickle', 'rb') as handle:
    unserialized_data = pickle.load(handle)

print(your_data == unserialized_data)

The advantage of HIGHEST_PROTOCOL is that files get smaller. This makes unpickling sometimes much faster.

Important notice: The maximum file size of pickle is about 2GB.

Alternative way

import mpu
your_data = {'foo': 'bar'}
mpu.io.write('filename.pickle', data)
unserialized_data = mpu.io.read('filename.pickle')

Alternative Formats

For your application, the following might be important:

  • Support by other programming languages
  • Reading / writing performance
  • Compactness (file size)

See also: Comparison of data serialization formats

In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python

How can I color a UIImage in Swift?

There's a built in method to obtain a UIImage that is automatically rendered in template mode. This uses a view's tintColor to color the image:

let templateImage = originalImage.imageWithRenderingMode(UIImageRenderingModeAlwaysTemplate)
myImageView.image = templateImage
myImageView.tintColor = UIColor.orangeColor()

How do I parse JSON into an int?

Non of them worked for me. I did this and it worked:

To encode as a json:

JSONObject obj = new JSONObject();
obj.put("productId", 100);

To decode:

long temp = (Long) obj.get("productId");

Xcode 10: A valid provisioning profile for this executable was not found

Finally, I figured out what's going on... almost take me 2 hours

My case is, my phone's date is not correct. I forgot I changed my phone's date. I guess that makes all of my provisioning profiles expired...

So if you've tried all of those answers but nothing works. Go to the SETTINGS, check your phone's date.

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used


This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.




import numpy as np
import cv2
   
      
# Read the image
image = cv2.imread('digits.png')
  
# gray scale conversion
gray_img = cv2.cvtColor(image,
                        cv2.COLOR_BGR2GRAY)
  
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
  
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
   
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
  
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
  
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
   
# Initiate kNN classifier
knn = cv2.ml.KNearest_create()
  
# perform training of data
knn.train(train_data,
          cv2.ml.ROW_SAMPLE, 
          train_labels)
   
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
   
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
   
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
   
# Display accuracy.
print(accuracy)


Output

91.64


Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked, below is the result I got:

enter image description here


Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

Laravel Eloquent Join vs Inner Join?

Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.

You could build it like this:

<?php

Schema::create('feeds', function($table) {
    $table->increments('id');
    $table->timestamps();
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->morphs('target'); 
});

Build the feed model like so:

<?php

class Feed extends Eloquent
{
    protected $fillable = ['user_id', 'target_type', 'target_id'];

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function target()
    {
        return $this->morphTo();
    }
}

Then keep it up to date with something like:

<?php

Vote::created(function(Vote $vote) {
    $target_type = 'Vote';
    $target_id   = $vote->id;
    $user_id     = $vote->user_id;

    Feed::create(compact('target_type', 'target_id', 'user_id'));
});

You could make the above much more generic/robust—this is just for demonstration purposes.

At this point, your feed items are really easy to retrieve all at once:

<?php

Feed::whereIn('user_id', $my_friend_ids)
    ->with('user', 'target')
    ->orderBy('created_at', 'desc')
    ->get();

How do you uninstall a python package that was installed using distutils?

for Python in Windows:

python -m pip uninstall "package_keyword"
uninstall **** (y/n)?

Add (insert) a column between two columns in a data.frame

Here is a an example of how to move a column from last to first position. It combines [ with ncol. I thought it would be useful to have a very short answer here for the busy reader:

d = mtcars
d[, c(ncol(d), 1:(ncol(d)-1))] 

Regex match digits, comma and semicolon?

word.matches("^[0-9,;]+$"); you were almost there

What is the best way to paginate results in SQL Server

The best way for paging in sql server 2012 is by using offset and fetch next in a stored procedure. OFFSET Keyword - If we use offset with the order by clause then the query will skip the number of records we specified in OFFSET n Rows.

FETCH NEXT Keywords - When we use Fetch Next with an order by clause only it will returns the no of rows you want to display in paging, without Offset then SQL will generate an error. here is the example given below.

create procedure sp_paging
(
 @pageno as int,
 @records as int
)
as
begin
declare @offsetcount as int
set @offsetcount=(@pageno-1)*@records
select id,bs,variable from salary order by id offset @offsetcount rows fetch Next @records rows only
end

you can execute it as follow.

exec sp_paging 2,3

Change event on select with knockout binding, how can I know if it is a real change?

If you use an observable instead of a primitive value, the select will not raise change events on initial binding. You can continue to bind to the change event, rather than subscribing directly to the observable.

How does bitshifting work in Java?

These examples cover the three types of shifts applied to both a positive and a negative number:

// Signed left shift on 626348975
00100101010101010101001110101111 is   626348975
01001010101010101010011101011110 is  1252697950 after << 1
10010101010101010100111010111100 is -1789571396 after << 2
00101010101010101001110101111000 is   715824504 after << 3

// Signed left shift on -552270512
11011111000101010000010101010000 is  -552270512
10111110001010100000101010100000 is -1104541024 after << 1
01111100010101000001010101000000 is  2085885248 after << 2
11111000101010000010101010000000 is  -123196800 after << 3


// Signed right shift on 626348975
00100101010101010101001110101111 is   626348975
00010010101010101010100111010111 is   313174487 after >> 1
00001001010101010101010011101011 is   156587243 after >> 2
00000100101010101010101001110101 is    78293621 after >> 3

// Signed right shift on -552270512
11011111000101010000010101010000 is  -552270512
11101111100010101000001010101000 is  -276135256 after >> 1
11110111110001010100000101010100 is  -138067628 after >> 2
11111011111000101010000010101010 is   -69033814 after >> 3


// Unsigned right shift on 626348975
00100101010101010101001110101111 is   626348975
00010010101010101010100111010111 is   313174487 after >>> 1
00001001010101010101010011101011 is   156587243 after >>> 2
00000100101010101010101001110101 is    78293621 after >>> 3

// Unsigned right shift on -552270512
11011111000101010000010101010000 is  -552270512
01101111100010101000001010101000 is  1871348392 after >>> 1
00110111110001010100000101010100 is   935674196 after >>> 2
00011011111000101010000010101010 is   467837098 after >>> 3

Append key/value pair to hash with << in Ruby

No, I don't think you can append key/value pairs. The only thing closest that I am aware of is using the store method:

h = {}
h.store("key", "value")

jQuery: Get the cursor position of text in input without browser specific code?

You can't do this without some browser specific code, since they implement text select ranged slightly differently. However, there are plugins that abstract this away. For exactly what you're after, there's the jQuery Caret (jCaret) plugin.

For your code to get the position you could do something like this:

$("#myTextInput").bind("keydown keypress mousemove", function() {
  alert("Current position: " + $(this).caret().start);
});

You can test it here.

How to process each output line in a loop?

Without any iteration with the --line-buffered grep option:

your_command | grep --line-buffered "your search"

Real life exemple with a Symfony PHP Framework router debug command ouput, to grep all "api" related routes:

php bin/console d:r | grep --line-buffered "api"

I am getting Failed to load resource: net::ERR_BLOCKED_BY_CLIENT with Google chrome

As other people have mentioned, this issue is common when using adblock or similar extensions.

The source of my issues was my Privacy Badger extension.

Centering elements in jQuery Mobile

I had found problems with some of the other methods mentioned here. Another way to do it would be to use layout grid B, and put your content in block b, and leave blocks a and c empty.

http://demos.jquerymobile.com/1.1.2/docs/content/content-grids.html

_x000D_
_x000D_
<div class="ui-grid-b">_x000D_
 <div class="ui-block-a"></div>_x000D_
 <div class="ui-block-b">Your Content Here</div>_x000D_
 <div class="ui-block-c"></div>_x000D_
</div><!-- /grid-b -->
_x000D_
_x000D_
_x000D_

Unable to verify leaf signature

You have to include the Intermediate certificate in your server. This solves the [Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE]

Passing a variable to a powershell script via command line

Make this in your test.ps1, at the first line

param(
[string]$a
)

Write-Host $a

Then you can call it with

./Test.ps1 "Here is your text"

Found here (English)

PHP - auto refreshing page

use this code ,it will automatically refresh in 5 seconds, you can change time in refresh

<?php $url1=$_SERVER['REQUEST_URI']; header("Refresh: 5; URL=$url1"); ?>

Using a different font with twitter bootstrap

you can customize twitter bootstrap css file, open the bootstrap.css file on a text editor, and change the font-family with your font name and SAVE it.

OR got to http://getbootstrap.com/customize/ and make a customized twitter bootstrap

Node.js console.log() not logging anything

Using modern --inspect with node the console.log is captured and relayed to the browser.

node --inspect myApp.js

or to capture early logging --inspect-brk can be used to stop the program on the first line of the first module...

node --inspect-brk myApp.js

Setting Column width in Apache POI

I answered my problem with a default width for all columns and cells, like below:

int width = 15; // Where width is number of caracters 
sheet.setDefaultColumnWidth(width);

Using other keys for the waitKey() function of opencv

For C++:

In case of using keyboard characters/numbers, an easier solution would be:

int key = cvWaitKey();

switch(key)
{
   case ((int)('a')):
   // do something if button 'a' is pressed
   break;
   case ((int)('h')):
   // do something if button 'h' is pressed
   break;
}

Simplest way to profile a PHP script

XDebug is not stable and it's not always available for particular php version. For example on some servers I still run php-5.1.6, -- it's what comes with RedHat RHEL5 (and btw still receives updates for all important issues), and recent XDebug does not even compile with this php. So I ended up with switching to DBG debugger Its php benchmarking provides timing for functions, methods, modules and even lines.

How to efficiently remove duplicates from an array without using Set

int tempvar=0; //Variable for the final array without any duplicates
     int whilecount=0;    //variable for while loop
     while(whilecount<(nsprtable*2)-1) //nsprtable can be any number
     {
//to check whether the next value is idential in case of sorted array       
if(temparray[whilecount]!=temparray[whilecount+1])
        {
            finalarray[tempvar]=temparray[whilecount];
            tempvar++;
            whilecount=whilecount+1;
        }
        else if (temparray[whilecount]==temparray[whilecount+1])
        {
            finalarray[tempvar]=temparray[whilecount];
            tempvar++;
            whilecount=whilecount+2;
        }
     }

Hope this helps or solves the purpose.

Bootstrap: add margin/padding space between columns

In the otherside if you like to remove double padding between columns just add class "nogap" inside row

<div class="row nogap">
    <div class="text-center col-md-6">Widget 1</div>
    <div class="text-center col-md-6">Widget 2</div>
</div>

and create additional css class for it

.nogap > .col{ padding-left:7.5px; padding-right: 7.5px}
.nogap > .col:first-child{ padding-left: 15px; }
.nogap > .col:last-child{ padding-right: 15px; }

Thats it, check here: https://codepen.io/michal-lukasik/pen/xXvoYJ

Use of PUT vs PATCH methods in REST API real life scenarios

One additional information I just one to add is that a PATCH request use less bandwidth compared to a PUT request since just a part of the data is sent not the whole entity. So just use a PATCH request for updates of specific records like (1-3 records) while PUT request for updating a larger amount of data. That is it, don't think too much or worry about it too much.

What is the difference between Sessions and Cookies in PHP?

Cookies are stored in browser as a text file format.It stores limited amount of data, up to 4kb[4096bytes].A single Cookie can not hold multiple values but yes we can have more than one cookie.

Cookies are easily accessible so they are less secure. The setcookie() function must appear BEFORE the tag.

Sessions are stored in server side.There is no such storage limit on session .Sessions can hold multiple variables.Since they are not easily accessible hence are more secure than cookies.

How do I remove link underlining in my HTML email?

To completely "hide" underline for <a> in both mail application and web browser, can do the following tricky way.

<a href="..."><div style="background-color:red;">
    <span style="color:red; text-decoration:underline;"><span style="color:white;">BUTTON</span></span>
</div></a>
  1. Color in 1st <span> is the one you don't need, MUST set as same as your background color. (red in here)

  2. Color in 2nd <span> is the one for your button text. (white in here)

Is "else if" faster than "switch() case"?

I'd say the switch is the way to go, it is both faster and better practise.

There are various links such as (http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx) that show benchmark tests comparing the two.

Centering a background image, using CSS

background-repeat:no-repeat;
background-position:center center;

Does not vertically center the background image when using a html 4.01 'STRICT' doctype.

Adding:

background-attachment: fixed;

Should fix the problem

(So Alexander is right)

Which are more performant, CTE or temporary tables?

CTE won't take any physical space. It is just a result set we can use join.

Temp tables are temporary. We can create indexes, constrains as like normal tables for that we need to define all variables.

Temp table's scope only within the session. EX: Open two SQL query window

create table #temp(empid int,empname varchar)
insert into #temp 
select 101,'xxx'

select * from #temp

Run this query in first window then run the below query in second window you can find the difference.

select * from #temp

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

Maybe an old version of the service was not uninstalled from windows

  1. uninstall the old version running this command line

    sc delete wampapache

  2. Reinstall the service from wamp:

    Wamp Tray Icon -> Apache -> Service -> Install Service

It works for me, enjoy!

Java program to find the largest & smallest number in n numbers without using arrays

Try the code mentioned below

public static void main(String[] args) {
    int smallest=0; int large=0; int num;
    System.out.println("enter the number");
    Scanner input=new Scanner(System.in);
    int n=input.nextInt();
    num=input.nextInt();
    smallest = num;
    for(int i=0;i<n-1;i++)
        {
            num=input.nextInt();
            if(num<smallest)
            {
                smallest=num;
            }
        }
        System.out.println("the smallest is:"+smallest);
}

How can I add numbers in a Bash script?

I always forget the syntax so I come to google, but then I never find the one I'm familiar with :P. This is the cleanest to me and more true to what I'd expect in other languages.

i=0
((i++))

echo $i;

Using the last-child selector

If you are floating the elements you can reverse the order

i.e. float: right; instead of float: left;

And then use this method to select the first-child of a class.

/* 1: Apply style to ALL instances */
#header .some-class {
  padding-right: 0;
}
/* 2: Remove style from ALL instances except FIRST instance */
#header .some-class~.some-class {
  padding-right: 20px;
}

This is actually applying the class to the LAST instance only because it's now in reversed order.

Here is a working example for you:

<!doctype html>
<head><title>CSS Test</title>
<style type="text/css">
.some-class { margin: 0; padding: 0 20px; list-style-type: square; }
.lfloat { float: left; display: block; }
.rfloat { float: right; display: block; }
/* apply style to last instance only */
#header .some-class {
  border: 1px solid red;
  padding-right: 0;
}
#header .some-class~.some-class {
  border: 0;
  padding-right: 20px;
}
</style>
</head>
<body>
<div id="header">
  <img src="some_image" title="Logo" class="lfloat no-border"/>
  <ul class="some-class rfloat">
    <li>List 1-1</li>
    <li>List 1-2</li>
    <li>List 1-3</li>
  </ul>
  <ul class="some-class rfloat">
    <li>List 2-1</li>
    <li>List 2-2</li>
    <li>List 2-3</li>
  </ul>
  <ul class="some-class rfloat">
    <li>List 3-1</li>
    <li>List 3-2</li>
    <li>List 3-3</li>
  </ul>
  <img src="some_other_img" title="Icon" class="rfloat no-border"/>
</div>
</body>
</html>

Using SED with wildcard

So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.

Find the index of a char in string?

The String class exposes some methods to enable this, such as IndexOf and LastIndexOf, so that you may do this:

Dim myText = "abcde"
Dim dIndex = myText.IndexOf("d")
If (dIndex > -1) Then

End If

jQuery checkbox check/uncheck

 $('mainCheckBox').click(function(){
    if($(this).prop('checked')){
        $('Id or Class of checkbox').prop('checked', true);
    }else{
        $('Id or Class of checkbox').prop('checked', false);
    }
});

MassAssignmentException in Laravel

Just add Eloquent::unguard(); in the top of the run method when you do a seed, no need to create an $fillable array in all the models you have to seed.

Normally this is already specified in the DatabaseSeeder class. However because you're calling the UsersTableSeeder directly:

php artisan db:seed --class="UsersTableSeeder"

Eloquent::unguard(); isn't being called and gives the error.

OS specific instructions in CMAKE: How to?

I want to leave this here because I struggled with this when compiling for Android in Windows with the Android SDK.

CMake distinguishes between TARGET and HOST platform.

My TARGET was Android so the variables like CMAKE_SYSTEM_NAME had the value "Android" and the variable WIN32 from the other answer here was not defined. But I wanted to know if my HOST system was Windows because I needed to do a few things differently when compiling on either Windows or Linux or IOs. To do that I used CMAKE_HOST_SYSTEM_NAME which I found is barely known or mentioned anywhere because for most people TARGEt and HOST are the same or they don't care.

Hope this helps someone somewhere...

Prevent flicker on webkit-transition of webkit-transform

The rule:

-webkit-backface-visibility: hidden;

will not work for sprites or image backgrounds.

body {-webkit-transform:translate3d(0,0,0);}

screws up backgrounds that are tiled.

I prefer to make a class called no-flick and do this:

.no-flick{-webkit-transform:translate3d(0,0,0);}

REST API Token-based Authentication

In the web a stateful protocol is based on having a temporary token that is exchanged between a browser and a server (via cookie header or URI rewriting) on every request. That token is usually created on the server end, and it is a piece of opaque data that has a certain time-to-live, and it has the sole purpose of identifying a specific web user agent. That is, the token is temporary, and becomes a STATE that the web server has to maintain on behalf of a client user agent during the duration of that conversation. Therefore, the communication using a token in this way is STATEFUL. And if the conversation between client and server is STATEFUL it is not RESTful.

The username/password (sent on the Authorization header) is usually persisted on the database with the intent of identifying a user. Sometimes the user could mean another application; however, the username/password is NEVER intended to identify a specific web client user agent. The conversation between a web agent and server based on using the username/password in the Authorization header (following the HTTP Basic Authorization) is STATELESS because the web server front-end is not creating or maintaining any STATE information whatsoever on behalf of a specific web client user agent. And based on my understanding of REST, the protocol states clearly that the conversation between clients and server should be STATELESS. Therefore, if we want to have a true RESTful service we should use username/password (Refer to RFC mentioned in my previous post) in the Authorization header for every single call, NOT a sension kind of token (e.g. Session tokens created in web servers, OAuth tokens created in authorization servers, and so on).

I understand that several called REST providers are using tokens like OAuth1 or OAuth2 accept-tokens to be be passed as "Authorization: Bearer " in HTTP headers. However, it appears to me that using those tokens for RESTful services would violate the true STATELESS meaning that REST embraces; because those tokens are temporary piece of data created/maintained on the server side to identify a specific web client user agent for the valid duration of a that web client/server conversation. Therefore, any service that is using those OAuth1/2 tokens should not be called REST if we want to stick to the TRUE meaning of a STATELESS protocol.

Rubens

jQuery-- Populate select from json

I would do something like this:

$.each(temp,function(key, value) 
{
    $select.append('<option value=' + key + '>' + value + '</option>');
});

JSON structure would be appreciated. At first you can experiment with find('element') - it depends on JSON.

adding multiple event listeners to one element

//catch volume update
var volEvents = "change,input";
var volEventsArr = volEvents.split(",");
for(var i = 0;i<volknob.length;i++) {
    for(var k=0;k<volEventsArr.length;k++) {
    volknob[i].addEventListener(volEventsArr[k], function() {
        var cfa = document.getElementsByClassName('watch_televised');
        for (var j = 0; j<cfa.length; j++) {
            cfa[j].volume = this.value / 100;
        }
    });
}
}

Deep copy an array in Angular 2 + TypeScript

Here is my own. Doesn't work for complex cases, but for a simple array of Objects, it's good enough.

  deepClone(oldArray: Object[]) {
    let newArray: any = [];
    oldArray.forEach((item) => {
      newArray.push(Object.assign({}, item));
    });
    return newArray;
  }

How do I test a private function or a class that has private methods, fields or inner classes?

Groovy has a bug/feature, through which you can invoke private methods as if they were public. So if you're able to use Groovy in your project, it's an option you can use in lieu of reflection. Check out this page for an example.

JavaScript ternary operator example with functions

There is nothing particularly tricky about the example you posted.

In a ternary operator, the first argument (the conditional) is evaluated and if the result is true, the second argument is evaluated and returned, otherwise, the third is evaluated and returned. Each of those arguments can be any valid code block, including function calls.

Think of it this way:

var x = (1 < 2) ? true : false;

Could also be written as:

var x = (1 < 2) ? getTrueValue() : getFalseValue();

This is perfectly valid, and those functions can contain any arbitrary code, whether it is related to returning a value or not. Additionally, the results of the ternary operation don't have to be assigned to anything, just as function results do not have to be assigned to anything:

(1 < 2) ? getTrueValue() : getFalseValue();

Now simply replace those with any arbitrary functions, and you are left with something like your example:

(1 < 2) ? removeItem($this) : addItem($this);

Now your last example really doesn't need a ternary at all, as it can be written like this:

x = (1 < 2);  // x will be set to "true"

Foreign Key to multiple tables

CREATE TABLE dbo.OwnerType
(
    ID int NOT NULL,
    Name varchar(50) NULL
)

insert into OwnerType (Name) values ('User');
insert into OwnerType (Name) values ('Group');

I think that would be the most general way to represent what you want instead of using a flag.

How to set fake GPS location on IOS real device

Of course ios7 prohibits creating fake locations on real device.
For testing purpose there are two approches:
1) while device is connected to xcode, use the simulator and let it play a gpx track.

2) for real world testing, not connected to simu, one possibility is that your app, has a special modus built in, where you set it to "playback" mode. In that mode the app has to create the locations itself, using a timer of 1s, and creating a new CLLocation object.

3) A third possibility is described here: https://blackpixel.com/writing/2013/05/simulating-locations-with-xcode.html

How to apply a patch generated with git format-patch?

Note: You can first preview what your patch will do:

First the stats:

git apply --stat a_file.patch

Then a dry run to detect errors:

git apply --check a_file.patch

Finally, you can use git am to apply your patch as a commit. This also allows you to sign off an applied patch.
This can be useful for later reference.

git am --signoff < a_file.patch 

See an example in this article:

In your git log, you’ll find that the commit messages contain a “Signed-off-by” tag. This tag will be read by Github and others to provide useful info about how the commit ended up in the code.

Example

SQL Server - Convert varchar to another collation (code page) to fix character encoding

Character set conversion is done implicitly on the database connection level. You can force automatic conversion off in the ODBC or ADODB connection string with the parameter "Auto Translate=False". This is NOT recommended. See: https://msdn.microsoft.com/en-us/library/ms130822.aspx

There has been a codepage incompatibility in SQL Server 2005 when Database and Client codepage did not match. https://support.microsoft.com/kb/KbView/904803

SQL-Management Console 2008 and upwards is a UNICODE application. All values entered or requested are interpreted as such on the application level. Conversation to and from the column collation is done implicitly. You can verify this with:

SELECT CAST(N'±' as varbinary(10)) AS Result

This will return 0xB100 which is the Unicode character U+00B1 (as entered in the Management Console window). You cannot turn off "Auto Translate" for Management Studio.

If you specify a different collation in the select, you eventually end up in a double conversion (with possible data loss) as long as "Auto Translate" is still active. The original character is first transformed to the new collation during the select, which in turn gets "Auto Translated" to the "proper" application codepage. That's why your various COLLATION tests still show all the same result.

You can verify that specifying the collation DOES have an effect in the select, if you cast the result as VARBINARY instead of VARCHAR so the SQL Server transformation is not invalidated by the client before it is presented:

SELECT cast(columnName COLLATE SQL_Latin1_General_CP850_BIN2 as varbinary(10)) from tableName
SELECT cast(columnName COLLATE SQL_Latin1_General_CP1_CI_AS as varbinary(10)) from tableName

This will get you 0xF1 or 0xB1 respectively if columnName contains just the character '±'

You still might get the correct result and yet a wrong character, if the font you are using does not provide the proper glyph.

Please double check the actual internal representation of your character by casting the query to VARBINARY on a proper sample and verify whether this code indeed corresponds to the defined database collation SQL_Latin1_General_CP850_BIN2

SELECT CAST(columnName as varbinary(10)) from tableName

Differences in application collation and database collation might go unnoticed as long as the conversion is always done the same way in and out. Troubles emerge as soon as you add a client with a different collation. Then you might find that the internal conversion is unable to match the characters correctly.

All that said, you should keep in mind that Management Studio usually is not the final reference when interpreting result sets. Even if it looks gibberish in MS, it still might be the correct output. The question is whether the records show up correctly in your applications.

How to use WPF Background Worker

using System;  
using System.ComponentModel;   
using System.Threading;    
namespace BackGroundWorkerExample  
{   
    class Program  
    {  
        private static BackgroundWorker backgroundWorker;  

        static void Main(string[] args)  
        {  
            backgroundWorker = new BackgroundWorker  
            {  
                WorkerReportsProgress = true,  
                WorkerSupportsCancellation = true  
            };  

            backgroundWorker.DoWork += backgroundWorker_DoWork;  
            //For the display of operation progress to UI.    
            backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;  
            //After the completation of operation.    
            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;  
            backgroundWorker.RunWorkerAsync("Press Enter in the next 5 seconds to Cancel operation:");  

            Console.ReadLine();  

            if (backgroundWorker.IsBusy)  
            { 
                backgroundWorker.CancelAsync();  
                Console.ReadLine();  
            }  
        }  

        static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)  
        {  
            for (int i = 0; i < 200; i++)  
            {  
                if (backgroundWorker.CancellationPending)  
                {  
                    e.Cancel = true;  
                    return;  
                }  

                backgroundWorker.ReportProgress(i);  
                Thread.Sleep(1000);  
                e.Result = 1000;  
            }  
        }  

        static void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)  
        {  
            Console.WriteLine("Completed" + e.ProgressPercentage + "%");  
        }  

        static void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)  
        {  

            if (e.Cancelled)  
            {  
                Console.WriteLine("Operation Cancelled");  
            }  
            else if (e.Error != null)  
            {  
                Console.WriteLine("Error in Process :" + e.Error);  
            }  
            else  
            {  
                Console.WriteLine("Operation Completed :" + e.Result);  
            }  
        }  
    }  
} 

Also, referr the below link you will understand the concepts of Background:

http://www.c-sharpcorner.com/UploadFile/1c8574/threads-in-wpf/

How to prevent line breaks in list items using CSS

display: inline-block; will prevent break between the words in a list item

 li {
    display: inline-block;
 }

Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'

This is a problem that can arise from writing down a "filename" instead of a path, while generating the .jks file. Generate a new one, put it on the Desktop (or any other real path) and re-generate APK.

Load More Posts Ajax Button in WordPress

If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.

Having both a Created and Last Updated timestamp columns in MySQL 4.0

As of MySQL 5.6 its easy-peasy... give it a try:

create table tweet ( 
    id integer not null auto_increment primary key, 
    stamp_created timestamp default now(), 
    stamp_updated timestamp default now() on update now(),
    message varchar(163)
)

How to [recursively] Zip a directory in PHP?

USAGE: thisfile.php?dir=./path/to/folder (After zipping, it starts download too:)

<?php
$exclude_some_files=
array(
        'mainfolder/folder1/filename.php',
        'mainfolder/folder5/otherfile.php'
);

//***************built from https://gist.github.com/ninadsp/6098467 ******
class ModifiedFlxZipArchive extends ZipArchive {
    public function addDirDoo($location, $name , $prohib_filenames=false) {
        if (!file_exists($location)) {  die("maybe file/folder path incorrect");}

        $this->addEmptyDir($name);
        $name .= '/';
        $location.= '/';
        $dir = opendir ($location);   // Read all Files in Dir

        while ($file = readdir($dir)){
            if ($file == '.' || $file == '..') continue;
            if (!in_array($name.$file,$prohib_filenames)){
                if (filetype( $location . $file) == 'dir'){
                    $this->addDirDoo($location . $file, $name . $file,$prohib_filenames );
                }
                else {
                    $this->addFile($location . $file, $name . $file);
                }
            }
        }
    }

    public function downld($zip_name){
        ob_get_clean();
        header("Pragma: public");   header("Expires: 0");   header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private", false);    header("Content-Type: application/zip");
        header("Content-Disposition: attachment; filename=" . basename($zip_name) . ";" );
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: " . filesize($zip_name));
        readfile($zip_name);
    }
}

//set memory limits
set_time_limit(3000);
ini_set('max_execution_time', 3000);
ini_set('memory_limit','100M');
$new_zip_filename='down_zip_file_'.rand(1,1000000).'.zip';  
// Download action
if (isset($_GET['dir']))    {
    $za = new ModifiedFlxZipArchive;
    //create an archive
    if  ($za->open($new_zip_filename, ZipArchive::CREATE)) {
        $za->addDirDoo($_GET['dir'], basename($_GET['dir']), $exclude_some_files); $za->close();
    }else {die('cantttt');}

if (isset($_GET['dir']))    {
    $za = new ModifiedFlxZipArchive;
    //create an archive
    if  ($za->open($new_zip_filename, ZipArchive::CREATE)) {
        $za->addDirDoo($_GET['dir'], basename($_GET['dir']), $exclude_some_files); $za->close();
    }else {die('cantttt');}

    //download archive
    //on the same execution,this made problems in some hostings, so better redirect
    //$za -> downld($new_zip_filename);
    header("location:?fildown=".$new_zip_filename); exit;
}   
if (isset($_GET['fildown'])){
    $za = new ModifiedFlxZipArchive;
    $za -> downld($_GET['fildown']);
}
?>

Getting a list of files in a directory with a glob

I won't pretend to be an expert on the topic, but you should have access to both the glob and wordexp function from objective-c, no?

Install python 2.6 in CentOS

No need to do yum or make your own RPM. Build python26 from source.

wget https://www.python.org/ftp/python/2.6.6/Python-2.6.6.tgz
tar -zxvf Python-2.6.6.tgz
cd Python-2.6.6
./configure && make && make install

There can be a dependency error use

yum install gcc cc

Add the install path (/usr/local/bin/python by default) to ~/.bash_profile.

It will not break yum or any other things which are dependent on python24.

No newline at end of file

The core problem is what you define line and whether end-on-line character sequence is part of the line or not. UNIX-based editors (such as VIM) or tools (such as Git) use EOL character sequence as line terminator, therefore it's a part of the line. It's similar to use of semicolon (;) in C and Pascal. In C semicolon terminates statements, in Pascal it separates them.

How do I update a Linq to SQL dbml file?

You could also check out the PLINQO set of code generation templates, based on CodeSmith, which allow you to do a lot of neat things for and with Linq-to-SQL:

  • generate one file per class (instead of a single, huge file)
  • update your model as needed
  • many more features

Check out the PLINQO site at http://www.plinqo.com and have a look at the intro videos.

The second tool I know of are the Huagati DBML/EDMX tools, which allow update of DBML (Linq-to-SQL) and EDMX (Entity Framework) mapping files, and more (like naming conventions etc.).

Marc

AngularJS : How to watch service variables?

I have found a really great solution on the other thread with a similar problem but totally different approach. Source: AngularJS : $watch within directive is not working when $rootScope value is changed

Basically the solution there tells NOT TO use $watch as it is very heavy solution. Instead they propose to use $emit and $on.

My problem was to watch a variable in my service and react in directive. And with the above method it very easy!

My module/service example:

angular.module('xxx').factory('example', function ($rootScope) {
    var user;

    return {
        setUser: function (aUser) {
            user = aUser;
            $rootScope.$emit('user:change');
        },
        getUser: function () {
            return (user) ? user : false;
        },
        ...
    };
});

So basically I watch my user - whenever it is set to new value I $emit a user:change status.

Now in my case, in the directive I used:

angular.module('xxx').directive('directive', function (Auth, $rootScope) {
    return {
        ...
        link: function (scope, element, attrs) {
            ...
            $rootScope.$on('user:change', update);
        }
    };
});

Now in the directive I listen on the $rootScope and on the given change - I react respectively. Very easy and elegant!

Laravel where on relationship object

[OOT]

A bit OOT, but this question is the most closest topic with my question.

Here is an example if you want to show Event where ALL participant meet certain requirement. Let's say, event where ALL the participant has fully paid. So, it WILL NOT return events which having one or more participants that haven't fully paid .

Simply use the whereDoesntHave of the others 2 statuses.

Let's say the statuses are haven't paid at all [eq:1], paid some of it [eq:2], and fully paid [eq:3]

Event::whereDoesntHave('participants', function ($query) {
   return $query->whereRaw('payment = 1 or payment = 2');
})->get();

Tested on Laravel 5.8 - 7.x

What does "#pragma comment" mean?

These link in the libraries selected in MSVC++.

How to extract string following a pattern with grep, regex or perl

If you're using Perl, download a module to parse the XML: XML::Simple, XML::Twig, or XML::LibXML. Don't re-invent the wheel.

Modulo operation with negative numbers

In Mathematics, where these conventions stem from, there is no assertion that modulo arithmetic should yield a positive result.

Eg.

1 mod 5 = 1, but it can also equal -4. That is, 1/5 yields a remainder 1 from 0 or -4 from 5. (Both factors of 5)

Similarly, -1 mod 5 = -1, but it can also equal 4. That is, -1/5 yields a remainder -1 from 0 or 4 from -5. (Both factors of 5)

For further reading look into equivalence classes in Mathematics.

How to deal with page breaks when printing a large HTML table

Well Guys... Most of the Solutions up here didn't worked for. So this is how things worked for me..

HTML

<table>
  <thead>
   <tr>
     <th style="border:none;height:26px;"></th>
     <th style="border:none;height:26px;"></th>
     .
     .
   </tr>
   <tr>
     <th style="border:1px solid black">ABC</th>
     <th style="border:1px solid black">ABC</th>
     .
     .
   <tr>
  </thead>
<tbody>

    //YOUR CODE

</tbody>
</table>

The first set of head is used as a dummy one so that there won't be a missing top border in 2nd head(i.e. original head) while page break.

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

An alternative to the already provided ways is to simply filter on the column like so

df = df.where(F.col('columnNameHere').isNull())

This has the added benefit that you don't have to add another column to do the filtering and it's quick on larger data sets.

UITableView - change section header color

This is an old question, but I think the answer needs to be updated.

This method does not involve defining and creating your own custom view. In iOS 6 and up, you can easily change the background color and the text color by defining the

-(void)tableView:(UITableView *)tableView 
    willDisplayHeaderView:(UIView *)view 
    forSection:(NSInteger)section

section delegate method

For example:

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // Background color
    view.tintColor = [UIColor blackColor];

    // Text Color
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    [header.textLabel setTextColor:[UIColor whiteColor]];

    // Another way to set the background color
    // Note: does not preserve gradient effect of original header
    // header.contentView.backgroundColor = [UIColor blackColor];
}

Taken from my post here: https://happyteamlabs.com/blog/ios-how-to-customize-table-view-header-and-footer-colors/

Swift 3 / 4

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
    view.tintColor = UIColor.red
    let header = view as! UITableViewHeaderFooterView
    header.textLabel?.textColor = UIColor.white
}

ssh: The authenticity of host 'hostname' can't be established

The following steps are used to authenticate yourself to the host

  1. Generate a ssh key. You will be asked to create a password for the key
ssh-keygen -f ~/.ssh/id_ecdsa -t ecdsa -b 521

(above uses the recommended encryption technique)

  1. Copy the key over to the remote host
ssh-copy-id -i ~/.ssh/id_ecdsa user@host

N.B the user @ host will be different to you. You will need to type in the password for this server, not the keys password.

  1. You can now login to the server securely and not get an error message.
ssh user@host

All source information is located here: ssh-keygen

Cocoa: What's the difference between the frame and the bounds?

Short Answer

frame = a view's location and size using the parent view's coordinate system

  • Important for: placing the view in the parent

bounds = a view's location and size using its own coordinate system

  • Important for: placing the view's content or subviews within itself

Detailed Answer

To help me remember frame, I think of a picture frame on a wall. The picture frame is like the border of a view. I can hang the picture anywhere I want on the wall. In the same way, I can put a view anywhere I want inside a parent view (also called a superview). The parent view is like the wall. The origin of the coordinate system in iOS is the top left. We can put our view at the origin of the superview by setting the view frame's x-y coordinates to (0, 0), which is like hanging our picture in the very top left corner of the wall. To move it right, increase x, to move it down increase y.

To help me remember bounds, I think of a basketball court where sometimes the basketball gets knocked out of bounds. You are dribbling the ball all over the basketball court, but you don't really care where the court itself is. It could be in a gym, or outside at a high school, or in front of your house. It doesn't matter. You just want to play basketball. In the same way, the coordinate system for a view's bounds only cares about the view itself. It doesn't know anything about where the view is located in the parent view. The bounds' origin (point (0, 0) by default) is the top left corner of the view. Any subviews that this view has are laid out in relation to this point. It is like taking the basketball to the front left corner of the court.

Now the confusion comes when you try to compare frame and bounds. It actually isn't as bad as it seems at first, though. Let's use some pictures to help us understand.

Frame vs Bounds

In the first picture on the left we have a view that is located at the top left of its parent view. The yellow rectangle represents the view's frame. On the right we see the view again but this time the parent view is not shown. That's because the bounds don't know about the parent view. The green rectangle represents the view's bounds. The red dot in both images represents the origin of the frame or bounds.

Frame
    origin = (0, 0)
    width = 80
    height = 130

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here

So the frame and bounds were exactly the same in that picture. Let's look at an example where they are different.

Frame
    origin = (40, 60)  // That is, x=40 and y=60
    width = 80
    height = 130

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here

So you can see that changing the x-y coordinates of the frame moves it in the parent view. But the content of the view itself still looks exactly the same. The bounds have no idea that anything is different.

Up to now the width and height of both the frame and the bounds have been exactly the same. That isn't always true, though. Look what happens if we rotate the view 20 degrees clockwise. (Rotation is done using transforms. See the the documentation and these view and layer examples for more information.)

Frame
    origin = (20, 52)  // These are just rough estimates.
    width = 118
    height = 187

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here

You can see that the bounds are still the same. They still don't know anything has happened! The frame values have all changed, though.

Now it is a little easier to see the difference between frame and bounds, isn't it? The article You Probably Don't Understand frames and bounds defines a view frame as

...the smallest bounding box of that view with respect to it’s parents coordinate system, including any transformations applied to that view.

It is important to note that if you transform a view, then the frame becomes undefined. So actually, the yellow frame that I drew around the rotated green bounds in the image above never actually exists. That means if you rotate, scale or do some other transformation then you shouldn't use the frame values any more. You can still use the bounds values, though. The Apple docs warn:

Important: If a view’s transform property does not contain the identity transform, the frame of that view is undefined and so are the results of its autoresizing behaviors.

Rather unfortunate about the autoresizing.... There is something you can do, though.

The Apple docs state:

When modifying the transform property of your view, all transformations are performed relative to the center point of the view.

So if you do need to move a view around in the parent after a transformation has been done, you can do it by changing the view.center coordinates. Like frame, center uses the coordinate system of the parent view.

Ok, let's get rid of our rotation and focus on the bounds. So far the bounds origin has always stayed at (0, 0). It doesn't have to, though. What if our view has a large subview that is too big to display all at once? We'll make it a UIImageView with a large image. Here is our second picture from above again, but this time we can see what the whole content of our view's subview would look like.

Frame
    origin = (40, 60)
    width = 80
    height = 130

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here

Only the top left corner of the image can fit inside the view's bounds. Now look what happens if we change the bounds' origin coordinates.

Frame
    origin = (40, 60)
    width = 80
    height = 130

Bounds 
    origin = (280, 70)
    width = 80
    height = 130

enter image description here

The frame hasn't moved in the superview but the content inside the frame has changed because the origin of the bounds rectangle starts at a different part of the view. This is the whole idea behind a UIScrollView and it's subclasses (for example, a UITableView). See Understanding UIScrollView for more explanation.

When to use frame and when to use bounds

Since frame relates a view's location in its parent view, you use it when you are making outward changes, like changing its width or finding the distance between the view and the top of its parent view.

Use the bounds when you are making inward changes, like drawing things or arranging subviews within the view. Also use the bounds to get the size of the view if you have done some transfomation on it.

Articles for further research:

Apple docs

Related StackOverflow questions

Other resources

Practice yourself

In addition to reading the above articles, it helps me a lot to make a test app. You might want to try to do something similar. (I got the idea from this video course but unfortunately it isn't free.)

enter image description here

Here is the code for your reference:

import UIKit

class ViewController: UIViewController {


    @IBOutlet weak var myView: UIView!

    // Labels
    @IBOutlet weak var frameX: UILabel!
    @IBOutlet weak var frameY: UILabel!
    @IBOutlet weak var frameWidth: UILabel!
    @IBOutlet weak var frameHeight: UILabel!
    @IBOutlet weak var boundsX: UILabel!
    @IBOutlet weak var boundsY: UILabel!
    @IBOutlet weak var boundsWidth: UILabel!
    @IBOutlet weak var boundsHeight: UILabel!
    @IBOutlet weak var centerX: UILabel!
    @IBOutlet weak var centerY: UILabel!
    @IBOutlet weak var rotation: UILabel!

    // Sliders
    @IBOutlet weak var frameXSlider: UISlider!
    @IBOutlet weak var frameYSlider: UISlider!
    @IBOutlet weak var frameWidthSlider: UISlider!
    @IBOutlet weak var frameHeightSlider: UISlider!
    @IBOutlet weak var boundsXSlider: UISlider!
    @IBOutlet weak var boundsYSlider: UISlider!
    @IBOutlet weak var boundsWidthSlider: UISlider!
    @IBOutlet weak var boundsHeightSlider: UISlider!
    @IBOutlet weak var centerXSlider: UISlider!
    @IBOutlet weak var centerYSlider: UISlider!
    @IBOutlet weak var rotationSlider: UISlider!

    // Slider actions
    @IBAction func frameXSliderChanged(sender: AnyObject) {
        myView.frame.origin.x = CGFloat(frameXSlider.value)
        updateLabels()
    }
    @IBAction func frameYSliderChanged(sender: AnyObject) {
        myView.frame.origin.y = CGFloat(frameYSlider.value)
        updateLabels()
    }
    @IBAction func frameWidthSliderChanged(sender: AnyObject) {
        myView.frame.size.width = CGFloat(frameWidthSlider.value)
        updateLabels()
    }
    @IBAction func frameHeightSliderChanged(sender: AnyObject) {
        myView.frame.size.height = CGFloat(frameHeightSlider.value)
        updateLabels()
    }
    @IBAction func boundsXSliderChanged(sender: AnyObject) {
        myView.bounds.origin.x = CGFloat(boundsXSlider.value)
        updateLabels()
    }
    @IBAction func boundsYSliderChanged(sender: AnyObject) {
        myView.bounds.origin.y = CGFloat(boundsYSlider.value)
        updateLabels()
    }
    @IBAction func boundsWidthSliderChanged(sender: AnyObject) {
        myView.bounds.size.width = CGFloat(boundsWidthSlider.value)
        updateLabels()
    }
    @IBAction func boundsHeightSliderChanged(sender: AnyObject) {
        myView.bounds.size.height = CGFloat(boundsHeightSlider.value)
        updateLabels()
    }
    @IBAction func centerXSliderChanged(sender: AnyObject) {
        myView.center.x = CGFloat(centerXSlider.value)
        updateLabels()
    }
    @IBAction func centerYSliderChanged(sender: AnyObject) {
        myView.center.y = CGFloat(centerYSlider.value)
        updateLabels()
    }
    @IBAction func rotationSliderChanged(sender: AnyObject) {
        let rotation = CGAffineTransform(rotationAngle: CGFloat(rotationSlider.value))
        myView.transform = rotation
        updateLabels()
    }

    private func updateLabels() {

        frameX.text = "frame x = \(Int(myView.frame.origin.x))"
        frameY.text = "frame y = \(Int(myView.frame.origin.y))"
        frameWidth.text = "frame width = \(Int(myView.frame.width))"
        frameHeight.text = "frame height = \(Int(myView.frame.height))"
        boundsX.text = "bounds x = \(Int(myView.bounds.origin.x))"
        boundsY.text = "bounds y = \(Int(myView.bounds.origin.y))"
        boundsWidth.text = "bounds width = \(Int(myView.bounds.width))"
        boundsHeight.text = "bounds height = \(Int(myView.bounds.height))"
        centerX.text = "center x = \(Int(myView.center.x))"
        centerY.text = "center y = \(Int(myView.center.y))"
        rotation.text = "rotation = \((rotationSlider.value))"

    }

}

ASP.NET MVC: Custom Validation by DataAnnotation

ExpressiveAnnotations gives you such a possibility:

[Required]
[AssertThat("Length(FieldA) + Length(FieldB) + Length(FieldC) + Length(FieldD) > 50")]
public string FieldA { get; set; }

Rails Root directory path?

For super correctness, you should use:

Rails.root.join('foo','bar')

which will allow your app to work on platforms where / is not the directory separator, should anyone try and run it on one.

How to Convert UTC Date To Local time Zone in MySql Select Query

 select convert_tz(now(),@@session.time_zone,'+05:30')

replace '+05:30' with desired timezone. see here - https://stackoverflow.com/a/3984412/2359994

to format into desired time format, eg:

 select DATE_FORMAT(convert_tz(now(),@@session.time_zone,'+05:30') ,'%b %d %Y %h:%i:%s %p') 

you will get similar to this -> Dec 17 2014 10:39:56 AM

What is the hamburger menu icon called and the three vertical dots icon called?

Cannot say about the "official nomenclature" - infact I wonder whose word will be "official" anyway - but here's how they can be called:

CSS display:inline property with list-style-image: property on <li> tags

If you look at the 'display' property in the CSS spec, you will see that 'list-item' is specifically a display type. When you set an item to "inline", you're replacing the default display type of list-item, and the marker is specifically a part of the list-item type.

The above answer suggests float, but I've tried that and it doesn't work (at least on Chrome). According to the spec, if you set your boxes to float left or right,"The 'display' is ignored, unless it has the value 'none'." I take this to mean that the default display type of 'list-item' is gone (taking the marker with it) as soon as you float the element.

Edit: Yeah, I guess I was wrong. See top entry. :)

PowerShell To Set Folder Permissions

Referring to Gamaliel 's answer: $args is an array of the arguments that are passed into a script at runtime - as such cannot be used the way Gamaliel is using it. This is actually working:

$myPath = 'C:\whatever.file'
# get actual Acl entry
$myAcl = Get-Acl "$myPath"
$myAclEntry = "Domain\User","FullControl","Allow"
$myAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($myAclEntry)
# prepare new Acl
$myAcl.SetAccessRule($myAccessRule)
$myAcl | Set-Acl "$MyPath"
# check if added entry present
Get-Acl "$myPath" | fl

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

The two commands have the same effect (thanks to Robert Siemer’s answer for pointing it out).

The practical difference comes when using a local branch named differently:

  • git checkout -b mybranch origin/abranch will create mybranch and track origin/abranch
  • git checkout --track origin/abranch will only create 'abranch', not a branch with a different name.

(That is, as commented by Sebastian Graf, if the local branch did not exist already.
If it did, you would need git checkout -B abranch origin/abranch)


Note: with Git 2.23 (Q3 2019), that would use the new command git switch:

git switch -c <branch> --track <remote>/<branch>

If the branch exists in multiple remotes and one of them is named by the checkout.defaultRemote configuration variable, we'll use that one for the purposes of disambiguation, even if the <branch> isn't unique across all remotes.
Set it to e.g. checkout.defaultRemote=origin to always checkout remote branches from there if <branch> is ambiguous but exists on the 'origin' remote.

Here, '-c' is the new '-b'.


First, some background: Tracking means that a local branch has its upstream set to a remote branch:

# git config branch.<branch-name>.remote origin
# git config branch.<branch-name>.merge refs/heads/branch

git checkout -b branch origin/branch will:

  • create/reset branch to the point referenced by origin/branch.
  • create the branch branch (with git branch) and track the remote tracking branch origin/branch.

When a local branch is started off a remote-tracking branch, Git sets up the branch (specifically the branch.<name>.remote and branch.<name>.merge configuration entries) so that git pull will appropriately merge from the remote-tracking branch.
This behavior may be changed via the global branch.autosetupmerge configuration flag. That setting can be overridden by using the --track and --no-track options, and changed later using git branch --set-upstream-to.


And git checkout --track origin/branch will do the same as git branch --set-upstream-to):

 # or, since 1.7.0
 git branch --set-upstream upstream/branch branch
 # or, since 1.8.0 (October 2012)
 git branch --set-upstream-to upstream/branch branch
 # the short version remains the same:
 git branch -u upstream/branch branch

It would also set the upstream for 'branch'.

(Note: git1.8.0 will deprecate git branch --set-upstream and replace it with git branch -u|--set-upstream-to: see git1.8.0-rc1 announce)


Having an upstream branch registered for a local branch will:

  • tell git to show the relationship between the two branches in git status and git branch -v.
  • directs git pull without arguments to pull from the upstream when the new branch is checked out.

See "How do you make an existing git branch track a remote branch?" for more.

How to block users from closing a window in Javascript?

If your sending out an internal survey that requires 100% participation from your company's employees, then a better route would be to just have the form keep track of the responders ID/Username/email etc. Every few days or so just send a nice little email reminder to those in your organization to complete the survey...you could probably even automate this.

Stack, Static, and Heap in C++

Stack memory allocation (function variables, local variables) can be problematic when your stack is too "deep" and you overflow the memory available to stack allocations. The heap is for objects that need to be accessed from multiple threads or throughout the program lifecycle. You can write an entire program without using the heap.

You can leak memory quite easily without a garbage collector, but you can also dictate when objects and memory is freed. I have run in to issues with Java when it runs the GC and I have a real time process, because the GC is an exclusive thread (nothing else can run). So if performance is critical and you can guarantee there are no leaked objects, not using a GC is very helpful. Otherwise it just makes you hate life when your application consumes memory and you have to track down the source of a leak.

AndroidStudio: Failed to sync Install build tools

There may be some file access permission/restriction problems. First check to access the below directory manually, check whether your TARGET_VERSION exists, Then check the android sdk manager.

  • sdk/build-tools/{TARGET_VERSION}

Angular : Manual redirect to route

You should inject Router in your constructor like this;

constructor(private router: Router) { }

then you can do this anywhere you want;

this.router.navigate(['/product-list']);

How to enable local network users to access my WAMP sites?

I have some experiences in Wamp 3.0 and Apache 2.4 .

After all works do this steps:

1- Disable nod32.

2- Add this line to <VirtualHost *:80> block in httpd-vhosts.conf file:

Require ip 192.168.100 #client ip, allow 192.168.100.### ip's access

Serializing/deserializing with memory stream

This code works for me:

public void Run()
{
    Dog myDog = new Dog();
    myDog.Name= "Foo";
    myDog.Color = DogColor.Brown;

    System.Console.WriteLine("{0}", myDog.ToString());

    MemoryStream stream = SerializeToStream(myDog);

    Dog newDog = (Dog)DeserializeFromStream(stream);

    System.Console.WriteLine("{0}", newDog.ToString());
}

Where the types are like this:

[Serializable]
public enum DogColor
{
    Brown,
    Black,
    Mottled
}

[Serializable]
public class Dog
{
    public String Name
    {
        get; set;
    }

    public DogColor Color
    {
        get;set;
    }

    public override String ToString()
    {
        return String.Format("Dog: {0}/{1}", Name, Color);
    }
}

and the utility methods are:

public static MemoryStream SerializeToStream(object o)
{
    MemoryStream stream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, o);
    return stream;
}

public static object DeserializeFromStream(MemoryStream stream)
{
    IFormatter formatter = new BinaryFormatter();
    stream.Seek(0, SeekOrigin.Begin);
    object o = formatter.Deserialize(stream);
    return o;
}

Scrolling to an Anchor using Transition/CSS3

Only mozilla implements a simple property in css : http://caniuse.com/#search=scroll-behavior

you will have to use JS at least.

I personally use this because its easy to use (I use JQ but you can adapt it I guess):

/*Scroll transition to anchor*/
$("a.toscroll").on('click',function(e) {
    var url = e.target.href;
    var hash = url.substring(url.indexOf("#")+1);
    $('html, body').animate({
        scrollTop: $('#'+hash).offset().top
    }, 500);
    return false;
});

just add class toscroll to your a tag

Remove duplicates from an array of objects in JavaScript

_x000D_
_x000D_
 const things = [
  {place:"here",name:"stuff"},
  {place:"there",name:"morestuff"},
  {place:"there",name:"morestuff"}
];
const filteredArr = things.reduce((thing, current) => {
  const x = thing.find(item => item.place === current.place);
  if (!x) {
    return thing.concat([current]);
  } else {
    return thing;
  }
}, []);
console.log(filteredArr)
_x000D_
_x000D_
_x000D_

Solution Via Set Object | According to the data type

_x000D_
_x000D_
const seen = new Set();
 const things = [
  {place:"here",name:"stuff"},
  {place:"there",name:"morestuff"},
  {place:"there",name:"morestuff"}
];

const filteredArr = things.filter(el => {
  const duplicate = seen.has(el.place);
  seen.add(el.place);
  return !duplicate;
});
console.log(filteredArr)
_x000D_
_x000D_
_x000D_

Set Object Feature

Each value in the Set Object has to be unique, the value equality will be checked

The Purpose of Set object storing unique values according to the Data type , whether primitive values or object references.it has very useful four Instance methods add, clear , has & delete.

Unique & data Type feature:..

addmethod

it's push unique data into collection by default also preserve data type .. that means it prevent to push duplicate item into collection also it will check data type by default...

has method

sometime needs to check data item exist into the collection and . it's handy method for the collection to cheek unique id or item and data type..

delete method

it will remove specific item from the collection by identifying data type..

clear method

it will remove all collection items from one specific variable and set as empty object

Set object has also Iteration methods & more feature..

Better Read from Here : Set - JavaScript | MDN

EF Migrations: Rollback last applied migration?

In case there is a possibility for dataloss EF does not complete the update-database command since AutomaticMigrationDataLossAllowed = false by default, and roolbacks the action unless you run it with the -force parameter.

Update-Database –TargetMigration:"Your migration name" -force

or

Update-Database –TargetMigration:Your_Migration_Index -force

Is there a link to the "latest" jQuery library on Google APIs?

Not for nothing, but you shouldn't just automatically use the latest library. If they release the newest library tomorrow and it breaks some of your scripts, you are SOL, but if you use the library you used to develop the scripts, you will ensure they will work.

What is the reason behind "non-static method cannot be referenced from a static context"?

You can't call something that doesn't exist. Since you haven't created an object, the non-static method doesn't exist yet. A static method (by definition) always exists.

Custom style to jquery ui dialogs

The solution only solves part of the problem, it may let you style the container and contents but doesn't let you change the titlebar. I developed a workaround of sorts but adding an id to the dialog div, then using jQuery .prev to change the style of the div which is the previous sibling of the dialog's div. This works because when jQueryUI creates the dialog, your original div becomes a sibling of the new container, but the title div is a the immediately previous sibling to your original div but neither the container not the title div has an id to simplify selecting the div.

HTML

<button id="dialog1" class="btn btn-danger">Warning</button>
<div title="Nothing here, really" id="nonmodal1">
  Nothing here
</div>

You can use CSS to style the main section of the dialog but not the title

.custom-ui-widget-header-warning {
  background: #EBCCCC;
  font-size: 1em;
}

You need some JS to style the title

$(function() {
                   $("#nonmodal1").dialog({
                     minWidth: 400,
                     minHeight: 'auto',
                     autoOpen: false,
                     dialogClass: 'custom-ui-widget-header-warning',
                     position: {
                       my: 'center',
                       at: 'left'
                     }
                   });

                   $("#dialog1").click(function() {
                     if ($("#nonmodal1").dialog("isOpen") === true) {
                       $("#nonmodal1").dialog("close");
                     } else {
                       $("#nonmodal1").dialog("open").prev().css('background','#D9534F');

                     }
                   });
    });

The example only shows simple styling (background) but you can make it as complex as you wish.

You can see it in action here:

http://codepen.io/chris-hore/pen/OVMPay

Split String by delimiter position using oracle SQL

You want to use regexp_substr() for this. This should work for your example:

select regexp_substr(val, '[^/]+/[^/]+', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

Here, by the way, is the SQL Fiddle.

Oops. I missed the part of the question where it says the last delimiter. For that, we can use regex_replace() for the first part:

select regexp_replace(val, '/[^/]+$', '', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

And here is this corresponding SQL Fiddle.

How do I calculate tables size in Oracle

First off, I would generally caution that gathering table statistics in order to do space analysis is a potentially dangerous thing to do. Gathering statistics may change query plans, particularly if the DBA has configured a statistics gathering job that uses non-default parameters that your call is not using, and will cause Oracle to re-parse queries that utilize the table in question which can be a performance hit. If the DBA has intentionally left some tables without statistics (common if your OPTIMIZER_MODE is CHOOSE), gathering statistics can cause Oracle to stop using the rule-based optimizer and start using the cost-based optimizer for a set of queries which can be a major performance headache if it is done unexpectedly in production. If your statistics are accurate, you can query USER_TABLES (or ALL_TABLES or DBA_TABLES) directly without calling GATHER_TABLE_STATS. If your statistics are not accurate, there is probably a reason for that and you don't want to disturb the status quo.

Second, the closest equivalent to the SQL Server sp_spaceused procedure is likely Oracle's DBMS_SPACE package. Tom Kyte has a nice show_space procedure that provides a simple interface to this package and prints out information similar to what sp_spaceused prints out.

How to specify "does not contain" in dplyr filter

Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)

double free or corruption (!prev) error in c program

1 - Your malloc() is wrong.
2 - You are overstepping the bounds of the allocated memory
3 - You should initialize your allocated memory

Here is the program with all the changes needed. I compiled and ran... no errors or warnings.

#include <stdio.h>
#include <stdlib.h> //malloc
#include <math.h>  //sine
#include <string.h>

#define TIME 255
#define HARM 32

int main (void) {
    double sineRads;
    double sine;
    int tcount = 0;
    int hcount = 0;
    /* allocate some heap memory for the large array of waveform data */
    double *ptr = malloc(sizeof(double) * TIME);
     //memset( ptr, 0x00, sizeof(double) * TIME);  may not always set double to 0
    for( tcount = 0; tcount < TIME; tcount++ )
    {
         ptr[tcount] = 0; 
    }

    tcount = 0;
    if (NULL == ptr) {
        printf("ERROR: couldn't allocate waveform memory!\n");
    } else {
        /*evaluate and add harmonic amplitudes for each time step */
        for(tcount = 0; tcount < TIME; tcount++){
            for(hcount = 0; hcount <= HARM; hcount++){
                sineRads = ((double)tcount / (double)TIME) * (2*M_PI); //angular frequency
                sineRads *= (hcount + 1); //scale frequency by harmonic number
                sine = sin(sineRads); 
                ptr[tcount] += sine; //add to other results for this time step
            }
        }
        free(ptr);
        ptr = NULL;     
    }
    return 0;
}

json_encode() escaping forward slashes

is there a way to disable it?

Yes, you only need to use the JSON_UNESCAPED_SLASHES flag.

!important read before: https://stackoverflow.com/a/10210367/367456 (know what you're dealing with - know your enemy)

json_encode($str, JSON_UNESCAPED_SLASHES);

If you don't have PHP 5.4 at hand, pick one of the many existing functions and modify them to your needs, e.g. http://snippets.dzone.com/posts/show/7487 (archived copy).

Example Demo

<?php
/*
 * Escaping the reverse-solidus character ("/", slash) is optional in JSON.
 *
 * This can be controlled with the JSON_UNESCAPED_SLASHES flag constant in PHP.
 *
 * @link http://stackoverflow.com/a/10210433/367456
 */    

$url = 'http://www.example.com/';

echo json_encode($url), "\n";

echo json_encode($url, JSON_UNESCAPED_SLASHES), "\n";

Example Output:

"http:\/\/www.example.com\/"
"http://www.example.com/"

Rails has_many with alias name

If you use has_many through, and want to alias:

has_many :alias_name, through: model_name, source: initial_name

Find which rows have different values for a given column in Teradata SQL

You can do this using a group by:

select id, addressCode
from t
group by id, addressCode
having min(address) <> max(address)

Another way of writing this may seem clearer, but does not perform as well:

select id, addressCode
from t
group by id, addressCode
having count(distinct address) > 1

How to create a numeric vector of zero length in R

Simply:

x <- vector(mode="numeric", length=0)

How can I switch word wrap on and off in Visual Studio Code?

  • Windows: Ctrl + Shift + press the key "P". Now on the command line, type Toggle Word Wrap and press Enter.
  • Mac: Command + Shift + press the key "P". Now in the command line, type Toggle Word Wrap and press Enter.

What is lexical scope?

IBM defines it as:

The portion of a program or segment unit in which a declaration applies. An identifier declared in a routine is known within that routine and within all nested routines. If a nested routine declares an item with the same name, the outer item is not available in the nested routine.

Example 1:

function x() {
    /*
    Variable 'a' is only available to function 'x' and function 'y'.
    In other words the area defined by 'x' is the lexical scope of
    variable 'a'
    */
    var a = "I am a";

    function y() {
        console.log( a )
    }
    y();

}
// outputs 'I am a'
x();

Example 2:

function x() {

    var a = "I am a";

    function y() {
         /*
         If a nested routine declares an item with the same name,
         the outer item is not available in the nested routine.
         */
        var a = 'I am inner a';
        console.log( a )
    }
    y();

}
// outputs 'I am inner a'
x();

Android: show/hide a view using an animation

First of all get the height of the view yo want to saw and make a boolean to save if the view is showing:

int heigth=0;
boolean showing=false;
LinearLayout layout = (LinearLayout) view.findViewById(R.id.layout);

        proDetailsLL.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                // gets called after layout has been done but before display
                // so we can get the height then hide the view

                proHeight = proDetailsLL.getHeight(); // Ahaha!  Gotcha

                proDetailsLL.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                proDetailsLL.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0));
            }
        });

Then call the method for showing hide the view, and change the value of the boolean:

slideInOutAnimation(showing, heigth, layout);
proShowing = !proShowing;

The method:

/**
     * Method to slide in out the layout
     * 
     * @param isShowing
     *            if the layout is showing
     * @param height
     *            the height to slide
     * @param slideLL
     *            the container to show
     */
private void slideInOutAnimation(boolean isShowing, int height, final LinearLayout slideLL, final ImageView arroIV) {

        if (!isShowing) {
        Animation animIn = new Animation() {
        protected void applyTransformation(float interpolatedTime, Transformation t) {
                    super.applyTransformation(interpolatedTime, t);
        // Do relevant calculations here using the interpolatedTime that runs from 0 to 1
        slideLL.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int) (heigth * interpolatedTime)));

                }
            };
            animIn.setDuration(500);
            slideLL.startAnimation(animIn);
        } else {

            Animation animOut = new Animation() {
                protected void applyTransformation(float interpolatedTime, Transformation t) {
                    super.applyTransformation(interpolatedTime, t);
                    // Do relevant calculations here using the interpolatedTime that runs from 0 to 1


                        slideLL.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                                (int) (heigth * (1 - interpolatedTime))));

                }
            };
            animOut.setDuration(500);
            slideLL.startAnimation(animOut);


        }

    }

Java 8 lambda Void argument

I don't think it is possible, because function definitions do not match in your example.

Your lambda expression is evaluated exactly as

void action() { }

whereas your declaration looks like

Void action(Void v) {
    //must return Void type.
}

as an example, if you have following interface

public interface VoidInterface {
    public Void action(Void v);
}

the only kind of function (while instantiating) that will be compatibile looks like

new VoidInterface() {
    public Void action(Void v) {
        //do something
        return v;
    }
}

and either lack of return statement or argument will give you a compiler error.

Therefore, if you declare a function which takes an argument and returns one, I think it is impossible to convert it to function which does neither of mentioned above.

How do I count occurrence of duplicate items in array

You can also use it with text items array, u will get number of duplicates properly, but PHP shows

Warning: array_count_values(): Can only count STRING and INTEGER values!

$domains = 
array (
  0 => 'i1.wp.com',
  1 => 'i1.wp.com',
  2 => 'i2.wp.com',
  3 => 'i0.wp.com',
  4 => 'i2.wp.com',
  5 => 'i2.wp.com',
  6 => 'i0.wp.com',
  7 => 'i2.wp.com',
  8 => 'i0.wp.com',
  9 => 'i0.wp.com' );

$tmp = array_count_values($domains);
print_r ($tmp);

    array (
      'i1.wp.com' => 2730,
      'i2.wp.com' => 2861,
      'i0.wp.com' => 2807
    )

No newline after div?

Have you considered using span instead of div? It is the in-line version of div.

Insert Update trigger how to determine if insert or update

After a lot of searching I could not find an exact example of a single SQL Server trigger that handles all (3) three conditions of the trigger actions INSERT, UPDATE, and DELETE. I finally found a line of text that talked about the fact that when a DELETE or UPDATE occurs, the common DELETED table will contain a record for these two actions. Based upon that information, I then created a small Action routine which determines why the trigger has been activated. This type of interface is sometimes needed when there is both a common configuration and a specific action to occur on an INSERT vs. UPDATE trigger. In these cases, to create a separate trigger for the UPDATE and the INSERT would become maintenance problem. (i.e. were both triggers updated properly for the necessary common data algorithm fix?)

To that end, I would like to give the following multi-trigger event code snippet for handling INSERT, UPDATE, DELETE in one trigger for an Microsoft SQL Server.

CREATE TRIGGER [dbo].[INSUPDDEL_MyDataTable]
ON [dbo].[MyDataTable] FOR INSERT, UPDATE, DELETE
AS 

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with caller queries SELECT statements.
-- If an update/insert/delete occurs on the main table, the number of records affected
-- should only be based on that table and not what records the triggers may/may not
-- select.
SET NOCOUNT ON;

--
-- Variables Needed for this Trigger
-- 
DECLARE @PACKLIST_ID varchar(15)
DECLARE @LINE_NO smallint
DECLARE @SHIPPED_QTY decimal(14,4)
DECLARE @CUST_ORDER_ID varchar(15)
--
-- Determine if this is an INSERT,UPDATE, or DELETE Action
-- 
DECLARE @Action as char(1)
DECLARE @Count as int
SET @Action = 'I' -- Set Action to 'I'nsert by default.
SELECT @Count = COUNT(*) FROM DELETED
if @Count > 0
    BEGIN
        SET @Action = 'D' -- Set Action to 'D'eleted.
        SELECT @Count = COUNT(*) FROM INSERTED
        IF @Count > 0
            SET @Action = 'U' -- Set Action to 'U'pdated.
    END

if @Action = 'D'
    -- This is a DELETE Record Action
    --
    BEGIN
        SELECT @PACKLIST_ID =[PACKLIST_ID]
                    ,@LINE_NO = [LINE_NO]
        FROM DELETED

        DELETE [dbo].[MyDataTable]
        WHERE [PACKLIST_ID]=@PACKLIST_ID AND [LINE_NO]=@LINE_NO
    END
 Else
    BEGIN
            --
            -- Table INSERTED is common to both the INSERT, UPDATE trigger
            --
            SELECT @PACKLIST_ID =[PACKLIST_ID]
                ,@LINE_NO = [LINE_NO]
                ,@SHIPPED_QTY =[SHIPPED_QTY]
                ,@CUST_ORDER_ID = [CUST_ORDER_ID]
            FROM INSERTED 

         if @Action = 'I'
            -- This is an Insert Record Action
            --
            BEGIN
                INSERT INTO [MyChildTable]
                    (([PACKLIST_ID]
                    ,[LINE_NO]
                    ,[STATUS]
                VALUES
                    (@PACKLIST_ID
                    ,@LINE_NO
                    ,'New Record'
                    )
            END
        else
            -- This is an Update Record Action
            --
            BEGIN
                UPDATE [MyChildTable]
                    SET [PACKLIST_ID] = @PACKLIST_ID
                          ,[LINE_NO] = @LINE_NO
                          ,[STATUS]='Update Record'
                WHERE [PACKLIST_ID]=@PACKLIST_ID AND [LINE_NO]=@LINE_NO
            END
    END   

java.lang.IllegalArgumentException: View not attached to window manager

I had the same problem while using a button to sync a list from the server: 1) I click the button 2) A progress dialog shows up while dowloading the list from server 3) I turn the device to another orientation 4) java.lang.IllegalArgumentException: View not attached to window manager on postExecute() of the AsyncTask during progress.dismiss().

As I tried the fix I figured that even if the problem doesn't occur my list wasn't showing all items.

I figured that what I wanted was for the AsyncTask to finish (and dismiss the dialog) before the activity beign destroyed, so I made the asynctask object an attribute and overrided the onDestroy() method.

If the asynctask takes a lot of time the user maybe will feel that the device is slow, but I think that's the price he pays for trying to change the device orientation while the progress dialog is showing up. And even if it takes some time the app doesn't crash.

private AsyncTask<Boolean, Void, Boolean> atask;

@Override
protected void onDestroy() {
    if (atask!=null)
        try {
            atask.get();
        } catch (InterruptedException e) {
        } catch (ExecutionException e) {
        }
    super.onDestroy();
}