Programs & Examples On #Dllnotfoundexception

0

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

In my case it was wrong content of the file. DLL was downloaded from the web, but content of the DLL was HTML page :D Try to check if it is binary file, if it seems like correct DLL :)

How to fix libeay32.dll was not found error

Download libeay32.dll and ssleay32.dll binary package for 32Bit and 64Bit from http://indy.fulgan.com/SSL/ then put it into executable or System32 directory.

UITableView - scroll to the top

In Swift-3 :

self.tableView.setContentOffset(CGPoint.zero, animated: true)

Python foreach equivalent

While the answers above are valid, if you are iterating over a dict {key:value} it this is the approach I like to use:

for key, value in Dictionary.items():
    print(key, value)

Therefore, if I wanted to do something like stringify all keys and values in my dictionary, I would do this:

stringified_dictionary = {}
for key, value in Dictionary.items():
    stringified_dictionary.update({str(key): str(value)})
return stringified_dictionary

This avoids any mutation issues when applying this type of iteration, which can cause erratic behavior (sometimes) in my experience.

ldap query for group members

The good way to get all the members from a group is to, make the DN of the group as the searchDN and pass the "member" as attribute to get in the search function. All of the members of the group can now be found by going through the attribute values returned by the search. The filter can be made generic like (objectclass=*).

Create a tag in a GitHub repository

For creating git tag you can simply run git tag <tagname> command by replacing with the actual name of the tag. Here is a complete tutorial on the basics of managing git tags: https://www.drupixels.com/blog/git-tags-create-push-remote-checkout-and-much-more

Use a.any() or a.all()

If you take a look at the result of valeur <= 0.6, you can see what’s causing this ambiguity:

>>> valeur <= 0.6
array([ True, False, False, False], dtype=bool)

So the result is another array that has in this case 4 boolean values. Now what should the result be? Should the condition be true when one value is true? Should the condition be true only when all values are true?

That’s exactly what numpy.any and numpy.all do. The former requires at least one true value, the latter requires that all values are true:

>>> np.any(valeur <= 0.6)
True
>>> np.all(valeur <= 0.6)
False

querying WHERE condition to character length?

Sorry, I wasn't sure which SQL platform you're talking about:

In MySQL:

$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");

in MSSQL

$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");

The LENGTH() (MySQL) or LEN() (MSSQL) function will return the length of a string in a column that you can use as a condition in your WHERE clause.

Edit

I know this is really old but thought I'd expand my answer because, as Paulo Bueno rightly pointed out, you're most likely wanting the number of characters as opposed to the number of bytes. Thanks Paulo.

So, for MySQL there's the CHAR_LENGTH(). The following example highlights the difference between LENGTH() an CHAR_LENGTH():

CREATE TABLE words (
    word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;

INSERT INTO words(word) VALUES('??'), ('happy'), ('hayir');

SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;

+--------+-----------+----------------+
| word   | num_bytes | num_characters |
+--------+-----------+----------------+
| ??    |         6 |              2 |
| happy  |         5 |              5 |
| hayir  |         6 |              5 |
+--------+-----------+----------------+

Be careful if you're dealing with multi-byte characters.

Need a query that returns every field that contains a specified letter

There's most likely a more elegant way, but this does find every record with a letter in it, both upper or lower case:

select * from your_table
where UPPER(your_field) like '%A%'
or UPPER(your_field) like '%B%'
or UPPER(your_field) like '%C%'
or UPPER(your_field) like '%D%'
or UPPER(your_field) like '%E%'
or UPPER(your_field) like '%F%'
or UPPER(your_field) like '%G%'
or UPPER(your_field) like '%H%'
or UPPER(your_field) like '%I%'
or UPPER(your_field) like '%J%'
or UPPER(your_field) like '%K%'
or UPPER(your_field) like '%L%'
or UPPER(your_field) like '%M%'
or UPPER(your_field) like '%N%'
or UPPER(your_field) like '%O%'
or UPPER(your_field) like '%P%'
or UPPER(your_field) like '%Q%'
or UPPER(your_field) like '%R%'
or UPPER(your_field) like '%S%'
or UPPER(your_field) like '%T%'
or UPPER(your_field) like '%U%'
or UPPER(your_field) like '%V%'
or UPPER(your_field) like '%W%'
or UPPER(your_field) like '%X%'
or UPPER(your_field) like '%Y%'
or UPPER(your_field) like '%Z%'

Sleep function in ORACLE

If executed within "sqlplus", you can execute a host operating system command "sleep" :

!sleep 1

or

host sleep 1

How to get the squared symbol (²) to display in a string

I create equations with random numbers in VBA and for x squared put in x^2.

I read each square (or textbox) text into a string.

I then read each character in the string in turn and note the location of the ^ ("hats")'s in each.

Say the hats were at positions 4, 8 and 12.

I then "chop out" the first hat - the position of the character to be superscripted is now 4, the position of the other hats is now 7 and 11. I chop out the second hat, the character to superscript is now at 7 and the hat has moved to 10. I chop out the last hat .. the superscript character is now position 10.

I now select each character in turn and change the font to superscript.

Thus I can fill a whole spreadsheet with algebra using ^ and then call a routine to tidy it up.

For big powers like x to the 23 I build x^2^3 and the above routine does it.

Develop Android app using C#

Here is a new one (Note: in Tech Preview stage): http://www.dot42.com

It is basically a Visual Studio add-in that lets you compile your C# code directly to DEX code. This means there is no run-time requirement such as Mono.

Disclosure: I work for this company


UPDATE: all sources are now on https://github.com/dot42

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

JAX-RS implementations automatically support marshalling/unmarshalling of classes based on discoverable JAXB annotations, but because your payload is declared as Object, I think the created JAXBContext misses the Department class and when it's time to marshall it it doesn't know how.

A quick and dirty fix would be to add a XmlSeeAlso annotation to your response class:

@XmlRootElement
@XmlSeeAlso({Department.class})
public class Response implements Serializable {
  ....

or something a little more complicated would be "to enrich" the JAXB context for the Response class by using a ContextResolver:

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

@Provider
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public class ResponseResolver implements ContextResolver<JAXBContext> {
    private JAXBContext ctx;

    public ResponseResolver() {
        try {
            this.ctx = JAXBContext.newInstance(

                        Response.class, 
                        Department.class

                    );
        } catch (JAXBException ex) {
            throw new RuntimeException(ex);
        }
    }

    public JAXBContext getContext(Class<?> type) {
        return (type.equals(Response.class) ? ctx : null);
    }
}

Hashmap holding different data types as values for instance Integer, String and Object

If you don't have Your own Data Class, then you can design your map as follows

Map<Integer, Object> map=new HashMap<Integer, Object>();

Here don't forget to use "instanceof" operator while retrieving the values from MAP.

If you have your own Data class then then you can design your map as follows

Map<Integer, YourClassName> map=new HashMap<Integer, YourClassName>();

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class HashMapTest {
public static void main(String[] args) {
    Map<Integer,Demo> map=new HashMap<Integer, Demo>();
    Demo d1= new Demo(1,"hi",new Date(),1,1);
    Demo d2= new Demo(2,"this",new Date(),2,1);
    Demo d3= new Demo(3,"is",new Date(),3,1);
    Demo d4= new Demo(4,"mytest",new Date(),4,1);
    //adding values to map
    map.put(d1.getKey(), d1);
    map.put(d2.getKey(), d2);
    map.put(d3.getKey(), d3);
    map.put(d4.getKey(), d4);
    //retrieving values from map
    Set<Integer> keySet= map.keySet();
    for(int i:keySet){
        System.out.println(map.get(i));
    }
    //searching key on map
    System.out.println(map.containsKey(d1.getKey()));
    //searching value on map
    System.out.println(map.containsValue(d1));
}

}
class Demo{
    private int key;
    private String message;
    private Date time;
    private int count;
    private int version;

    public Demo(int key,String message, Date time, int count, int version){
        this.key=key;
        this.message = message;
        this.time = time;
        this.count = count;
        this.version = version;
    }
    public String getMessage() {
        return message;
    }
    public Date getTime() {
        return time;
    }
    public int getCount() {
        return count;
    }
    public int getVersion() {
        return version;
    }
    public int getKey() {
        return key;
    }
    @Override
    public String toString() {
        return "Demo [message=" + message + ", time=" + time
                + ", count=" + count + ", version=" + version + "]";
    }

}

Does Python support short-circuiting?

Yes, Python does support Short-circuit evaluation, minimal evaluation, or McCarthy evaluation for Boolean operators. It is used to reduce the number of evaluations for computing the output of boolean expression. Example -

Base Functions

def a(x):
    print('a')
    return x

def b(x):
    print('b')
    return x 

AND

if(a(True) and b(True)):
    print(1,end='\n\n')

if(a(False) and b(True)):
    print(2,end='\n\n') 

AND-OUTPUT

a
b
1

a 

OR

if(a(True) or b(False)):
    print(3,end='\n\n')

if(a(False) or b(True)):
    print(4,end='\n\n') 

OR-OUTPUT

a
3

a
b
4 

SQL Server: Make all UPPER case to Proper Case/Title Case

If you can enable the CLR in SQL Server (requires 2005 or later) then you could create a CLR function that uses the TextInfo.ToTitleCase built-in function which would allow you to create a culture-aware way of doing this in only a few lines of code.

How do you grep a file and get the next 5 lines

Here is a sed solution:

sed '/19:55/{
N
N
N
N
N
s/\n/ /g
}' file.txt

C++: Rounding up to the nearest multiple of a number

Here's my solution based on the OP's suggestion, and the examples given by everyone else. Since most everyone was looking for it to handle negative numbers, this solution does just that, without the use of any special functions, i.e. abs, and the like.

By avoiding the modulus and using division instead, the negative number is a natural result, although it's rounded down. After the rounded down version is calculated, then it does the required math to round up, either in the negative or positive direction.

Also note that no special functions are used to calculate anything, so there is a small speed boost there.

int RoundUp(int n, int multiple)
{
    // prevent divide by 0 by returning n
    if (multiple == 0) return n;

    // calculate the rounded down version
    int roundedDown = n / multiple * multiple;

    // if the rounded version and original are the same, then return the original
    if (roundedDown == n) return n;

    // handle negative number and round up according to the sign
    // NOTE: if n is < 0 then subtract the multiple, otherwise add it
    return (n < 0) ? roundedDown - multiple : roundedDown + multiple;
}

exception.getMessage() output with class name

My guess is that you've got something in method1 which wraps one exception in another, and uses the toString() of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.

Here's a short but complete program which demonstrates RuntimeException.getMessage() behaving correctly:

public class Test {
    public static void main(String[] args) {
        try {
            failingMethod();
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }       

    private static void failingMethod() {
        throw new RuntimeException("Just the message");
    }
}

Output:

Error: Just the message

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

@article = user.articles.build(:title => "MainTitle")
@article.save

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be

lista.sort()

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..


The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:

None[0]

The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

Access key value from Web.config in Razor View-MVC3 ASP.NET

@System.Configuration.ConfigurationManager.AppSettings["myKey"]

How do I get the currently-logged username from a Windows service in .NET?

If you are in a network of users, then the username will be different:

Environment.UserName

Will Display format : 'Username', rather than

System.Security.Principal.WindowsIdentity.GetCurrent().Name

Will Display format : 'NetworkName\Username'

Choose the format you want.

Convert to date format dd/mm/yyyy

<?php
$test1='2010-04-19 18:31:27';
echo date('d/m/Y',strtotime($test1));
?>

try this

How to show the text on a ImageButton?

It is technically possible to put a caption on an ImageButton if you really want to do it. Just put a TextView over the ImageButton using FrameLayout. Just remember to not make the Textview clickable.

Example:

<FrameLayout>
    <ImageButton
        android:id="@+id/button_x"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@null"
        android:scaleType="fitXY"
        android:src="@drawable/button_graphic" >
    </ImageButton>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:clickable="false"
        android:text="TEST TEST" >
    </TextView>
</FrameLayout>

Dropdown using javascript onchange

easy

<script>
jQuery.noConflict()(document).ready(function() {
    $('#hide').css('display','none');
    $('#plano').change(function(){

        if(document.getElementById('plano').value == 1){
            $('#hide').show('slow');    

        }else 
            if(document.getElementById('plano').value == 0){

             $('#hide').hide('slow'); 
        }else
            if(document.getElementById('plano').value == 0){
             $('#hide').css('display','none');  

            }

    });
    $('#plano').change();
});
</script>

this example shows and hides the div if selected in combobox some specific value

text-align: right on <select> or <option>

You could try using the "dir" attribute, but I'm not sure that would produce the desired effect?

<select dir="rtl">
    <option>Foo</option>    
    <option>bar</option>
    <option>to the right</option>
</select>

Demo here: http://jsfiddle.net/fparent/YSJU7/

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

For your needs, use ConcurrentHashMap. It allows concurrent modification of the Map from several threads without the need to block them. Collections.synchronizedMap(map) creates a blocking Map which will degrade performance, albeit ensure consistency (if used properly).

Use the second option if you need to ensure data consistency, and each thread needs to have an up-to-date view of the map. Use the first if performance is critical, and each thread only inserts data to the map, with reads happening less frequently.

Illegal mix of collations MySQL Error

You should set both your table encoding and connection encoding to UTF-8:

ALTER TABLE keywords CHARACTER SET UTF8; -- run once

and

SET NAMES 'UTF8';
SET CHARACTER SET 'UTF8';

stdlib and colored output in C

Because you can't print a character with string formating. You can also think of adding a format with something like this

#define PRINTC(c,f,s) printf ("\033[%dm" f "\033[0m", 30 + c, s)

f is format as in printf

PRINTC (4, "%s\n", "bar")

will print blue bar

PRINTC (1, "%d", 'a')

will print red 97

Select statement to find duplicates on certain fields

To see duplicate values:

with MYCTE  as (
    select row_number() over ( partition by name  order by name) rown, *
    from tmptest  
    ) 
select * from MYCTE where rown <=1

How to "pull" from a local branch into another one?

you have to tell git where to pull from, in this case from the current directory/repository:

git pull . master

but when working locally, you usually just call merge (pull internally calls merge):

git merge master

Cannot bulk load. Operating system error code 5 (Access is denied.)

This is quite simple the way I resolved this problem:

  1. open SQL Server
  2. right click on database (you want to be backup)
  3. select properties
  4. select permissions
  5. select your database role (local or cloud)
  6. in the you bottom you will see explicit permissions table
  7. find " backup database " permission and click Grant permission .

your problem is resolved .

How to change current working directory using a batch file

A simpler syntax might be

pushd %root%

How do I use Wget to download all images into a single folder, from a URL?

wget -nd -r -l 2 -A jpg,jpeg,png,gif http://t.co
  • -nd: no directories (save all files to the current directory; -P directory changes the target directory)
  • -r -l 2: recursive level 2
  • -A: accepted extensions
wget -nd -H -p -A jpg,jpeg,png,gif -e robots=off example.tumblr.com/page/{1..2}
  • -H: span hosts (wget doesn't download files from different domains or subdomains by default)
  • -p: page requisites (includes resources like images on each page)
  • -e robots=off: execute command robotos=off as if it was part of .wgetrc file. This turns off the robot exclusion which means you ignore robots.txt and the robot meta tags (you should know the implications this comes with, take care).

Example: Get all .jpg files from an exemplary directory listing:

$ wget -nd -r -l 1 -A jpg http://example.com/listing/

Installing a local module using npm?

npm pack + package.json

This is what worked for me:

STEP 1: In module project, execute npm pack:

This will build a <package-name>-<version>.tar.gz file.

STEP 2: Move the file to the consumer project

Ideally you can put all such files in a tmp folder in your consumer-project root:

STEP 3: Refer it in your package.json:

"dependencies": {
  "my-package": "file:/./tmp/my-package-1.3.3.tar.gz"
}

STEP 4: Install the packages:

npm install or npm i or yarn

Now, your package would be available in your consumer-project's node_modules folder.

Good Luck...

How to get request URL in Spring Boot RestController

Add a parameter of type UriComponentsBuilder to your controller method. Spring will give you an instance that's preconfigured with the URI for the current request, and you can then customize it (such as by using MvcUriComponentsBuilder.relativeTo to point at a different controller using the same prefix).

How can I convert the "arguments" object to an array in JavaScript?

_x000D_
_x000D_
function sortArgs(...args) {_x000D_
  return args.sort(function (a, b) { return a - b; });_x000D_
}_x000D_
_x000D_
document.body.innerHTML = sortArgs(1, 2, 3, 4).toString();
_x000D_
_x000D_
_x000D_

Difference between numeric, float and decimal in SQL Server

Guidelines from MSDN: Using decimal, float, and real Data

The default maximum precision of numeric and decimal data types is 38. In Transact-SQL, numeric is functionally equivalent to the decimal data type. Use the decimal data type to store numbers with decimals when the data values must be stored exactly as specified.

The behavior of float and real follows the IEEE 754 specification on approximate numeric data types. Because of the approximate nature of the float and real data types, do not use these data types when exact numeric behavior is required, such as in financial applications, in operations involving rounding, or in equality checks. Instead, use the integer, decimal, money, or smallmoney data types. Avoid using float or real columns in WHERE clause search conditions, especially the = and <> operators. It is best to limit float and real columns to > or < comparisons.

Getting date format m-d-Y H:i:s.u from milliseconds

I benched a few different ways:

1) microtime + sscanf + date:

sscanf(microtime(), '0.%6s00 %s', $usec, $sec);
$date = date('Y-m-d H:i:s.', $sec) . $usec;

I'm not sure why microtime() returns 10 chars (0.dddddd00) for the microseconds part but maybe someone can tell me ?

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { sscanf(microtime(), '0.%6s00 %s', $usec, $sec); $date = date('Y-m-d H:i:s.', $sec) . $usec; } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "22372.335910797 ms" // macOS PHP 5.6.30
string(18) "16772.964000702 ms" // Linux PHP 5.4.16
string(18) "10382.229089737 ms" // Linux PHP 7.3.11 (same linux box as above)

2) DateTime::createFromFormat + Datetime->format:

$now = new DateTime('NOW');
$date = $now->format('Y-m-d H:i:s.u');

not working in PHP 5.x ...

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { $now = new DateTime('NOW'); $date = $now->format('Y-m-d H:i:s.u'); } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "45801.825046539 ms" // macOS PHP 5.6.30 (ms not working)
string(18) "21180.155038834 ms" // Linux PHP 5.4.16 (ms not working)
string(18) "11879.796028137 ms" // Linux PHP 7.3.11 (same linux box as above)

3) gettimeofday + date:

$time = gettimeofday();
$date = date('Y-m-d H:i:s.', $time['sec']) . $time['usec'];

-

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { $time = gettimeofday(); $date = date('Y-m-d H:i:s.', $time['sec']) . $time['usec']; } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "23706.788063049 ms" // macOS PHP 5.6.30
string(18) "14984.534025192 ms" // Linux PHP 5.4.16
string(18) "7799.1390228271 ms" // Linux PHP 7.3.11 (same linux box as above)

4) microtime + number_format + DateTime::createFromFormat + DateTime->format:

$now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''));
$date = $now->format('Y-m-d H:i:s.u');

-

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { $now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', '')); $date = $now->format('Y-m-d H:i:s.u'); } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "83326.496124268 ms" // macOS PHP 5.6.30
string(18) "61982.603788376 ms" // Linux PHP 5.4.16
string(16) "19107.1870327 ms" // Linux PHP 7.3.11 (same linux box as above)

5) microtime + sprintf + DateTime::createFromFormat + DateTime->format:

$now = DateTime::createFromFormat('U.u', sprintf('%.6f', microtime(true)));
$date = $now->format('Y-m-d H:i:s.u');

-

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { $now = DateTime::createFromFormat('U.u', sprintf('%.6f', microtime(true))); $date = $now->format('Y-m-d H:i:s.u'); } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "79387.331962585 ms" // macOS PHP 5.6.30
string(18) "60734.437942505 ms" // Linux PHP 5.4.16
string(18) "18594.941139221 ms" // Linux PHP 7.3.11 (same linux box as above)

How to deploy a Java Web Application (.war) on tomcat?

Note that you can deploy remotely using HTTP.

http://localhost:8080/manager/deploy

Upload the web application archive (WAR) file that is specified as the request data in this HTTP PUT request, install it into the appBase directory of our corresponding virtual host, and start it using the war file name without the .war extension as the path. The application can later be undeployed (and the corresponding application directory removed) by use of the /undeploy. To deploy the ROOT web application (the application with a context path of "/"), name the war ROOT.war.

and if you're using Ant you can do this using Tomcat Ant tasks (perhaps following a successful build).

To determine which path you then hit on your browser, you need to know the port Tomcat is running on, the context and your servlet path. See here for more details.

Setting new value for an attribute using jQuery

It is working you have to check attr after assigning value

LiveDemo

$('#amount').attr( 'datamin','1000');

alert($('#amount').attr( 'datamin'));?

What is the shortest function for reading a cookie by name in JavaScript?

To have all cookies accessible by name in a Map:

const cookies = "a=b ; c = d ;e=";
const map = cookies.split(";").map((s) => s.split("=").map((s) => s.trim())).reduce((m, [k, v]) => (m.set(k, v), m), new Map());
console.log(map); //Map(3) {'a' => 'b', 'c' => 'd', 'e' => ''}
map.get("a"); //returns "b"
map.get("c"); //returns "d"
map.get("e"); //returns ""

How can I limit the visible options in an HTML <select> dropdown?

I have made a simple solution for this in ReactJS you can use this in Vanilla Javascript aswell.

Javascript code

//props.options = [{value:'123',label:'123'},{value:'321',label:'321'},{value:'432',label:'432'}];
<div>
<div
  className="new-user-input"
  style={{ marginTop: '10px' }}
  onClick={() => {
    this.setState({
      showOptions: !this.state.showOptions,
    });
  }}
>
  {selectedOption ? (
    <span className="txt-black-600-12">
      {' '}
      {selectedOption.label}{' '}
    </span>
  ) : (
    <span className="txt-grey-500-12">
      Select Option
    </span>
  )}

  //Font awesome icons
  <span className="float-right">
    {this.state.showOptions ? (
      <FaAngleUp />
    ) : (
      <FaAngleDown />
    )}
  </span>
  {this.state.showOptions && (
    <div className="custom-select mt-10">
      {this.props.options.map(ele => {
        return (
          <span
            className="custom-select-option"
            onClick={() => {
              this.setState({
                selectedOption: ele,
                showOptions: false,
              });
            }}
          >
            {ele.label}
          </span>
        );
      })}
    </div>
  )}
</div>
</div>

CSS

.new-user-input {
  border: none;
  background-image: none;
  background-color: #ffffff;

  box-shadow: 0px 1px 5px 1px #d1d1d1;
  outline: none;
  display: block;
  margin: 20px auto;
  padding: 10px;
  width: 90%;
  border-radius: 8px;
}

.new-user-input:focus {
  border: none;
  background-image: none;
  background-color: #ffffff;
  outline: none;
}
    .custom-select{
  display: flex;
    flex-direction: column;
    max-height: 100px;
    overflow: auto;
    flex: 1 0;
}
.custom-select-option{
  padding: 10px 0;
  border-bottom: 1px solid #ececec;
  font-size: 10px;
  font-weight: 500;
  color: #413958;
}

Adding to a vector of pair

Try using another temporary pair:

pair<string,double> temp;
vector<pair<string,double>> revenue;

// Inside the loop
temp.first = "string";
temp.second = map[i].second;
revenue.push_back(temp);

Simple example for Intent and Bundle

For example :

In MainActivity :

Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra(OtherActivity.KEY_EXTRA, yourDataObject);
startActivity(intent);

In OtherActivity :

public static final String KEY_EXTRA = "com.example.yourapp.KEY_BOOK";

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  String yourDataObject = null;

  if (getIntent().hasExtra(KEY_EXTRA)) {
      yourDataObject = getIntent().getStringExtra(KEY_EXTRA);
  } else {
      throw new IllegalArgumentException("Activity cannot find  extras " + KEY_EXTRA);
  }
  // do stuff
}

More informations here : http://developer.android.com/reference/android/content/Intent.html

Copy text from nano editor to shell

For whoever still looking for a copy + paste solution in nano editor

To select text

  • ctrl+6
  • Use arrow to move the cursor to where you want the mark to end

Note: If you want to copy the whole line, no need to mark just move the cursor to the line

To copy:

  • Press alt + 6

To paste:

  • Press ctrl + U

Reference

Pandas sum by groupby, but exclude certain columns

If you are looking for a more generalized way to apply to many columns, what you can do is to build a list of column names and pass it as the index of the grouped dataframe. In your case, for example:

columns = ['Y'+str(i) for year in range(1967, 2011)]

df.groupby('Country')[columns].agg('sum')

How do I lock the orientation to portrait mode in a iPhone Web Application?

I like the idea of telling the user to put his phone back into portrait mode. Like it's mentioned here: http://tech.sarathdr.com/featured/prevent-landscape-orientation-of-iphone-web-apps/ ...but utilising CSS instead of JavaScript.

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

The correct solution that i get is

<html>
      <head>
        <script type="text/javascript" language="JavaScript">
                  function clickedButton()
            {

                window.location = 'new url'

            }
             </script>
      </head>

      <form name="login_form" method="post">
            ..................
            <input type="button" value="Login" onClick="clickedButton()"/>
      </form>
 </html>

Here the new url is given inside the single quote.

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

@XmlRootElement
public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;
}

Then your @POST method would look like the following:

@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);
}

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com

{"param1":"hello","param2":"world"}

Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


HTML <FORM>

The parameters would be annotated using @FormParam:

@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {
    ...
}

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25

param1=hello&param2=world

The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
    ...
}

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {
    ...
}

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.


HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {
    ...
}

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0
Host: www.example.com

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.


HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {
    ...
}

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.


As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

Best way to initialize (empty) array in PHP

$myArray = []; 

Creates empty array.

You can push values onto the array later, like so:

$myArray[] = "tree";
$myArray[] = "house";
$myArray[] = "dog";

At this point, $myArray contains "tree", "house" and "dog". Each of the above commands appends to the array, preserving the items that were already there.

Having come from other languages, this way of appending to an array seemed strange to me. I expected to have to do something like $myArray += "dog" or something... or maybe an "add()" method like Visual Basic collections have. But this direct append syntax certainly is short and convenient.

You actually have to use the unset() function to remove items:

unset($myArray[1]); 

... would remove "house" from the array (arrays are zero-based).

unset($myArray); 

... would destroy the entire array.

To be clear, the empty square brackets syntax for appending to an array is simply a way of telling PHP to assign the indexes to each value automatically, rather than YOU assigning the indexes. Under the covers, PHP is actually doing this:

$myArray[0] = "tree";
$myArray[1] = "house";
$myArray[2] = "dog";

You can assign indexes yourself if you want, and you can use any numbers you want. You can also assign index numbers to some items and not others. If you do that, PHP will fill in the missing index numbers, incrementing from the largest index number assigned as it goes.

So if you do this:

$myArray[10] = "tree";
$myArray[20] = "house";
$myArray[] = "dog";

... the item "dog" will be given an index number of 21. PHP does not do intelligent pattern matching for incremental index assignment, so it won't know that you might have wanted it to assign an index of 30 to "dog". You can use other functions to specify the increment pattern for an array. I won't go into that here, but its all in the PHP docs.

Cheers,

-=Cameron

Creating a blocking Queue<T> in .NET?

This is what I came op for a thread safe bounded blocking queue.

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

public class BlockingBuffer<T>
{
    private Object t_lock;
    private Semaphore sema_NotEmpty;
    private Semaphore sema_NotFull;
    private T[] buf;

    private int getFromIndex;
    private int putToIndex;
    private int size;
    private int numItems;

    public BlockingBuffer(int Capacity)
    {
        if (Capacity <= 0)
            throw new ArgumentOutOfRangeException("Capacity must be larger than 0");

        t_lock = new Object();
        buf = new T[Capacity];
        sema_NotEmpty = new Semaphore(0, Capacity);
        sema_NotFull = new Semaphore(Capacity, Capacity);
        getFromIndex = 0;
        putToIndex = 0;
        size = Capacity;
        numItems = 0;
    }

    public void put(T item)
    {
        sema_NotFull.WaitOne();
        lock (t_lock)
        {
            while (numItems == size)
            {
                Monitor.Pulse(t_lock);
                Monitor.Wait(t_lock);
            }

            buf[putToIndex++] = item;

            if (putToIndex == size)
                putToIndex = 0;

            numItems++;

            Monitor.Pulse(t_lock);

        }
        sema_NotEmpty.Release();


    }

    public T take()
    {
        T item;

        sema_NotEmpty.WaitOne();
        lock (t_lock)
        {

            while (numItems == 0)
            {
                Monitor.Pulse(t_lock);
                Monitor.Wait(t_lock);
            }

            item = buf[getFromIndex++];

            if (getFromIndex == size)
                getFromIndex = 0;

            numItems--;

            Monitor.Pulse(t_lock);

        }
        sema_NotFull.Release();

        return item;
    }
}

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

How do I make a relative reference to another workbook in Excel?

Using =worksheetname() and =Indirect() function, and naming the worksheets in the parent Excel file with the name of the externally referenced Excel file. Each externally referenced excel file were in their own folders with same name. These sub-folders were only to create more clarity.


What I did was as follows:-

|----Column B---------------|----Column C------------|

R2) Parent folder --------> "C:\TEMP\Excel\"

R3) Sub folder name ---> =worksheetname()

R5) Full path --------------> ="'"&C2&C3&"["&C3&".xlsx]Sheet1'!$A$1"

R7) Indirect function-----> =INDIRECT(C5,TRUE)

In the main file, I had say, 5 worksheets labeled as Ext-1, Ext-2, Ext-3, Ext-4, Ext-5. Copy pasted the above formulas into all the five worksheets. Opened all the respectively named Excel files in the background. For some reason the results were not automatically computing, hence had to force a change by editing any cell. Volla, the value in cell A1 of each externally referenced Excel file were in the Main file.

How to get element-wise matrix multiplication (Hadamard product) in numpy?

just do this:

import numpy as np

a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])

a * b

jquery : focus to div is not working

a <div> can be focused if it has a tabindex attribute. (the value can be set to -1)

For example:

$("#focus_point").attr("tabindex",-1).focus();

In addition, consider setting outline: none !important; so it displayed without a focus rectangle.

var element = $("#focus_point");
element.css('outline', 'none !important')
       .attr("tabindex", -1)
       .focus();

How to decorate a class?

No one has explained that you can dynamically define classes. So you can have a decorator that defines (and returns) a subclass:

def addId(cls):

    class AddId(cls):

        def __init__(self, id, *args, **kargs):
            super(AddId, self).__init__(*args, **kargs)
            self.__id = id

        def getId(self):
            return self.__id

    return AddId

Which can be used in Python 2 (the comment from Blckknght which explains why you should continue to do this in 2.6+) like this:

class Foo:
    pass

FooId = addId(Foo)

And in Python 3 like this (but be careful to use super() in your classes):

@addId
class Foo:
    pass

So you can have your cake and eat it - inheritance and decorators!

python: get directory two levels up

(pathlib.Path('../../') ).resolve()

Connection pooling options with JDBC: DBCP vs C3P0

DBCP is out of date and not production grade. Some time back we conducted an in-house analysis of the two, creating a test fixture which generated load and concurrency against the two to assess their suitability under real life conditions.

DBCP consistently generated exceptions into our test application and struggled to reach levels of performance which C3P0 was more than capable of handling without any exceptions.

C3P0 also robustly handled DB disconnects and transparent reconnects on resume whereas DBCP never recovered connections if the link was taken out from beneath it. Worse still DBCP was returning Connection objects to the application for which the underlying transport had broken.

Since then we have used C3P0 in 4 major heavy-load consumer web apps and have never looked back.

UPDATE: It turns out that after many years of sitting on a shelf, the Apache Commons folk have taken DBCP out of dormancy and it is now, once again, an actively developed project. Thus my original post may be out of date.

That being said, I haven't yet experienced this new upgraded library's performance, nor heard of it being de-facto in any recent app framework, yet.

How do I find the width & height of a terminal window?

yes = | head -n$(($(tput lines) * $COLUMNS)) | tr -d '\n'

Customize the Authorization HTTP header

Kindly try below on postman :-

In header section example work for me..

Authorization : JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwiZ2V0dGVycyI6e30sIndhc1BvcHVsYXRlZCI6ZmFsc2UsImFjdGl2ZVBhdGhzIjp7InBhdGhzIjp7InBhc3N3b3JkIjoiaW5pdCIsImVtYWlsIjoiaW5pdCIsIl9fdiI6ImluaXQiLCJfaWQiOiJpbml0In0sInN0YXRlcyI6eyJpZ25vcmUiOnt9LCJkZWZhdWx0Ijp7fSwiaW5pdCI6eyJfX3YiOnRydWUsInBhc3N3b3JkIjp0cnVlLCJlbWFpbCI6dHJ1ZSwiX2lkIjp0cnVlfSwibW9kaWZ5Ijp7fSwicmVxdWlyZSI6e319LCJzdGF0ZU5hbWVzIjpbInJlcXVpcmUiLCJtb2RpZnkiLCJpbml0IiwiZGVmYXVsdCIsImlnbm9yZSJdfSwiZW1pdHRlciI6eyJkb21haW4iOm51bGwsIl9ldmVudHMiOnt9LCJfZXZlbnRzQ291bnQiOjAsIl9tYXhMaXN0ZW5lcnMiOjB9fSwiaXNOZXciOmZhbHNlLCJfZG9jIjp7Il9fdiI6MCwicGFzc3dvcmQiOiIkMmEkMTAkdTAybWNnWHFjWVQvdE41MlkzZ2l3dVROd3ZMWW9ZTlFXejlUcThyaDIwR09IMlhHY3haZWUiLCJlbWFpbCI6Im1hZGFuLmRhbGUxQGdtYWlsLmNvbSIsIl9pZCI6IjU5MjEzYzYyYWM2ODZlMGMyNzI2MjgzMiJ9LCJfcHJlcyI6eyIkX19vcmlnaW5hbF9zYXZlIjpbbnVsbCxudWxsLG51bGxdLCIkX19vcmlnaW5hbF92YWxpZGF0ZSI6W251bGxdLCIkX19vcmlnaW5hbF9yZW1vdmUiOltudWxsXX0sIl9wb3N0cyI6eyIkX19vcmlnaW5hbF9zYXZlIjpbXSwiJF9fb3JpZ2luYWxfdmFsaWRhdGUiOltdLCIkX19vcmlnaW5hbF9yZW1vdmUiOltdfSwiaWF0IjoxNDk1MzUwNzA5LCJleHAiOjE0OTUzNjA3ODl9.BkyB0LjKB4FIsCtnM5FcpcBLvKed_j7rCCxZddwiYnU

Appropriate datatype for holding percent values?

  • Hold as a decimal.
  • Add check constraints if you want to limit the range (e.g. between 0 to 100%; in some cases there may be valid reasons to go beyond 100% or potentially even into the negatives).
  • Treat value 1 as 100%, 0.5 as 50%, etc. This will allow any math operations to function as expected (i.e. as opposed to using value 100 as 100%).
  • Amend precision and scale as required (these are the two values in brackets columnName decimal(precision, scale). Precision says the total number of digits that can be held in the number, scale says how many of those are after the decimal place, so decimal(3,2) is a number which can be represented as #.##; decimal(5,3) would be ##.###.
  • decimal and numeric are essentially the same thing. However decimal is ANSI compliant, so always use that unless told otherwise (e.g. by your company's coding standards).

Example Scenarios

  • For your case (0.00% to 100.00%) you'd want decimal(5,4).
  • For the most common case (0% to 100%) you'd want decimal(3,2).
  • In both of the above, the check constraints would be the same

Example:

if object_id('Demo') is null
create table Demo
    (
        Id bigint not null identity(1,1) constraint pk_Demo primary key
        , Name nvarchar(256) not null constraint uk_Demo unique 
        , SomePercentValue decimal(3,2) constraint chk_Demo_SomePercentValue check (SomePercentValue between 0 and 1)
        , SomePrecisionPercentValue decimal(5,2) constraint chk_Demo_SomePrecisionPercentValue check (SomePrecisionPercentValue between 0 and 1)
    )

Further Reading:

Sort ArrayList of custom Objects by property

Well if you using Java 8 or older version Here is the Best solution.

Collections.sort(studentList, Comparator.comparing(Student::getCgpa).reversed().thenComparing(Student:: getFname).thenComparing(Student::getId));

In this case, it will first sort with 'getCgpa' first and for the second part it will sort with getFname and getId. Which is field into the pojo class.

"Cannot GET /" with Connect on Node.js

The solution to "Cannot Get /" can usually be determined if you do an "ng build" in the command line. You will find most often that one of your "imports" does not have the correct path.

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

I got this error When upgrading Google play services to 9.0 from 7.5

Having error with below one:

compile 'com.google.android.gms:play-services:9.0.0'

When I changed to

compile 'com.google.android.gms:play-services:7.5.0'

There is no error. Try this

Transform DateTime into simple Date in Ruby on Rails

In Ruby 1.9.2 and above they added a .to_date function to DateTime:

http://ruby-doc.org/stdlib-1.9.2/libdoc/date/rdoc/DateTime.html#method-i-to_date

This instance method doesn't appear to be present in earlier versions like 1.8.7.

Do not want scientific notation on plot axis

You can use format or formatC to, ahem, format your axis labels.

For whole numbers, try

x <- 10 ^ (1:10)
format(x, scientific = FALSE)
formatC(x, digits = 0, format = "f")

If the numbers are convertable to actual integers (i.e., not too big), you can also use

formatC(x, format = "d")

How you get the labels onto your axis depends upon the plotting system that you are using.

How can you get the build/version number of your Android application?

package com.sqisland.android.versionview;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView textViewversionName = (TextView) findViewById(R.id.text);

    try {
        PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        textViewversionName.setText(packageInfo.versionName);

    }
    catch (PackageManager.NameNotFoundException e) {

    }
  }
}

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

EDIT: The new Design Support Library supports this and the previous method is no longer required.

This can now be achieved using the new Android Design Support Library.

You can see the Cheesesquare sample app by Chris Banes which demos all the new features.


Previous method:

Since there is no complete solution posted, here is the way I achieved the desired result.

First include a ScrimInsetsFrameLayout in your project.

/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* A layout that draws something in the insets passed to 
* {@link #fitSystemWindows(Rect)}, i.e. the area above UI chrome
* (status and navigation bars, overlay action bars).
*/
public class ScrimInsetsFrameLayout extends FrameLayout {
    private Drawable mInsetForeground;

    private Rect mInsets;
    private Rect mTempRect = new Rect();
    private OnInsetsCallback mOnInsetsCallback;

    public ScrimInsetsFrameLayout(Context context) {
        super(context);
        init(context, null, 0);
    }

    public ScrimInsetsFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public ScrimInsetsFrameLayout(
        Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        final TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.ScrimInsetsView, defStyle, 0);
        if (a == null) {
            return;
        }
        mInsetForeground = a.getDrawable(
            R.styleable.ScrimInsetsView_insetForeground);
        a.recycle();

        setWillNotDraw(true);
    }

    @Override
    protected boolean fitSystemWindows(Rect insets) {
        mInsets = new Rect(insets);
        setWillNotDraw(mInsetForeground == null);
        ViewCompat.postInvalidateOnAnimation(this);
        if (mOnInsetsCallback != null) {
            mOnInsetsCallback.onInsetsChanged(insets);
        }
        return true; // consume insets
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        int width = getWidth();
        int height = getHeight();
        if (mInsets != null && mInsetForeground != null) {
            int sc = canvas.save();
            canvas.translate(getScrollX(), getScrollY());

            // Top
            mTempRect.set(0, 0, width, mInsets.top);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Bottom
            mTempRect.set(0, height - mInsets.bottom, width, height);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Left
            mTempRect.set(
                0, 
                mInsets.top, 
                mInsets.left, 
                height - mInsets.bottom);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Right
            mTempRect.set(
                width - mInsets.right, 
                mInsets.top, width, 
                height - mInsets.bottom);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            canvas.restoreToCount(sc);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (mInsetForeground != null) {
            mInsetForeground.setCallback(this);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mInsetForeground != null) {
            mInsetForeground.setCallback(null);
        }
    }

    /**
     * Allows the calling container to specify a callback for custom 
     * processing when insets change (i.e. when {@link #fitSystemWindows(Rect)}
     * is called. This is useful for setting padding on UI elements 
     * based on UI chrome insets (e.g. a Google Map or a ListView). 
     * When using with ListView or GridView, remember to set
     * clipToPadding to false.
     */
    public void setOnInsetsCallback(OnInsetsCallback onInsetsCallback) {
        mOnInsetsCallback = onInsetsCallback;
    }

    public static interface OnInsetsCallback {
        public void onInsetsChanged(Rect insets);
    }
}

Then create a styleable so that the insetForeground can be set.

values/attrs.xml

<declare-styleable name="ScrimInsetsView">
    <attr name="insetForeground" format="reference|color" />
</declare-styleable>

Update your activity's xml file and make sure android:fitsSystemWindows is set to true on both the DrawerLayout as well as the ScrimInsetsFrameLayout.

layout/activity_main.xml

<android.support.v4.widget.DrawerLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <!-- The main content view -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- Your main content -->

    </LinearLayout>

    <!-- The navigation drawer -->
    <com.example.app.util.ScrimInsetsFrameLayout 
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/scrimInsetsFrameLayout"
        android:layout_width="320dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@color/white"
        android:elevation="10dp"
        android:fitsSystemWindows="true"
        app:insetForeground="#4000">

        <!-- Your drawer content -->

    </com.example.app.util.ScrimInsetsFrameLayout>

</android.support.v4.widget.DrawerLayout>

Inside the onCreate method of your activity set the status bar background color on the drawer layout.

MainActivity.java

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

    // ...

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mDrawerLayout.setStatusBarBackgroundColor(
        getResources().getColor(R.color.primary_dark));
}

Finally update your app's theme so that the DrawerLayout is behind the status bar.

values-v21/styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
</style>

Result:

Capturing a form submit with jquery and .submit

_x000D_
_x000D_
$(document).ready(function () {_x000D_
  var form = $('#login_form')[0];_x000D_
  form.onsubmit = function(e){_x000D_
  var data = $("#login_form :input").serializeArray();_x000D_
  console.log(data);_x000D_
  $.ajax({_x000D_
  url: "the url to post",_x000D_
  data: data,_x000D_
  processData: false,_x000D_
  contentType: false,_x000D_
  type: 'POST',_x000D_
  success: function(data){_x000D_
    alert(data);_x000D_
  },_x000D_
  error: function(xhrRequest, status, error) {_x000D_
    alert(JSON.stringify(xhrRequest));_x000D_
  }_x000D_
});_x000D_
    return false;_x000D_
  }_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Capturing sumit action</title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<form method="POST" id="login_form">_x000D_
    <label>Username:</label>_x000D_
    <input type="text" name="username" id="username"/>_x000D_
    <label>Password:</label>_x000D_
    <input type="password" name="password" id="password"/>_x000D_
    <input type="submit" value="Submit" name="submit" class="submit" id="submit" />_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

JOIN queries vs multiple queries

There are several factors which means there is no binary answer. The question of what is best for performance depends on your environment. By the way, if your single select with an identifier is not sub-second, something may be wrong with your configuration.

The real question to ask is how do you want to access the data. Single selects support late-binding. For example if you only want employee information, you can select from the Employees table. The foreign key relationships can be used to retrieve related resources at a later time and as needed. The selects will already have a key to point to so they should be extremely fast, and you only have to retrieve what you need. Network latency must always be taken into account.

Joins will retrieve all of the data at once. If you are generating a report or populating a grid, this may be exactly what you want. Compiled and optomized joins are simply going to be faster than single selects in this scenario. Remember, Ad-hoc joins may not be as fast--you should compile them (into a stored proc). The speed answer depends on the execution plan, which details exactly what steps the DBMS takes to retrieve the data.

How to save a dictionary to a file?

We can also use the json module in the case when dictionaries or some other data can be easily mapped to JSON format.

import json

# Serialize data into file:
json.dump( data, open( "file_name.json", 'w' ) )

# Read data from file:
data = json.load( open( "file_name.json" ) )

This solution brings many benefits, eg works for Python 2.x and Python 3.x in an unchanged form and in addition, data saved in JSON format can be easily transferred between many different platforms or programs. This data are also human-readable.

What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

As mentioned, you can use:

=Format(Fields!Price.Value, "C")

A digit after the "C" will specify precision:

=Format(Fields!Price.Value, "C0")
=Format(Fields!Price.Value, "C1")

You can also use Excel-style masks like this:

=Format(Fields!Price.Value, "#,##0.00")

Haven't tested the last one, but there's the idea. Also works with dates:

=Format(Fields!Date.Value, "yyyy-MM-dd")

Deny all, allow only one IP through htaccess

ErrorDocument 403 /maintenance.html
Order Allow,Deny
Allow from #:#:#:#:#:#

For me, this seems to work (Using IPv6 rather than IPv4) I don't know if this is different for some websites but for mine this works.

WAITING at sun.misc.Unsafe.park(Native Method)

From the stack trace it's clear that, the ThreadPoolExecutor > Worker thread started and it's waiting for the task to be available on the BlockingQueue(DelayedWorkQueue) to pick the task and execute.So this thread will be in WAIT status only as long as get a SIGNAL from the publisher thread.

SQL Server: combining multiple rows into one row

Using MySQL inbuilt function group_concat() will be a good choice for getting the desired result. The syntax will be -

SELECT group_concat(STRINGVALUE) 
FROM Jira.customfieldvalue
WHERE CUSTOMFIELD = 12534
AND ISSUE = 19602

Before you execute the above command make sure you increase the size of group_concat_max_len else the the whole output may not fit in that cell.

To set the value of group_concat_max_len, execute the below command-

SET group_concat_max_len = 50000;

You can change the value 50000 accordingly, you increase it to a higher value as required.

Get difference between 2 dates in JavaScript?

Here is one way:

_x000D_
_x000D_
const date1 = new Date('7/13/2010');_x000D_
const date2 = new Date('12/15/2010');_x000D_
const diffTime = Math.abs(date2 - date1);_x000D_
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); _x000D_
console.log(diffTime + " milliseconds");_x000D_
console.log(diffDays + " days");
_x000D_
_x000D_
_x000D_

Observe that we need to enclose the date in quotes. The rest of the code gets the time difference in milliseconds and then divides to get the number of days. Date expects mm/dd/yyyy format.

$.widget is not a function

Place your widget.js after core.js, but before any other jquery that calls the widget.js file. (Example: draggable.js) Precedence (order) matters in what javascript/jquery can 'see'. Always position helper code before the code that uses the helper code.

Remove ALL white spaces from text

Using String.prototype.replace with regex, as mentioned in the other answers, is certainly the best solution.

But, just for fun, you can also remove all whitespaces from a text by using String.prototype.split and String.prototype.join:

_x000D_
_x000D_
const text = ' a b    c d e   f g   ';_x000D_
const newText = text.split(/\s/).join('');_x000D_
_x000D_
console.log(newText); // prints abcdefg
_x000D_
_x000D_
_x000D_

Simplest way to read json from a URL in java

I have done the json parser in simplest way, here it is

package com.inzane.shoapp.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
            System.out.println(line);
        }
        is.close();
        json = sb.toString();

    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
        System.out.println("error on parse data in jsonparser.java");
    }

    // return JSON String
    return jObj;

}
}

this class returns the json object from the url

and when you want the json object you just call this class and the method in your Activity class

my code is here

String url = "your url";
JSONParser jsonParser = new JSONParser();
JSONObject object = jsonParser.getJSONFromUrl(url);
String content=object.getString("json key");

here the "json key" is denoted that the key in your json file

this is a simple json file example

{
    "json":"hi"
}

Here "json" is key and "hi" is value

This will get your json value to string content.

How to view the assembly behind the code using Visual C++?

Specify the /FA switch for the cl compiler. Depending on the value of the switch either only assembly code or high-level code and assembly code is integrated. The filename gets .asm file extension. Here are the supported values:


  • /FA Assembly code; .asm
  • /FAc Machine and assembly code; .cod
  • /FAs Source and assembly code; .asm
  • /FAcs Machine, source, and assembly code; .cod

Using sudo with Python script

It works in python 2.7 and 3.8:

from subprocess import Popen, PIPE
from shlex import split

proc = Popen(split('sudo -S %s' % command), bufsize=0, stdout=PIPE, stdin=PIPE, stderr=PIPE)
proc.stdin.write((password +'\n').encode()) # write as bytes
proc.stdin.flush() # need if not bufsize=0 (unbuffered stdin)

without .flush() password will not reach sudo if stdin buffered. In python 2.7 Popen by default used bufsize=0 and stdin.flush() was not needed.

For secure using, create password file in protected directory:

mkdir --mode=700 ~/.prot_dir
nano ~/.prot_dir/passwd.txt
chmod 600 ~/.prot_dir/passwd.txt 

at start your py-script read password from ~/.prot_dir/passwd.txt

with open(os.environ['HOME'] +'/.prot_dir/passwd.txt') as f:
    password = f.readline().rstrip()

How to check whether a int is not null or empty?

int variables can't be null

If a null is to be converted to int, then it is the converter which decides whether to set 0, throw exception, or set another value (like Integer.MIN_VALUE). Try to plug your own converter.

How to find the size of a table in SQL?

Combining the answers from ratty's and Haim's posts (including comments) I've come up with this, which for SQL Server seems to be the most elegant so far:

-- DROP TABLE #tmpTableSizes
CREATE TABLE #tmpTableSizes
(
    tableName varchar(100),
    numberofRows varchar(100),
    reservedSize varchar(50),
    dataSize varchar(50),
    indexSize varchar(50),
    unusedSize varchar(50)
)
insert #tmpTableSizes
EXEC sp_MSforeachtable @command1="EXEC sp_spaceused '?'"


select  * from #tmpTableSizes
order by cast(LEFT(reservedSize, LEN(reservedSize) - 4) as int)  desc

This gives you a list of all your tables in order of reserved size, ordered from largest to smallest.

Removing App ID from Developer Connection

Delete application IDs is allowed. Make sure you deleted all certificates, APNS certs and provisioning profiles associated with your application. Then go to Identitifies --> App IDs, select the application ID, Edit and Delete button should be enabled.

How to define custom configuration variables in rails

I would suggest good approach how to deal with configuration in your application at all. There are three basic rules:

  • change your configuration not a code;
  • use configurations over conditions;
  • write code that means something.

To have more detailed overview follow this link: Rails configuration in the proper way

pandas how to check dtype for all columns in a dataframe?

To go one step further, I assume you want to do something with these dtypes. df.dtypes.to_dict() comes in handy.

my_type = 'float64' #<---

dtypes = dataframe.dtypes.to_dict()

for col_nam, typ in dtypes.items():
    if (typ != my_type): #<---
        raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")

You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype will succeed when .dtype==np.float64.

How do I change the IntelliJ IDEA default JDK?

One other place worth checking: Look in the pom.xml for your project, if you are using Maven compiler plugin, at the source/target config and make sure it is the desired version of Java. I found that I had 1.7 in the following; I changed it to 1.8 and then everything compiled correctly in IntelliJ.

<build>
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <encoding>UTF-8</encoding>
        </configuration>
    </plugin>
</plugins>
</build>

How to convert number to words in java

I tried to make the code more readable. This works for numbers within integer range

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Scanner;

public class Solution2 {

    static Map<Integer, String> numberMap = new HashMap<Integer, String>();
    static Map<Integer, String> tensMap = new HashMap<Integer, String>();
    static Map<Integer, String> exponentsMap = new HashMap<Integer, String>();
    
    public static void main(String[] args) {

        LinkedList<String> wordList = new LinkedList<String>();
        Scanner scan = new Scanner(System.in);
        int input = scan.nextInt();
        scan.close();

        exponentsMap.put(3, "thousand");
        exponentsMap.put(6, "million");
        exponentsMap.put(9, "billion");

        tensMap.put(2, "twenty");
        tensMap.put(3, "thirty");
        tensMap.put(4, "forty");
        tensMap.put(5, "fifty");
        tensMap.put(6, "sixty");
        tensMap.put(7, "seventy");
        tensMap.put(8, "eighty");
        tensMap.put(9, "ninety");

        numberMap.put(1, "one");
        numberMap.put(2, "two");
        numberMap.put(3, "three");
        numberMap.put(4, "four");
        numberMap.put(5, "five");
        numberMap.put(6, "six");
        numberMap.put(7, "seven");
        numberMap.put(8, "eight");
        numberMap.put(9, "nine");
        numberMap.put(10, "ten");
        numberMap.put(11, "eleven");
        numberMap.put(12, "twelve");
        numberMap.put(13, "thirteen");
        numberMap.put(14, "fourteen");
        numberMap.put(15, "fifteen");
        numberMap.put(16, "sixteen");
        numberMap.put(17, "seventeen");
        numberMap.put(18, "eighteen");
        numberMap.put(19, "nineteen");

        int temp = input;
        
        int exponentCounter =0;
        while(temp>0) {
            // words from 1 to 99
            addLastTwo(temp%100,wordList);
            temp=temp/100;
            
            // add hundreds before exponents
            if(temp!=0) {
                wordList.addFirst("hundred");
                wordList.addFirst(numberMap.getOrDefault(temp%10,""));
                temp = temp/10;
            }
            
            // words for exponents
            if(temp!=0) {
                exponentCounter+=3;
                wordList.addFirst(exponentsMap.getOrDefault(exponentCounter,""));
            }
        }
        wordList.stream().filter(word -> !word.contentEquals("")).forEach(word -> System.out.print(word + " "));
    }

    private static void addLastTwo(int num, LinkedList<String> wordList) {
        if (num > 19) {
            wordList.addFirst(numberMap.getOrDefault(num % 10,""));
            wordList.addFirst(tensMap.getOrDefault(num / 10,""));
            
        } else {
            wordList.addFirst(numberMap.getOrDefault(num,""));
        }
    }
}

How to get only numeric column values?

The other answers indicating using IsNumeric in the where clause are correct, as far as they go, but it's important to remember that it returns 1 if the value can be converted to any numeric type. As such, oddities such as "1d3" will make it through the filter.

If you need only values composed of digits, search for that explicitly:

SELECT column1 FROM table WHERE column1 not like '%[^0-9]%'

The above is filtering to reject any column which contains a non-digit character

Note that in any case, you're going to incur a table scan, indexes are useless for this sort of query.

Deserializing a JSON into a JavaScript object

If you paste the string in server-side into the html don't need to do nothing:

For plain java in jsp:

var jsonObj=<%=jsonStringInJavaServlet%>;

For jsp width struts:

var jsonObj=<s:property value="jsonStringInJavaServlet" escape="false" escapeHtml="false"/>;

Get source jar files attached to Eclipse for Maven-managed dependencies

After Setting the Properties either at Project Level or User Properties level, Please do a Maven -> Update Project (Force Update). It downloads the sources

The target principal name is incorrect. Cannot generate SSPI context

Since I landed here when looking for a solution to my own problem, I'll share my solution here, in case others land here as well.

I was connecting fine to SQL Server until my machine was moved to another office on another domain. Then, after the switch, I was getting this error regarding the target principal name. What fixed it was connecting using a fully qualified name such as: server.domain.com. And actually, once I connected to the first server that way, I could connect to other servers using just the server name (without the full qualification), but your mileage may vary.

What are "named tuples" in Python?

I think it's worth adding information about NamedTuples using type hinting:

# dependencies
from typing import NamedTuple, Optional

# definition
class MyNamedTuple(NamedTuple):
    an_attribute: str
    my_attribute: Optional[str] = None
    next_attribute: int = 1

# instantiation
my_named_tuple = MyNamedTuple("abc", "def")
# or more explicitly:
other_tuple = MyNamedTuple(an_attribute="abc", my_attribute="def")

# access
assert "abc" == my_named_tuple.an_attribute
assert 1 == other_tuple.next_attribute

Return index of greatest value in an array

function findIndicesOf(haystack, needle)
{
    var indices = [];

    var j = 0;
    for (var i = 0; i < haystack.length; ++i) {
        if (haystack[i] == needle)
            indices[j++] = i;
    }
    return indices;
}

pass array to haystack and Math.max(...array) to needle. This will give all max elements of the array, and it is more extensible (for example, you also need to find min values)

Binding objects defined in code-behind

That's my way to bind to code behind (see property DataTemplateSelector)

public partial class MainWindow : Window
{
  public MainWindow()
  {
    this.DataTemplateSelector = new MyDataTemplateSelector();

    InitializeComponent();

    // ... more initializations ...
  }

  public DataTemplateSelector DataTemplateSelector { get; }

  // ... more code stuff ...
}

In XAML will referenced by RelativeSource via Ancestors up to containing Window, so I'm at my Window class and use the property via Path declaration:

<GridViewColumn Header="Value(s)"
                CellTemplateSelector="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataTemplateSelector}"/>

Setting of property DataTemplateSelector before call InitializeComponent depends on missing implementation of IPropertyChanged or use of implementation with DependencyProperty so no communication run on change of property DataTemplateSelector.

What is the most efficient way to loop through dataframes with pandas?

I checked out iterrows after noticing Nick Crawford's answer, but found that it yields (index, Series) tuples. Not sure which would work best for you, but I ended up using the itertuples method for my problem, which yields (index, row_value1...) tuples.

There's also iterkv, which iterates through (column, series) tuples.

How to stop a looping thread in Python?

This has been asked before on Stack. See the following links:

Basically you just need to set up the thread with a stop function that sets a sentinel value that the thread will check. In your case, you'll have the something in your loop check the sentinel value to see if it's changed and if it has, the loop can break and the thread can die.

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

It happened for me as well while running a game using and-engine. It was fixed after i added the below code to my manifest.xml. This code should be added to your mainactivity.

android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|mcc|mnc"

Java for loop syntax: "for (T obj : objects)"

yes... This is for each loop in java.

Generally this loop is become useful when you are retrieving data or object from the database.

Syntex :

for(Object obj : Collection obj)
{
     //Code enter code here
}

Example :

for(User user : userList)
{
     System.out.println("USer NAme :" + user.name);
   // etc etc
}

This is for each loop.

it will incremental by automatically. one by one from collection to USer object data has been filled. and working.

How to change JAVA.HOME for Eclipse/ANT

If you are using Eclipse, try the following:

  • Right click on the ant build file, then choose "Properties".
  • Click on the "Run/Debug Settings", then click on the launch configuration file. You should be able to edit it then.
  • After you click "Edit", you should see a new window with a "Properties" tab which will show you a list of Ant build properties. There is a "java.home" property in the list. Make sure it refers to the correct path.

How to create a template function within a class? (C++)

Your guess is the correct one. The only thing you have to remember is that the member function template definition (in addition to the declaration) should be in the header file, not the cpp, though it does not have to be in the body of the class declaration itself.

SVG Positioning

There are two ways to group multiple SVG shapes and position the group:

The first to use <g> with transform attribute as Aaron wrote. But you can't just use a x attribute on the <g> element.

The other way is to use nested <svg> element.

<svg id="parent">
   <svg id="group1" x="10">
      <!-- some shapes -->
   </svg>
</svg>

In this way, the #group1 svg is nested in #parent, and the x=10 is relative to the parent svg. However, you can't use transform attribute on <svg> element, which is quite the contrary of <g> element.

Find number of decimal places in decimal value regardless of culture

Using recursion you can do:

private int GetDecimals(decimal n, int decimals = 0)  
{  
    return n % 1 != 0 ? GetDecimals(n * 10, decimals + 1) : decimals;  
}

Recursive file search using PowerShell

Try this:

Get-ChildItem -Path V:\Myfolder -Filter CopyForbuild.bat -Recurse | Where-Object { $_.Attributes -ne "Directory"}

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

In my case ; what solved my issue was.....

You may had json like this, the keys without " double quotations....

{ name: "test", phone: "2324234" }

So try any online Json Validator to make sure you have right syntax...

Json Validator Online

AngularJS- Login and Authentication in each route and controller

I feel like this way is easiest, but perhaps it's just personal preference.

When you specify your login route (and any other anonymous routes; ex: /register, /logout, /refreshToken, etc.), add:

allowAnonymous: true

So, something like this:

$stateProvider.state('login', {
    url: '/login',
    allowAnonymous: true, //if you move this, don't forget to update
                          //variable path in the force-page check.
    views: {
        root: {
            templateUrl: "app/auth/login/login.html",
            controller: 'LoginCtrl'
        }
    }
    //Any other config
}

You don't ever need to specify "allowAnonymous: false", if not present, it is assumed false, in the check. In an app where most URLs are force authenticated, this is less work. And safer; if you forget to add it to a new URL, the worst that can happen is an anonymous URL is protected. If you do it the other way, specifying "requireAuthentication: true", and you forget to add it to a URL, you are leaking a sensitive page to the public.

Then run this wherever you feel fits your code design best.

//I put it right after the main app module config. I.e. This thing:
angular.module('app', [ /* your dependencies*/ ])
       .config(function (/* you injections */) { /* your config */ })

//Make sure there's no ';' ending the previous line. We're chaining. (or just use a variable)
//
//Then force the logon page
.run(function ($rootScope, $state, $location, User /* My custom session obj */) {
    $rootScope.$on('$stateChangeStart', function(event, newState) {
        if (!User.authenticated && newState.allowAnonymous != true) {
            //Don't use: $state.go('login');
            //Apparently you can't set the $state while in a $state event.
            //It doesn't work properly. So we use the other way.
            $location.path("/login");
        }
    });
});

Simulating Key Press C#

Easy, short and no need window focus:

Also here a usefull list of Virtual Key Codes

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);

        private void button1_Click(object sender, EventArgs e)
        {
            const int WM_SYSKEYDOWN = 0x0104;
            const int VK_F5 = 0x74;

            IntPtr WindowToFind = FindWindow(null, "Google - Mozilla Firefox");

            PostMessage(WindowToFind, WM_SYSKEYDOWN, VK_F5, 0);
        }

Git diff against a stash

I believe git diff <current-branchname>..stash@{0} is the most intuitive way to compare the changes between the local working tree and the most recent stash. Replace stash@{0} with the applicable stash number as needed.

Beware that git diff stash@{0} may produce misleading results. If the two histories of your stash and current branch have diverged, the diff will look like you’re adding all the new stuff in your stash and removing everything unique to the current branch.

answer based on the git book

Also, note that double dot .. and triple dot ... specify different commit comparisons, and I am referring to the double dot for this answer. See the git book for details

How to get the first element of the List or Set?

I'm surprised that nobody suggested guava solution yet:

com.google.common.collect.Iterables.get(collection, 0)
// or
com.google.common.collect.Iterables.get(collection, 0, defaultValue)
// or
com.google.common.collect.Iterables.getFirst(collection, defaultValue)

or if you expect single element:

com.google.common.collect.Iterables.getOnlyElement(collection, defaultValue)
// or
com.google.common.collect.Iterables.getOnlyElement(collection)

Difference between Java SE/EE/ME?

Yes, Java SE is where to start. All the tasks you mention can be handled with it.

Java ME is the Mobile Edition, and EE is Enterprise Edition; these are specialized / extended versions of Standard Edition.

Replacing a fragment with another fragment inside activity group

you can use simple code its work for transaction

Fragment newFragment = new MainCategoryFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame_NavButtom, newFragment);
ft.commit(); 

Getting rid of bullet points from <ul>

The following code

_x000D_
_x000D_
#menu li{
  list-style-type: none;
}
_x000D_
<ul id="menu">
    <li>Root node 1</li>
    <li>Root node 2</li>
</ul>
_x000D_
_x000D_
_x000D_

will produce this output:

output is

Why do I get an error instantiating an interface?

It is what it says, you just cannot instantiate an abstract class. You need to implement it first, then instantiate that class.

IUser user = new User();

How to window.scrollTo() with a smooth effect

$('html, body').animate({scrollTop:1200},'50');

You can do this!

Eclipse HotKey: how to switch between tabs?

If you want to simply switch between your current and your previous tab selections, using CTRL + F6 will switch you back and forth. To navigate to a tab further back in your history, you need to use the UP / DOWN keys while the Editors window is open. This works with Helios (Eclipse 3.6); not sure if this is true for older versions of Eclipse.

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

IntelliJ IDEA does not have an action to add imports. Rather it has the ability to do such as you type. If you enable the "Add unambiguous imports on the fly" in Settings > Editor > General > Auto Import, IntelliJ IDEA will add them as you type without the need for any shortcuts. You can also add classes and packages to exclude from auto importing to make a class you use heavily, that clashes with other classes of the same name, unambiguous.

For classes that are ambiguous (or is you prefer to have the "Add unambiguous imports on the fly" option turned off), just type the name of the class (just the name is OK, no need to fully qualify). Use code completion and select the particular class you want:

enter image description here

Notice the fully qualified names to the right. When I select the one I want and hit enter, IDEA will automatically add the import statement. This works the same if I was typing the name of a constructor. For static methods, you can even just keep typing the method you want. In the following screenshot, no "StringUtils" class is imported yet.

enter image description here

Alternatively, type the class name and then hit Alt+Enter or ?+Enter to "Show intention actions and quick-fixes" and then select the import option.

Although I've never used it, I think the Eclipse Code Formatter third party plug-in will do what you want. It lists "emulates Eclipse's imports optimizing" as a feature. See its instructions for more information. But in the end, I suspect you'll find the built in IDEA features work fine once you get use to their paradigm. In general, IDEA uses a "develop by intentions" concept. So rather than interrupting my development work to add an import statement, I just type the class I want (my intention) and IDEA automatically adds the import statement for the class for me.

Convert month int to month name

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(
    Convert.ToInt32(e.Row.Cells[7].Text.Substring(3,2))).Substring(0,3) 
    + "-" 
    + Convert.ToDateTime(e.Row.Cells[7].Text).ToString("yyyy");

jquery to loop through table rows and cells, where checkob is checked, concatenate

UPDATED

I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/

Also, I've changed two ^= to *=. See http://api.jquery.com/category/selectors/

And note the :checked selector. See http://api.jquery.com/checked-selector/

function createcodes() {

    //run through each row
    $('.authors-list tr').each(function (i, row) {

        // reference all the stuff you need first
        var $row = $(row),
            $family = $row.find('input[name*="family"]'),
            $grade = $row.find('input[name*="grade"]'),
            $checkedBoxes = $row.find('input:checked');

        $checkedBoxes.each(function (i, checkbox) {
            // assuming you layout the elements this way, 
            // we'll take advantage of .next()
            var $checkbox = $(checkbox),
                $line = $checkbox.next(),
                $size = $line.next();

            $line.val(
                $family.val() + ' ' + $size.val() + ', ' + $grade.val()
            );

        });

    });
}

Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials

Rather than WNetUseConnection, I would recommend NetUseAdd. WNetUseConnection is a legacy function that's been superceded by WNetUseConnection2 and WNetUseConnection3, but all of those functions create a network device that's visible in Windows Explorer. NetUseAdd is the equivalent of calling net use in a DOS prompt to authenticate on a remote computer.

If you call NetUseAdd then subsequent attempts to access the directory should succeed.

Way to get all alphabetic chars in an array in PHP?

Lower Case Letters

for ($x = 97; $x < 122; $x++) {
    $y = chr($x);
    echo $y;
    echo "<br>";
}

Upper Case Letters

for ($x = 65; $x < 90; $x++) {
    $y = chr($x);
    echo $y;
    echo "<br>";
}

Difference between using gradlew and gradle

The difference lies in the fact that ./gradlew indicates you are using a gradle wrapper. The wrapper is generally part of a project and it facilitates installation of gradle. If you were using gradle without the wrapper you would have to manually install it - for example, on a mac brew install gradle and then invoke gradle using the gradle command. In both cases you are using gradle, but the former is more convenient and ensures version consistency across different machines.

Each Wrapper is tied to a specific version of Gradle, so when you first run one of the commands above for a given Gradle version, it will download the corresponding Gradle distribution and use it to execute the build.

Not only does this mean that you don’t have to manually install Gradle yourself, but you are also sure to use the version of Gradle that the build is designed for. This makes your historical builds more reliable

Read more here - https://docs.gradle.org/current/userguide/gradle_wrapper.html

Also, Udacity has a neat, high level video explaining the concept of the gradle wrapper - https://www.youtube.com/watch?v=1aA949H-shk

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

Explanation

The error message told us, that the build-time dependency (in this case it is cc1) was not found, so all we need — install the appropriate package to the system (using package manager // from sources // another way)

What is cc1:

cc1 is the internal command which takes preprocessed C-language files and converts them to assembly. It's the actual part that compiles C. For C++, there's cc1plus, and other internal commands for different languages.

taken from this answer by Alan Shutko.

Solution for: Ubuntu / Linux Mint

sudo apt-get update
sudo apt-get install --reinstall build-essential

Solution for: Docker-alpine environment

If you are in docker-alpine environment install the build-base package by adding this to your Dockerfile:

RUN apk add build-base

Better package name provided by Pablo Castellano. More details here.

If you need more packages for building purposes, consider adding of the alpine-sdk package:

RUN apk add alpine-sdk

Taken from github

Solution for: CentOS/Fedora

This answer contains instructions for CentOS and Fedora Linux

Solution for: Amazon Linux

sudo yum install gcc72-c++

Taken from this comment by CoderChris

You could also try to install missed dependencies by this (though, it is said to not to solve the issue):

sudo yum install gcc-c++.noarch

Taken from this answer

Using .htaccess to make all .html pages to run as .php files?

Running .html files as php stopped working all of a sudden in my .htaccess file.

Godaddy support had me change it to:

AddHandler application/x-httpd-lsphp .html

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

According to the official Laravel 7.x documentation, you can solve this quite easily.

Update your /app/Providers/AppServiceProvider.php to contain:

use Illuminate\Support\Facades\Schema;

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Schema::defaultStringLength(191);
}

Alternatively, you may enable the innodb_large_prefix option for your database. Refer to your database's documentation for instructions on how to properly enable this option.

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Ajax.BeginForm looks to be a fail.

Using a regular Html.Begin for, this does the trick just nicely:

$('#detailsform').submit(function(e) {
    e.preventDefault();
    $.post($(this).attr("action"), $(this).serialize(), function(r) {
        $("#edit").html(r);
    });
}); 

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

Plot logarithmic axes with matplotlib in python

if you want to change the base of logarithm, just add:

plt.yscale('log',base=2) 

Before Matplotlib 3.3, you would have to use basex/basey as the bases of log

Oracle 'Partition By' and 'Row_Number' keyword

I often use row_number() as a quick way to discard duplicate records from my select statements. Just add a where clause. Something like...

select a,b,rn 
  from (select a, b, row_number() over (partition by a,b order by a,b) as rn           
          from table) 
 where rn=1;

Django URL Redirect

If you are stuck on django 1.2 like I am and RedirectView doesn't exist, another route-centric way to add the redirect mapping is using:

(r'^match_rules/$', 'django.views.generic.simple.redirect_to', {'url': '/new_url'}),  

You can also re-route everything on a match. This is useful when changing the folder of an app but wanting to preserve bookmarks:

(r'^match_folder/(?P<path>.*)', 'django.views.generic.simple.redirect_to', {'url': '/new_folder/%(path)s'}),  

This is preferable to django.shortcuts.redirect if you are only trying to modify your url routing and do not have access to .htaccess, etc (I'm on Appengine and app.yaml doesn't allow url redirection at that level like an .htaccess).

How can I clear an HTML file input with JavaScript?

This worked for me. const clear = (event) =>{event.target.value = [ ];} clear("input_id");

How to check if a view controller is presented modally or pushed on a navigation stack?

Swift 5. Clean and simple.

if navigationController.presentingViewController != nil {
    // Navigation controller is being presented modally
}

Dump a NumPy array into a csv file

You can use pandas. It does take some extra memory so it's not always possible, but it's very fast and easy to use.

import pandas as pd 
pd.DataFrame(np_array).to_csv("path/to/file.csv")

if you don't want a header or index, use to_csv("/path/to/file.csv", header=None, index=None)

How to use GROUP_CONCAT in a CONCAT in MySQL

 SELECT id, GROUP_CONCAT(CONCAT_WS(':', Name, CAST(Value AS CHAR(7))) SEPARATOR ',') AS result 
    FROM test GROUP BY id

you must use cast or convert, otherwise will be return BLOB

result is

id         Column
1          A:4,A:5,B:8
2          C:9

you have to handle result once again by program such as python or java

How to remove focus from input field in jQuery?

$(':text').attr("disabled", "disabled"); sets all textbox to disabled mode. You can do in another way like giving each textbox id. By doing this code weight will be more and performance issue will be there.

So better have $(':text').attr("disabled", "disabled"); approach.

Import-CSV and Foreach

You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):

Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
   Write-Host $_.IP1
   Write-Host $_.IP2
   ...
}

Install msi with msiexec in a Specific Directory

Use APPLICATIONFOLDER="path" for latest msiexec

Ant build failed: "Target "build..xml" does not exist"

in the folder where the build.xml resides run command only -

ant

and not the command - `

ant build.xml

`

. if you are using the ant file as build xml then the below steps helps you Steps : open cmd Prompt >> switch to the project location >>type ant and click enter key

Java error: Implicit super constructor is undefined for default constructor

For those who Google for this error and arrive here: there might be another reason for receiving it. Eclipse gives this error when you have project setup - system configuration mismatch.

For example, if you import Java 1.7 project to Eclipse and you do not have 1.7 correctly set up then you will get this error. Then you can either go to Project - Preference - Java - Compiler and switch to 1.6 or earlier; or go to Window - Preferences - Java - Installed JREs and add/fix your JRE 1.7 installation.

If REST applications are supposed to be stateless, how do you manage sessions?

REST is stateless and doesn’t maintain any states between the requests. Client cookies / headers are set to maintain the user state like authentication. Say Client username/password are validated by third part authentication mechanism – 2nd level OTP gerneation etc. Once user get authenticated – headers /cookies comes to rest service end point exposed and we can assume user as auth since user is coming with valid headers/cookies. Now certain info of user like IP is either maintained in the cache and after that if request is coming from same Ip (mac address) for listed resources User is allowed. And cache is maintained for some particular time which get invalidated once time lapses. So either cache can be used or DB entries can be used to persist info b/w the requests.

Linux: Which process is causing "device busy" when doing umount?

lsof +f -- /mountpoint

(as lists the processes using files on the mount mounted at /mountpoint. Particularly useful for finding which process(es) are using a mounted USB stick or CD/DVD.

Angular routerLink does not navigate to the corresponding component

For anyone having this error after spliting modules check your routes, the following happened to me:

public-routing.module.ts:

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: '**', redirectTo: 'home' } // ? This was my mistake
    { path: 'home', component: HomeComponent },
    { path: 'privacy-policy', component: PrivacyPolicyComponent },
    { path: 'credits', component: CreditsComponent },
    { path: 'contact', component: ContactComponent },
    { path: 'news', component: NewsComponent },
    { path: 'presentation', component: PresentationComponent }
]

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class PublicRoutingModule { }

app-routing.module.ts:

const routes: Routes = [
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

Move { path: '**', redirectTo: 'home' } to your AppRoutingModule:

public-routing.module.ts:

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'home', component: HomeComponent },
    { path: 'privacy-policy', component: PrivacyPolicyComponent },
    { path: 'credits', component: CreditsComponent },
    { path: 'contact', component: ContactComponent },
    { path: 'news', component: NewsComponent },
    { path: 'presentation', component: PresentationComponent }
]

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class PublicRoutingModule { }

app-routing.module.ts:

const routes: Routes = [
    { path: '**', redirectTo: 'home' }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

How can I disable the UITableView selection?

You just have to put this code into cellForRowAtIndexPath

To disable the cell's selection property:(While tapping the cell).

cell.selectionStyle = UITableViewCellSelectionStyle.None

Java random number with given length

Would that work for you?

public class Main {

public static void main(String[] args) {
    Random r = new Random(System.currentTimeMillis());
    System.out.println(r.nextInt(100000) * 0.000001);
}

}

result e.g. 0.019007

How to select ALL children (in any level) from a parent in jQuery?

It seems that the original test case is wrong.

I can confirm that the selector #my_parent_element * works with unbind().

Let's take the following html as an example:

<div id="#my_parent_element">
  <div class="div1">
    <div class="div2">hello</div>
    <div class="div3">my</div>
  </div>
  <div class="div4">name</div>
  <div class="div5">
    <div class="div6">is</div>
    <div class="div7">
      <div class="div8">marco</div>
      <div class="div9">(try and click on any word)!</div>
    </div>
  </div>
</div>
<button class="unbind">Now, click me and try again</button>

And the jquery bit:

$('.div1,.div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9').click(function() {
  alert('hi!');
})
$('button.unbind').click(function() {
  $('#my_parent_element *').unbind('click');
})

You can try it here: http://jsfiddle.net/fLvwbazk/7/

Calling a function every 60 seconds

A better use of jAndy's answer to implement a polling function that polls every interval seconds, and ends after timeout seconds.

function pollFunc(fn, timeout, interval) {
    var startTime = (new Date()).getTime();
    interval = interval || 1000;

    (function p() {
        fn();
        if (((new Date).getTime() - startTime ) <= timeout)  {
            setTimeout(p, interval);
        }
    })();
}

pollFunc(sendHeartBeat, 60000, 1000);

UPDATE

As per the comment, updating it for the ability of the passed function to stop the polling:

function pollFunc(fn, timeout, interval) {
    var startTime = (new Date()).getTime();
    interval = interval || 1000,
    canPoll = true;

    (function p() {
        canPoll = ((new Date).getTime() - startTime ) <= timeout;
        if (!fn() && canPoll)  { // ensures the function exucutes
            setTimeout(p, interval);
        }
    })();
}

pollFunc(sendHeartBeat, 60000, 1000);

function sendHeartBeat(params) {
    ...
    ...
    if (receivedData) {
        // no need to execute further
        return true; // or false, change the IIFE inside condition accordingly.
    }
}

versionCode vs versionName in Android Manifest

Version Code Represent Version of Your code, android OS check for update by using this variable whether this code is old or new.

Version Name Represent name of version in the format-

(Major).(Minor).(point)

String, used for readable string only, functionally version code has been used by OS.

Running command line silently with VbScript and getting output?

Look for assigning the output to Clipboard (in your first script) and then in second script parse Clipboard value.

IndexError: tuple index out of range ----- Python

A tuple consists of a number of values separated by commas. like

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345

tuple are index based (and also immutable) in Python.

Here in this case x = rows[1][1] + " " + rows[1][2] have only two index 0, 1 available but you are trying to access the 3rd index.

HTTP 1.0 vs 1.1

Proxy support and the Host field:

HTTP 1.1 has a required Host header by spec.

HTTP 1.0 does not officially require a Host header, but it doesn't hurt to add one, and many applications (proxies) expect to see the Host header regardless of the protocol version.

Example:

GET / HTTP/1.1
Host: www.blahblahblahblah.com

This header is useful because it allows you to route a message through proxy servers, and also because your web server can distinguish between different sites on the same server.

So this means if you have blahblahlbah.com and helohelohelo.com both pointing to the same IP. Your web server can use the Host field to distinguish which site the client machine wants.

Persistent connections:

HTTP 1.1 also allows you to have persistent connections which means that you can have more than one request/response on the same HTTP connection.

In HTTP 1.0 you had to open a new connection for each request/response pair. And after each response the connection would be closed. This lead to some big efficiency problems because of TCP Slow Start.

OPTIONS method:

HTTP/1.1 introduces the OPTIONS method. An HTTP client can use this method to determine the abilities of the HTTP server. It's mostly used for Cross Origin Resource Sharing in web applications.

Caching:

HTTP 1.0 had support for caching via the header: If-Modified-Since.

HTTP 1.1 expands on the caching support a lot by using something called 'entity tag'. If 2 resources are the same, then they will have the same entity tags.

HTTP 1.1 also adds the If-Unmodified-Since, If-Match, If-None-Match conditional headers.

There are also further additions relating to caching like the Cache-Control header.

100 Continue status:

There is a new return code in HTTP/1.1 100 Continue. This is to prevent a client from sending a large request when that client is not even sure if the server can process the request, or is authorized to process the request. In this case the client sends only the headers, and the server will tell the client 100 Continue, go ahead with the body.

Much more:

  • Digest authentication and proxy authentication
  • Extra new status codes
  • Chunked transfer encoding
  • Connection header
  • Enhanced compression support
  • Much much more.

How to use S_ISREG() and S_ISDIR() POSIX Macros?

You're using S_ISREG() and S_ISDIR() correctly, you're just using them on the wrong thing.

In your while((dit = readdir(dip)) != NULL) loop in main, you're calling stat on currentPath over and over again without changing currentPath:

if(stat(currentPath, &statbuf) == -1) {
    perror("stat");
    return errno;
}

Shouldn't you be appending a slash and dit->d_name to currentPath to get the full path to the file that you want to stat? Methinks that similar changes to your other stat calls are also needed.

How to display an unordered list in two columns?

Here is an easy way to make a multiple column list using nothing more than simple CSS. The style tags can obviously be put into a CSS if desired.

<p>Materials List</p>
<ul style="display: inline-block; float: left">
    <u>Item Description<u>
    <li>1/2" x 4' wood dowel</li>
    <li>1/2" x 12"  PVC pipe</li>
    <li>1/2" PVC pipe end cap</li>
    <li>7/16" x 3" light duty expansion spring</li>
    <li>6" plastic zip ties</li>
    <li>Light weight antenna</li>
</ul>
<div style="display: inline-block; margin-left: 1em">
    <u>Qty</u>
    <div style="text-indent: 0.5em">3</div>
    <div style="text-indent: 0.5em">1</div>
    <div style="text-indent: 0.5em">1</div>
    <div style="text-indent: 0.5em">2</div>
    <div style="text-indent: 0.5em">8</div>
    <div style="text-indent: 0.5em">1</div>
</div>
<p></p>

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

Java: String - add character n-times

Use this:

String input = "original";
String newStr = "new"; //new string to be added
int n = 10 // no of times we want to add
input = input + new String(new char[n]).replace("\0", newStr);

Limiting Python input strings to certain characters and lengths

We can use assert here.

def _input(inp_str:str):
    try:
        assert len(inp_str)<=15,print('More than 15 characters present')
        assert all('a'<=i<='z' for i in inp_str),print('Characters other than "a"-"z" are found')
        return inp_str
    except Exception as e:
        pass

_input('abcd')
#abcd
_input('abc d')
#Characters other than "a"-"z" are found
_input('abcdefghijklmnopqrst')
#More than 15 characters present

Counting array elements in Python

If you have a multi-dimensional array, len() might not give you the value you are looking for. For instance:

import numpy as np
a = np.arange(10).reshape(2, 5)
print len(a) == 2

This code block will return true, telling you the size of the array is 2. However, there are in fact 10 elements in this 2D array. In the case of multi-dimensional arrays, len() gives you the length of the first dimension of the array i.e.

import numpy as np
len(a) == np.shape(a)[0]

To get the number of elements in a multi-dimensional array of arbitrary shape:

import numpy as np
size = 1
for dim in np.shape(a): size *= dim

Working with $scope.$emit and $scope.$on

You can call a service from your controller that returns a promise and then use it in your controller. And further use $emit or $broadcast to inform other controllers about it. In my case, I had to make http calls through my service, so I did something like this :

function ParentController($scope, testService) {
    testService.getList()
        .then(function(data) {
            $scope.list = testService.list;
        })
        .finally(function() {
            $scope.$emit('listFetched');
        })


    function ChildController($scope, testService) {
        $scope.$on('listFetched', function(event, data) {
            // use the data accordingly
        })
    }

and my service looks like this

    app.service('testService', ['$http', function($http) {

        this.list = [];

        this.getList = function() {
            return $http.get(someUrl)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        list = response.data.results;

                        return response.data;
                    } else {
                        // invalid response
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    // something went wrong
                    return $q.reject(response.data);
                });

        }

    }])

jQuery.each - Getting li elements inside an ul

Given an answer as high voted and views. I did find the answer with mixed of here and other links.

I have a scenario where all patient-related menu is disabled if a patient is not selected. (Refer link - how to disable a li tag using JavaScript)

//css
.disabled{
    pointer-events:none;
    opacity:0.4;
}
// jqvery
$("li a").addClass('disabled');
// remove .disabled when you are done

So rather than write long code, I found an interesting solution via CSS.

_x000D_
_x000D_
$(document).ready(function () {_x000D_
 var PatientId ; _x000D_
 //var PatientId =1;  //remove to test enable i.e. patient selected_x000D_
 if (typeof PatientId == "undefined" || PatientId == "" || PatientId == 0 || PatientId == null) {_x000D_
  console.log(PatientId);_x000D_
  $("#dvHeaderSubMenu a").each(function () {   _x000D_
   $(this).addClass('disabled');_x000D_
  });  _x000D_
  return;_x000D_
 }_x000D_
})
_x000D_
.disabled{_x000D_
    pointer-events:none;_x000D_
    opacity:0.4;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dvHeaderSubMenu">_x000D_
     <ul class="m-nav m-nav--inline pull-right nav-sub">_x000D_
      <li class="m-nav__item">_x000D_
       <a href="#" onclick="console.log('PatientMenu Clicked')" >_x000D_
        <i class="m-nav__link-icon fa fa-tachometer"></i>_x000D_
        Overview_x000D_
       </a>_x000D_
      </li>_x000D_
_x000D_
      <li class="m-nav__item active">_x000D_
       <a href="#" onclick="console.log('PatientMenu Clicked')" >_x000D_
        <i class="m-nav__link-icon fa fa-user"></i>_x000D_
        Personal_x000D_
       </a>_x000D_
      </li>_x000D_
            <li class="m-nav__item m-dropdown m-dropdown--inline m-dropdown--arrow" data-dropdown-toggle="hover">_x000D_
       <a href="#" class="m-dropdown__toggle dropdown-toggle" onclick="console.log('PatientMenu Clicked')">_x000D_
        <i class="m-nav__link-icon flaticon-medical-8"></i>_x000D_
        Insurance Claim_x000D_
       </a>_x000D_
       <div class="m-dropdown__wrapper">_x000D_
        <span class="m-dropdown__arrow m-dropdown__arrow--left"></span>_x000D_
        _x000D_
           <ul class="m-nav">_x000D_
            <li class="m-nav__item">_x000D_
             <a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')" >_x000D_
              <i class="m-nav__link-icon flaticon-toothbrush-1"></i>_x000D_
              <span class="m-nav__link-text">_x000D_
               Primary_x000D_
              </span>_x000D_
             </a>_x000D_
            </li>_x000D_
            <li class="m-nav__item">_x000D_
             <a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">_x000D_
              <i class="m-nav__link-icon flaticon-interface"></i>_x000D_
              <span class="m-nav__link-text">_x000D_
               Secondary_x000D_
              </span>_x000D_
             </a>_x000D_
            </li>_x000D_
            <li class="m-nav__item">_x000D_
             <a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">_x000D_
              <i class="m-nav__link-icon flaticon-healthy"></i>_x000D_
              <span class="m-nav__link-text">_x000D_
               Medical_x000D_
              </span>_x000D_
             </a>_x000D_
            </li>_x000D_
           </ul>_x000D_
          _x000D_
       _x000D_
      </li>_x000D_
     </ul>            _x000D_
</div>
_x000D_
_x000D_
_x000D_

java.text.ParseException: Unparseable date

  • Your formatting pattern fails to match the input string, as noted by other Answers.
  • Your input format is terrible.
  • You are using troublesome old date-time classes that were supplanted years ago by the java.time classes.

ISO 8601

Instead a format such as yours, use ISO 8601 standard formats for exchanging date-time values as text.

The java.time classes use the standard ISO 8601 formats by default when parsing/generating strings.

Proper time zone name

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

Your IST could mean Iceland Standard Time, India Standard Time, Ireland Standard Time, or others. The java.time classes are left to merely guessing, as there is no logical solution to this ambiguity.

java.time

The modern approach uses the java.time classes.

Define a formatting pattern to match your input strings.

String input = "Sat Jun 01 12:53:10 IST 2013";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

zdt.toString(): 2013-06-01T12:53:10Z[Atlantic/Reykjavik]

If your input was not intended for Iceland, you should pre-parse the string to adjust to a proper time zone name. For example, if you are certain the input was intended for India, change IST to Asia/Kolkata.

String input = "Sat Jun 01 12:53:10 IST 2013".replace( "IST" , "Asia/Kolkata" );
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

zdt.toString(): 2013-06-01T12:53:10+05:30[Asia/Kolkata]


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Mapping many-to-many association table with extra column(s)

As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.

For instance, the implementation code of the extra class should look like that:

@Entity
@Table(name = "USER_SERVICES")
public class UserService{

    // example of auto-generated ID
    @Id
    @Column(name = "USER_SERVICES_ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long userServiceID;



    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SERVICE_ID")
    private Service service;



    // example of extra column
    @Column(name="VISIBILITY")    
    private boolean visibility;



    public long getUserServiceID() {
        return userServiceID;
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Service getService() {
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }

    public boolean getVisibility() {
        return visibility;
    }

    public void setVisibility(boolean visibility) {
        this.visibility = visibility;
    }

}

Syncing Android Studio project with Gradle files

I've had this problem after installing the genymotion (another android amulator) plugin. A closer inspection reveled that gradle needs SDK tools version 19.1.0 in order to run (I had 19.0.3 previously).

To fix it, I had to edit build.gradle and under android I changed to: buildToolsVersion 19.1.0

Then I had to rebuild again, and the error was gone.

ASP.NET MVC Dropdown List From SelectList

Try this, just an example:

u.UserTypeOptions = new SelectList(new[]
    {
        new { ID="1", Name="name1" },
        new { ID="2", Name="name2" },
        new { ID="3", Name="name3" },
    }, "ID", "Name", 1);

Or

u.UserTypeOptions = new SelectList(new List<SelectListItem>
    {
        new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
        new SelectListItem { Selected = false, Text = "Homeowner", Value = "2"},
        new SelectListItem { Selected = false, Text = "Contractor", Value = "3"},
    },"Value","Text");

How to select all instances of a variable and edit variable name in Sublime

The Magic is, you have to start with an empty selection, so put your cursor in front of the word/character you want to multi-select and press Ctrl+D .

Black transparent overlay on image hover with only CSS?

.overlay didn't have a height or width and no content, and you can't hover over display:none.

I instead gave the div the same size and position as .image and changes RGBA value on hover.

http://jsfiddle.net/Zf5am/566/

.image { position: absolute; border: 1px solid black; width: 200px; height: 200px; z-index:1;}
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; background:rgba(255,0,0,0); z-index: 200; width:200px; height:200px; }
.overlay:hover { background:rgba(255,0,0,.7); }

how to use javascript Object.defineProperty

_x000D_
_x000D_
Object.defineProperty(Array.prototype, "last", {_x000D_
  get: function() {_x000D_
    if (this[this.length -1] == undefined) { return [] }_x000D_
    else { return this[this.length -1] }_x000D_
  }_x000D_
});_x000D_
_x000D_
console.log([1,2,3,4].last) //returns 4
_x000D_
_x000D_
_x000D_

Safest way to run BAT file from Powershell script

To run the .bat, and have access to the last exit code, run it as:

 & .\my-app\my-fle.bat

How to set recurring schedule for xlsm file using Windows Task Scheduler

Better to use a as you indicated

  1. Create a simple vbs, which is a text file with a .vbs extension (see sample code below)
  2. Use the Task Scheduler to run the vbs
  3. Use the vbs to open the workbook at the scheduled time and then either:
    • use the Private Sub Workbook_Open() event in the ThisWorkbook module to run code when the file is opened
    • more robustly (as macros may be disabled on open), use Application.Run in the vbs to run the macro

See this example of the later approach at Running Excel on Windows Task Scheduler

sample vbs

Dim ObjExcel, ObjWB
Set ObjExcel = CreateObject("excel.application")
'vbs opens a file specified by the path below
Set ObjWB = ObjExcel.Workbooks.Open("C:\temp\rod.xlsm")
'either use the Workbook Open event (if macros are enabled), or Application.Run

ObjWB.Close False
ObjExcel.Quit
Set ObjExcel = Nothing

Best way to do multiple constructors in PHP

Call constructors by data type:

class A 
{ 
    function __construct($argument)
    { 
       $type = gettype($argument);

       if($type == 'unknown type')
       {
            // type unknown
       }

       $this->{'__construct_'.$type}($argument);
    } 

    function __construct_boolean($argument) 
    { 
        // do something
    }
    function __construct_integer($argument) 
    { 
        // do something
    }
    function __construct_double($argument) 
    { 
        // do something
    }
    function __construct_string($argument) 
    { 
        // do something
    }
    function __construct_array($argument) 
    { 
        // do something
    }
    function __construct_object($argument) 
    { 
        // do something
    }
    function __construct_resource($argument) 
    { 
        // do something
    }

    // other functions

} 

Why is datetime.strptime not working in this simple example?

If in the folder with your project you created a file with the name "datetime.py"

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

Try executing this SQL command:

> grant all privileges 
  on YOUR_DATABASE.* 
  to 'asdfsdf'@'localhost' 
  identified by 'your_password';
> flush privileges; 

It seems that you are having issues with connecting to the database and not writing to the folder you’re mentioning.

Also, make sure you have granted FILE to user 'asdfsdf'@'localhost'.

> GRANT FILE ON *.* TO 'asdfsdf'@'localhost';

Getting windbg without the whole WDK?

If you're on Windows 7 x64, the solution provided by Sukesh doesn't work.

I managed to install the debugging tools by downloading the Windows SDK installer for Windows 8 (here), and then choosing "Debugging Tools for Windows" in the installer:

screenshot

PHP - check if variable is undefined

if(isset($variable)){
    $isTouch = $variable;
}

OR

if(!isset($variable)){
    $isTouch = "";// 
}

How to ignore conflicts in rpm installs

The --force option will reinstall already installed packages or overwrite already installed files from other packages. You don't want this normally.

If you tell rpm to install all RPMs from some directory, then it does exactly this. rpm will not ignore RPMs listed for installation. You must manually remove the unneeded RPMs from the list (or directory). It will always overwrite the files with the "latest RPM installed" whichever order you do it in.

You can remove the old RPM and rpm will resolve the dependency with the newer version of the installed RPM. But this will only work, if none of the to be installed RPMs depends exactly on the old version.

If you really need different versions of the same RPM, then the RPM must be relocatable. You can then tell rpm to install the specific RPM to a different directory. If the files are not conflicting, then you can just install different versions with rpm -i (zypper in can not install different versions of the same RPM). I am packaging for example ruby gems as relocatable RPMs at work. So I can have different versions of the same gem installed.

I don't know on which files your RPMs are conflicting, but if all of them are "just" man pages, then you probably can simply overwrite the new ones with the old ones with rpm -i --replacefiles. The only problem with this would be, that it could confuse somebody who is reading the old man page and thinks it is for the actual version. Another problem would be the rpm --verify command. It will complain for the new package if the old one has overwritten some files.

Is this possibly a duplicate of https://serverfault.com/questions/522525/rpm-ignore-conflicts?

CSS display:table-row does not expand when width is set to 100%

give on .view-type class float:left; or delete the float:right; of .view-name

edit: Wrap your div <div class="view-row"> with another div for example <div class="table">

and set the following css :

.table {
    display:table;
    width:100%;}

You have to use the table structure for correct results.

Why is this printing 'None' in the output?

Because there are two print statements. First is inside function and second is outside function. When function not return any thing that time it return None value.

Use return statement at end of function to return value.

e.g.:

Return None value.

>>> def test1():
...    print "In function."
... 
>>> a = test1()
In function.
>>> print a
None
>>> 
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>> 

Use return statement

>>> def test():
...   return "ACV"
... 
>>> print test()
ACV
>>> 
>>> a = test()
>>> print a
ACV
>>> 

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

That's called SQL INJECTION. The ' tries to open/close a string in your mysql query. You should always escape any string that gets into your queries.

for example,

instead of this:

"VALUES ('$sender_id') "

do this:

"VALUES ('". mysql_real_escape_string($sender_id)  ."') "

(or equivalent, of course)

However, it's better to automate this, using PDO, named parameters, prepared statements or many other ways. Research about this and SQL Injection (here you have some techniques).

Hope it helps. Cheers

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

The Clear method is defined as

    public void Clear() { 
        Text = null;
    } 

The Text property's setter starts with

        set { 
            if (value == null) { 
                value = "";
            } 

I assume this answers your question.

How to get the caller class in Java

StackTrace

This Highly depends on what you are looking for... But this should get the class and method that called this method within this object directly.

  • index 0 = Thread
  • index 1 = this
  • index 2 = direct caller, can be self.
  • index 3 ... n = classes and methods that called each other to get to the index 2 and below.

For Class/Method/File name:

Thread.currentThread().getStackTrace()[2].getClassName();
Thread.currentThread().getStackTrace()[2].getMethodName();
Thread.currentThread().getStackTrace()[2].getFileName();

For Class:

Class.forName(Thread.currentThread().getStackTrace()[2].getClassName())

FYI: Class.forName() throws a ClassNotFoundException which is NOT runtime. Youll need try catch.

Also, if you are looking to ignore the calls within the class itself, you have to add some looping with logic to check for that particular thing.

Something like... (I have not tested this piece of code so beware)

StackTraceElement[] stes = Thread.currentThread().getStackTrace();
for(int i=2;i<stes.length;i++)
  if(!stes[i].getClassName().equals(this.getClass().getName()))
    return stes[i].getClassName();

StackWalker

StackWalker StackFrame

Note that this is not an extensive guide but an example of the possibility.

Prints the Class of each StackFrame (by grabbing the Class reference)

StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE)
    .forEach(frame -> System.out.println(frame.getDeclaringClass()));

Does the same thing but first collects the stream into a List. Just for demonstration purposes.

StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE)
    .walk(stream -> stream.collect(Collectors.toList()))
    .forEach(frame -> System.out.println(frame.getDeclaringClass()));

How to copy data from another workbook (excel)?

I don't think you need to select anything at all. I opened two blank workbooks Book1 and Book2, put the value "A" in Range("A1") of Sheet1 in Book2, and submitted the following code in the immediate window -

Workbooks(2).Worksheets(1).Range("A1").Copy Workbooks(1).Worksheets(1).Range("A1")

The Range("A1") in Sheet1 of Book1 now contains "A".

Also, given the fact that in your code you are trying to copy from the ActiveWorkbook to "myfile.xls", the order seems to be reversed as the Copy method should be applied to a range in the ActiveWorkbook, and the destination (argument to the Copy function) should be the appropriate range in "myfile.xls".

How to load a text file into a Hive table stored as sequence files

You can load the text file into a textfile Hive table and then insert the data from this table into your sequencefile.

Start with a tab delimited file:

% cat /tmp/input.txt
a       b
a2      b2

create a sequence file

hive> create table test_sq(k string, v string) stored as sequencefile;

try to load; as expected, this will fail:

hive> load data local inpath '/tmp/input.txt' into table test_sq;

But with this table:

hive> create table test_t(k string, v string) row format delimited fields terminated by '\t' stored as textfile;

The load works just fine:

hive> load data local inpath '/tmp/input.txt' into table test_t;
OK
hive> select * from test_t;
OK
a       b
a2      b2

Now load into the sequence table from the text table:

insert into table test_sq select * from test_t;

Can also do load/insert with overwrite to replace all.

How to access Anaconda command prompt in Windows 10 (64-bit)

To create Anaconda Prompt using Command Prompt, just create a shortcut file of Command Prompt and modify the shortcut target to:

%windir%\System32\cmd.exe "/K" <Anaconda Location>\anaconda3\Scripts\activate.bat

Example:

%windir%\system32\cmd.exe "/K" C:\Users\user_1\AppData\Local\Continuum\anaconda3\Scripts\activate.bat

saving a file (from stream) to disk using c#

If you are using .NET 4.0 or newer you can use this method:

public static void CopyStream(Stream input, Stream output)
{
    input.CopyTo(output);
}

If not, use this one:

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[8 * 1024];
    int len;
    while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, len);
    }    
}

And here how to use it:

using (FileStream output = File.OpenWrite(path))
{
    CopyStream(input, output);
}

Determine the process pid listening on a certain port

on windows, the netstat option to get the pid's is -o and -p selects a protocol filter, ex.: netstat -a -p tcp -o

Is there a common Java utility to break a list into batches?

Using various cheats from the web, I came to this solution:

int[] count = new int[1];
final int CHUNK_SIZE = 500;
Map<Integer, List<Long>> chunkedUsers = users.stream().collect( Collectors.groupingBy( 
    user -> {
        count[0]++;
        return Math.floorDiv( count[0], CHUNK_SIZE );
    } )
);

We use count to mimic a normal collection index.
Then, we group the collection elements in buckets, using the algebraic quotient as bucket number.
The final map contains as key the bucket number, as value the bucket itself.

You can then easily do an operation on each of the buckets with:

chunkedUsers.values().forEach( ... );

While loop to test if a file exists in bash

I had the same problem, put the ! outside the brackets;

while ! [ -f /tmp/list.txt ];
do
    echo "#"
    sleep 1
done

Also, if you add an echo inside the loop it will tell you if you are getting into the loop or not.

Sound alarm when code finishes

I'm assuming you want the standard system bell, and don't want to concern yourself with frequencies and durations etc., you just want the standard windows bell.

import winsound
winsound.MessageBeep()

python numpy vector math

You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.

As I mentioned in the comment, having to use the dot() function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.

Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @ infix-operator for matrix multiplication, thanks to pep 465.

Edit: Regarding your comment:

  1. Yes. The whole of numpy is based on arrays.

  2. Yes. linalg.norm(v) is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.

  3. To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.

    An example in ipython:

    In [1]: import math
    
    In [2]: import numpy as np
    
    In [3]: a = np.array([4,2,7])
    
    In [4]: np.linalg.norm(a)
    Out[4]: 8.3066238629180749
    
    In [5]: math.sqrt(sum([n**2 for n in a]))
    Out[5]: 8.306623862918075
    
    In [6]: b = a/np.linalg.norm(a)
    
    In [7]: np.linalg.norm(b)
    Out[7]: 1.0
    

    Note that In [5] is an alternative way to calculate the length. In [6] shows normalizing the vector.

Java: Local variable mi defined in an enclosing scope must be final or effectively final

What you have here is a non-local variable (https://en.wikipedia.org/wiki/Non-local_variable), i.e. you access a local variable in a method an anonymous class.

Local variables of the method are kept on the stack and lost as soon as the method ends, however even after the method ends, the local inner class object is still alive on the heap and will need to access this variable (here, when an action is performed).

I would suggest two workarounds : Either you make your own class that implements actionlistenner and takes as constructor argument, your variable and keeps it as an class attribute. Therefore you would only access this variable within the same object.

Or (and this is probably the best solution) just qualify a copy of the variable final to access it in the inner scope as the error suggests to make it a constant:

This would suit your case since you are not modifying the value of the variable.

Android - Back button in the title bar

After a quality time I have found, theme option is the main problem in my code And following is the proper way to show the toolbar for me

In AndroidManifest file first you have to change your theme style

Theme.AppCompat.Light.DarkActionBar
to 
Theme.AppCompat.Light.NoActionBar

then at your activity xml you need to call your own Toolbar like

<androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        android:id="@+id/toolbar"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:elevation="4dp"/>

And then this toolbar should be called in your Java file by

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

And for toolbar showing U should check the null to avoid NullPointerException

if(getSupportActionBar() != null){
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

For Home activity back add this

@Override
public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId()==android.R.id.home) {
            finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

OR for your desired activity back

public boolean onOptionsItemSelected(MenuItem item){
    Intent myIntent = new Intent(getApplicationContext(), YourActivity.class);
    startActivityForResult(myIntent, 0);
    return true;
}

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

It is not necessary to stop timer, see nice solution from this post:

"You could let the timer continue firing the callback method but wrap your non-reentrant code in a Monitor.TryEnter/Exit. No need to stop/restart the timer in that case; overlapping calls will not acquire the lock and return immediately."

private void CreatorLoop(object state) 
 {
   if (Monitor.TryEnter(lockObject))
   {
     try
     {
       // Work here
     }
     finally
     {
       Monitor.Exit(lockObject);
     }
   }
 }

Is there a way to automatically build the package.json file for Node.js projects

The package.json file is used by npm to learn about your node.js project.

Use npm init to generate package.json files for you!

It comes bundled with npm. Read its documentation here: https://docs.npmjs.com/cli/init

Also, there's an official tool you can use to generate this file programmatically: https://github.com/npm/init-package-json

load scripts asynchronously

Well, x.parentNode returns the HEAD element, so you are inserting the script just before the head tag. Maybe that's the problem.

Try x.parentNode.appendChild() instead.

Calling Non-Static Method In Static Method In Java

Constructor is a special method which in theory is the "only" non-static method called by any static method. else its not allowed.

How to roundup a number to the closest ten?

the second argument in ROUNDUP, eg =ROUNDUP(12345.6789,3) refers to the negative of the base-10 column with that power of 10, that you want rounded up. eg 1000 = 10^3, so to round up to the next highest 1000, use ,-3)

=ROUNDUP(12345.6789,-4) = 20,000
=ROUNDUP(12345.6789,-3) = 13,000
=ROUNDUP(12345.6789,-2) = 12,400
=ROUNDUP(12345.6789,-1) = 12,350
=ROUNDUP(12345.6789,0) = 12,346
=ROUNDUP(12345.6789,1) = 12,345.7
=ROUNDUP(12345.6789,2) = 12,345.68
=ROUNDUP(12345.6789,3) = 12,345.679

So, to answer your question: if your value is in A1, use =ROUNDUP(A1,-1)

Count number of days between two dates

def business_days_between(date1, date2)
  business_days = 0
  date = date2
  while date > date1
   business_days = business_days + 1 unless date.saturday? or date.sunday?
   date = date - 1.day
  end
  business_days
end

Create a global variable in TypeScript

I found a way that works if I use JavaScript combined with TypeScript.

logging.d.ts:

declare var log: log4javascript.Logger;

log-declaration.js:

log = null;

initalize-app.ts

import './log-declaration.js';

// Call stuff to actually setup log.  
// Similar to this:
log = functionToSetupLog();

This puts it in the global scope and TypeScript knows about it. So I can use it in all my files.

NOTE: I think this only works because I have the allowJs TypeScript option set to true.

If someone posts an pure TypeScript solution, I will accept that.