Programs & Examples On #Flymake

Flymake is a minor editing mode for Emacs that performs on-the-fly syntax checks on the contents of your current buffer as you edit it, highlighting errors and warnings against the lines they occur on.

Navigation Drawer (Google+ vs. YouTube)

I know this is an old question but the most up to date answer is to use the Android Support Design library that will make your life easy.

is it possible to get the MAC address for machine using nmap

Just the standard scan will return the MAC.

nmap -sS target

Printing a java map Map<String, Object> - How?

You may use Map.entrySet() method:

for (Map.Entry entry : objectSet.entrySet())
{
    System.out.println("key: " + entry.getKey() + "; value: " + entry.getValue());
}

Where can I find the API KEY for Firebase Cloud Messaging?

Please add new api key from Firebase -> Project Settings -> Cloud Messaging -> Legacy Server Key to the workspace file i.e google-services.json

System.Net.WebException: The operation has timed out

It means what it says. The operation took too long to complete.

BTW, look at WebRequest.Timeout and you'll see that you've set your timeout for 1/5 second.

Java String array: is there a size of method?

array.length

It is actually a final member of the array, not a method.

When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0)

I had a very similar problem, and in my case it worked by doing:

npm clean

This is the nuclear option since it clears every package from the cache as expained here.

How to make Firefox headless programmatically in Selenium with Python?

Just a note for people who may have found this later (and want java way of achieving this); FirefoxOptions is also capable of enabling the headless mode:

FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setHeadless(true);

How is using OnClickListener interface different via XML and Java code?

using XML, you need to set the onclick listener yourself. First have your class implements OnClickListener then add the variable Button button1; then add this to your onCreate()

button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);

when you implement OnClickListener you need to add the inherited method onClick() where you will handle your clicks

invalid types 'int[int]' for array subscript

You are subscripting a three-dimensional array myArray[10][10][10] four times myArray[i][t][x][y]. You will probably need to add another dimension to your array. Also consider a container like Boost.MultiArray, though that's probably over your head at this point.

How can I define an array of objects?

You can also try

    interface IData{
        id: number;
        name:string;
    }

    let userTestStatus:Record<string,IData> = {
        "0": { "id": 0, "name": "Available" },
        "1": { "id": 1, "name": "Ready" },
        "2": { "id": 2, "name": "Started" }
    };

To check how record works: https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt

Here in our case Record is used to declare an object whose key will be a string and whose value will be of type IData so now it will provide us intellisense when we will try to access its property and will throw type error in case we will try something like userTestStatus[0].nameee

How to undo a SQL Server UPDATE query?

If you can catch this in time and you don't have the ability to ROLLBACK or use the transaction log, you can take a backup immediately and use a tool like Redgate's SQL Data Compare to generate a script to "restore" the affected data. This worked like a charm for me. :)

How do you add input from user into list in Python

code below allows user to input items until they press enter key to stop:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: 

DateTime "null" value

You can set the DateTime to Nullable. By default DateTime is not nullable. You can make it nullable in a couple of ways. Using a question mark after the type DateTime? myTime or using the generic style Nullable.

DateTime? nullDate = null;

or

DateTime? nullDate;

React: "this" is undefined inside a component function

I ran into a similar bind in a render function and ended up passing the context of this in the following way:

{someList.map(function(listItem) {
  // your code
}, this)}

I've also used:

{someList.map((listItem, index) =>
    <div onClick={this.someFunction.bind(this, listItem)} />
)}

Efficiently test if a port is open on Linux?

ss -tl4 '( sport = :22 )'

2ms is quick enough ?

Add the colon and this works on Linux

Count items in a folder with PowerShell

Recursively count files in directories in PowerShell 2.0

ls -rec | ? {$_.mode -match 'd'} | select FullName,  @{N='Count';E={(ls $_.FullName | measure).Count}}

'list' object has no attribute 'shape'

list object in python does not have 'shape' attribute because 'shape' implies that all the columns (or rows) have equal length along certain dimension.

Let's say list variable a has following properties: a = [[2, 3, 4] [0, 1] [87, 8, 1]]

it is impossible to define 'shape' for variable 'a'. That is why 'shape' might be determined only with 'arrays' e.g.

b = numpy.array([[2, 3, 4]
                [0, 1, 22]
                [87, 8, 1]])

I hope this explanation clarifies well this question.

Delete a row from a SQL Server table

Try with paramter

.....................
.....................

    using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + @IDNumber, con))
             {
                   command.Paramter.Add("@IDNumber",IDNumber)
                   command.ExecuteNonQuery();
             }

.....................
.....................

No need to close connection in using statement

Clearing an input text field in Angular2

There are two additional ways to do it apart from the two methods mentioned in @PradeepJain's answer.

I would suggest not to use this approach and to fall back to this only as a last resort if you are not using [(ngModel)] directive and also not using data binding via [value]. Read this for more info.

Using ElementRef

app.component.html

<div>
      <input type="text" #searchInput placeholder="Search...">
      <button (click)="clearSearchInput()">Clear</button>
</div>

app.component.ts

export class App {
  @ViewChild('searchInput') searchInput: ElementRef;

  clearSearchInput(){
     this.searchInput.nativeElement.value = '';
  }
}

Using FormGroup

app.component.html

<form [formGroup]="form">
    <div *ngIf="first.invalid"> Name is too short. </div>
    <input formControlName="first" placeholder="First name">
    <input formControlName="last" placeholder="Last name">
    <button type="submit">Submit</button>
</form>
<button (click)="setValue()">Set preset value</button>
<button (click)="clearInputMethod1()">Clear Input Method 1</button>
<button (click)="clearInputMethod2()">Clear Input Method 2</button>

app.component.ts

export class AppComponent {
  form = new FormGroup({
    first: new FormControl('Nancy', Validators.minLength(2)),
    last: new FormControl('Drew'),
  });
  get first(): any { return this.form.get('first'); }
  get last(): any { return this.form.get('last'); }
  clearInputMethod1() { this.first.reset(); this.last.reset(); }
  clearInputMethod2() { this.form.setValue({first: '', last: ''}); }
  setValue() { this.form.setValue({first: 'Nancy', last: 'Drew'}); }
}

Try it out on stackblitz Clearing input in a FormGroup

How to print to stderr in Python?

For Python 2 my choice is: print >> sys.stderr, 'spam' Because you can simply print lists/dicts etc. without convert it to string. print >> sys.stderr, {'spam': 'spam'} instead of: sys.stderr.write(str({'spam': 'spam'}))

html5 audio player - jquery toggle click play/pause?

You can call native methods trough trigger in jQuery. Just do this:

$('.play').trigger("play");

And the same for pause: $('.play').trigger("pause");

EDIT: as F... pointed out in the comments, you can do something similar to access properties: $('.play').prop("paused");

How is length implemented in Java Arrays?

Java arrays, like C++ arrays, have the fixed length that after initializing it, you cannot change it. But, like class template vector - vector <T> - in C++ you can use Java class ArrayList that has many more utilities than Java arrays have.

How do I efficiently iterate over each entry in a Java Map?

To summarize the other answers and combine them with what I know, I found 10 main ways to do this (see below). Also, I wrote some performance tests (see results below). For example, if we want to find the sum of all of the keys and values of a map, we can write:

  1. Using iterator and Map.Entry

    long i = 0;
    Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<Integer, Integer> pair = it.next();
        i += pair.getKey() + pair.getValue();
    }
    
  2. Using foreach and Map.Entry

    long i = 0;
    for (Map.Entry<Integer, Integer> pair : map.entrySet()) {
        i += pair.getKey() + pair.getValue();
    }
    
  3. Using forEach from Java 8

    final long[] i = {0};
    map.forEach((k, v) -> i[0] += k + v);
    
  4. Using keySet and foreach

    long i = 0;
    for (Integer key : map.keySet()) {
        i += key + map.get(key);
    }
    
  5. Using keySet and iterator

    long i = 0;
    Iterator<Integer> itr2 = map.keySet().iterator();
    while (itr2.hasNext()) {
        Integer key = itr2.next();
        i += key + map.get(key);
    }
    
  6. Using for and Map.Entry

    long i = 0;
    for (Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); entries.hasNext(); ) {
        Map.Entry<Integer, Integer> entry = entries.next();
        i += entry.getKey() + entry.getValue();
    }
    
  7. Using the Java 8 Stream API

    final long[] i = {0};
    map.entrySet().stream().forEach(e -> i[0] += e.getKey() + e.getValue());
    
  8. Using the Java 8 Stream API parallel

    final long[] i = {0};
    map.entrySet().stream().parallel().forEach(e -> i[0] += e.getKey() + e.getValue());
    
  9. Using IterableMap of Apache Collections

    long i = 0;
    MapIterator<Integer, Integer> it = iterableMap.mapIterator();
    while (it.hasNext()) {
        i += it.next() + it.getValue();
    }
    
  10. Using MutableMap of Eclipse (CS) collections

    final long[] i = {0};
    mutableMap.forEachKeyValue((key, value) -> {
        i[0] += key + value;
    });
    

Perfomance tests (mode = AverageTime, system = Windows 8.1 64-bit, Intel i7-4790 3.60 GHz, 16 GB)

  1. For a small map (100 elements), score 0.308 is the best

    Benchmark                          Mode  Cnt  Score    Error  Units
    test3_UsingForEachAndJava8         avgt  10   0.308 ±  0.021  µs/op
    test10_UsingEclipseMap             avgt  10   0.309 ±  0.009  µs/op
    test1_UsingWhileAndMapEntry        avgt  10   0.380 ±  0.014  µs/op
    test6_UsingForAndIterator          avgt  10   0.387 ±  0.016  µs/op
    test2_UsingForEachAndMapEntry      avgt  10   0.391 ±  0.023  µs/op
    test7_UsingJava8StreamApi          avgt  10   0.510 ±  0.014  µs/op
    test9_UsingApacheIterableMap       avgt  10   0.524 ±  0.008  µs/op
    test4_UsingKeySetAndForEach        avgt  10   0.816 ±  0.026  µs/op
    test5_UsingKeySetAndIterator       avgt  10   0.863 ±  0.025  µs/op
    test8_UsingJava8StreamApiParallel  avgt  10   5.552 ±  0.185  µs/op
    
  2. For a map with 10000 elements, score 37.606 is the best

    Benchmark                           Mode   Cnt  Score      Error   Units
    test10_UsingEclipseMap              avgt   10    37.606 ±   0.790  µs/op
    test3_UsingForEachAndJava8          avgt   10    50.368 ±   0.887  µs/op
    test6_UsingForAndIterator           avgt   10    50.332 ±   0.507  µs/op
    test2_UsingForEachAndMapEntry       avgt   10    51.406 ±   1.032  µs/op
    test1_UsingWhileAndMapEntry         avgt   10    52.538 ±   2.431  µs/op
    test7_UsingJava8StreamApi           avgt   10    54.464 ±   0.712  µs/op
    test4_UsingKeySetAndForEach         avgt   10    79.016 ±  25.345  µs/op
    test5_UsingKeySetAndIterator        avgt   10    91.105 ±  10.220  µs/op
    test8_UsingJava8StreamApiParallel   avgt   10   112.511 ±   0.365  µs/op
    test9_UsingApacheIterableMap        avgt   10   125.714 ±   1.935  µs/op
    
  3. For a map with 100000 elements, score 1184.767 is the best

    Benchmark                          Mode   Cnt  Score        Error    Units
    test1_UsingWhileAndMapEntry        avgt   10   1184.767 ±   332.968  µs/op
    test10_UsingEclipseMap             avgt   10   1191.735 ±   304.273  µs/op
    test2_UsingForEachAndMapEntry      avgt   10   1205.815 ±   366.043  µs/op
    test6_UsingForAndIterator          avgt   10   1206.873 ±   367.272  µs/op
    test8_UsingJava8StreamApiParallel  avgt   10   1485.895 ±   233.143  µs/op
    test5_UsingKeySetAndIterator       avgt   10   1540.281 ±   357.497  µs/op
    test4_UsingKeySetAndForEach        avgt   10   1593.342 ±   294.417  µs/op
    test3_UsingForEachAndJava8         avgt   10   1666.296 ±   126.443  µs/op
    test7_UsingJava8StreamApi          avgt   10   1706.676 ±   436.867  µs/op
    test9_UsingApacheIterableMap       avgt   10   3289.866 ±  1445.564  µs/op
    

Graphs (performance tests depending on map size)

Enter image description here

Table (perfomance tests depending on map size)

          100     600      1100     1600     2100
test10    0.333    1.631    2.752    5.937    8.024
test3     0.309    1.971    4.147    8.147   10.473
test6     0.372    2.190    4.470    8.322   10.531
test1     0.405    2.237    4.616    8.645   10.707
test2     0.376    2.267    4.809    8.403   10.910
test7     0.473    2.448    5.668    9.790   12.125
test9     0.565    2.830    5.952   13.220   16.965
test4     0.808    5.012    8.813   13.939   17.407
test5     0.810    5.104    8.533   14.064   17.422
test8     5.173   12.499   17.351   24.671   30.403

All tests are on GitHub.

SQL Server : Arithmetic overflow error converting expression to data type int

declare @d real
set @d=1.0;
select @d*40000*(192+2)*20000+150000

Better way to sort array in descending order

Sure, You can customize the sort.

You need to give the Sort() a delegate to a comparison method which it will use to sort.

Using an anonymous method:

Array.Sort<int>( array,
delegate(int a, int b)
  {
    return b - a; //Normal compare is a-b
  }); 

Read more about it:

Sorting arrays
MSDN - Array.Sort Method (T[], Comparison)

How can I return the sum and average of an int array?

i refer so many results and modified my code its working

foreach (var rate in rateing)
                {
                    sum += Convert.ToInt32(rate.Rate);
                }
                if(rateing.Count()!= 0)
                {
                    float avg = (float)sum / (float)rateing.Count();
                    saloonusers.Rate = avg;
                }
                else
                {
                    saloonusers.Rate = (float)0.0;
                }

GROUP BY having MAX date

There's no need to group in that subquery... a where clause would suffice:

SELECT * FROM tblpm n
WHERE date_updated=(SELECT MAX(date_updated)
    FROM tblpm WHERE control_number=n.control_number)

Also, do you have an index on the 'date_updated' column? That would certainly help.

How to calculate the number of days between two dates?

Here is my implementation:

function daysBetween(one, another) {
  return Math.round(Math.abs((+one) - (+another))/8.64e7);
}

+<date> does the type coercion to the integer representation and has the same effect as <date>.getTime() and 8.64e7 is the number of milliseconds in a day.

Using gradle to find dependency tree

Often the complete testImplementation, implementation, and androidTestImplementation dependency graph is too much to examine together. If you merely want the implementation dependency graph you can use:

./gradlew app:dependencies --configuration implementation

Source: Gradle docs section 4.7.6

Note: compile has been deprecated in more recent versions of Gradle and in more recent versions you are advised to shift all of your compile dependencies to implementation. Please see this answer here

100% height minus header?

As mentioned in the comments height:100% relies on the height of the parent container being explicitly defined. One way to achieve what you want is to use absolute/relative positioning, and specifying the left/right/top/bottom properties to "stretch" the content out to fill the available space. I have implemented what I gather you want to achieve in jsfiddle. Try resizing the Result window and you will see the content resizes automatically.

The limitation of this approach in your case is that you have to specify an explicit margin-top on the parent container to offset its contents down to make room for the header content. You can make it dynamic if you throw in javascript though.

How do I use TensorFlow GPU?

The 'new' way to install tensorflow GPU if you have Nvidia, is with Anaconda. Works on Windows too. With 1 line.

conda create --name tf_gpu tensorflow-gpu 

This is a shortcut for 3 commands, which you can execute separately if you want or if you already have a conda environment and do not need to create one.

  1. Create an anaconda environment conda create --name tf_gpu

  2. Activate the environment activate tf_gpu

  3. Install tensorflow-GPU conda install tensorflow-gpu

You can use the conda environment.

C# adding a character in a string

Inserting Space in emailId field after every 8 characters

public string BreakEmailId(string emailId) {
    string returnVal = string.Empty;
    if (emailId.Length > 8) {           
        for (int i = 0; i < emailId.Length; i += 8) {
            returnVal += emailId.Substring(i, 8) + " ";
        }
    }

    return returnVal;
}

Cannot find firefox binary in PATH. Make sure firefox is installed

I didn't see the C# anwer to this question here. The trick is to set the BrowserExecutableLocation property on a FirefoxOptions instance, and pass that into the driver constructor:

        var opt = new FirefoxOptions
        {
            BrowserExecutableLocation = @"c:\program files\mozilla firefox\firefox.exe"
        };
        var driver = new FirefoxDriver(opt);

Writing to CSV with Python adds blank lines

If you're using Python 2.x on Windows you need to change your line open('test.csv', 'w') to open('test.csv', 'wb'). That is you should open the file as a binary file.

However, as stated by others, the file interface has changed in Python 3.x.

Cannot find the declaration of element 'beans'

For me the problem was that spring was not able to download http://www.springframework.org/schema/beans/spring-beans.xsd or http://www.springframework.org/schema/context/spring-context.xsd

However I was able to access those from my browser as it was using my machines proxy. So I just copied the content of the two xsds to files named spring-beans.xsd and spring-context.xsd and replaced the http url with the file names and it worked for me.

How can I drop all the tables in a PostgreSQL database?

If all of your tables are in a single schema, this approach could work (below code assumes that the name of your schema is public)

DROP SCHEMA public CASCADE;
CREATE SCHEMA public;

If you are using PostgreSQL 9.3 or greater, you may also need to restore the default grants.

GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO public;

Simple way to copy or clone a DataRow?

You can use ImportRow method to copy Row from DataTable to DataTable with the same schema:

var row = SourceTable.Rows[RowNum];
DestinationTable.ImportRow(row);

Update:

With your new Edit, I believe:

var desRow = dataTable.NewRow();
var sourceRow = dataTable.Rows[rowNum];
desRow.ItemArray = sourceRow.ItemArray.Clone() as object[];

will work

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

Run this command :

    sudo chown -R yourUser /home/yourUser/.composer

how to copy only the columns in a DataTable to another DataTable?

The DataTable.Clone() method works great when you want to create a completely new DataTable, but there might be cases where you would want to add the schema columns from one DataTable to another existing DataTable.

For example, if you've derived a new subclass from DataTable, and want to import schema information into it, you couldn't use Clone().

E.g.:

public class CoolNewTable : DataTable {
   public void FillFromReader(DbDataReader reader) {
       // We want to get the schema information (i.e. columns) from the 
       // DbDataReader and 
       // import it into *this* DataTable, NOT a new one.
       DataTable schema = reader.GetSchemaTable(); 
       //GetSchemaTable() returns a DataTable with the columns we want.

       ImportSchema(this, schema); // <--- how do we do this?
   }
}

The answer is just to create new DataColumns in the existing DataTable using the schema table's columns as templates.

I.e. the code for ImportSchema would be something like this:

void ImportSchema(DataTable dest, DataTable source) {
    foreach(var c in source.Columns)
        dest.Columns.Add(c);
}

or, if you're using Linq:

void ImportSchema(DataTable dest, DataTable source) {
    var cols = source.Columns.Cast<DataColumn>().ToArray();
    dest.Columns.AddRange(cols);
}

This was just one example of a situation where you might want to copy schema/columns from one DataTable into another one without using Clone() to create a completely new DataTable. I'm sure I've come across several others as well.

How do I get the opposite (negation) of a Boolean in Python?

The accepted answer here is the most correct for the given scenario.

It made me wonder though about simply inverting a boolean value in general. It turns out the accepted solution here works as one liner, and there's another one-liner that works as well. Assuming you have a variable "n" that you know is a boolean, the easiest ways to invert it are:

n = n is False

which was my original solution, and then the accepted answer from this question:

n = not n

The latter IS more clear, but I wondered about performance and hucked it through timeit - and it turns out at n = not n is also the FASTER way to invert the boolean value.

Installing PIL with pip

I tried all the answers, but failed. Directly get the source from the official site and then build install success.

  1. Go to the site http://www.pythonware.com/products/pil/#pil117
  2. Click "Python Imaging Library 1.1.7 Source Kit" to download the source
  3. tar xf Imaging-1.1.7.tar.gz
  4. cd Imaging-1.1.7
  5. sudo python setup.py install

Update query with PDO and MySQL

  1. Your UPDATE syntax is wrong
  2. You probably meant to update a row not all of them so you have to use WHERE clause to target your specific row

Change

UPDATE `access_users`   
      (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`) 
      VALUES (:firstname, :surname, :telephone, :email)

to

UPDATE `access_users`   
   SET `contact_first_name` = :firstname,
       `contact_surname` = :surname,
       `contact_email` = :email,
       `telephone` = :telephone 
 WHERE `user_id` = :user_id -- you probably have some sort of id 

Utils to read resource text file to String (Java)

You can use the following code form Java

new String(Files.readAllBytes(Paths.get(getClass().getResource("example.txt").toURI())));

PHP ini file_get_contents external url

This will also give external links an absolute path without having to use php.ini

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.your_external_website.com");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#",'$1http://www.your_external_website.com/$2$3', $result);
echo $result
?>

T-SQL: Selecting rows to delete via joins

DELETE TableA
FROM   TableA a
       INNER JOIN TableB b
               ON b.Bid = a.Bid
                  AND [my filter condition] 

should work

Fastest way to download a GitHub project

Updated July 2016

As of July 2016, the Download ZIP button has moved under Clone or download to extreme-right of header under the Code tab:

Download ZIP (2013)


If you don't see the button:

  • Make sure you've selected <> Code tab from right side navigation menu, or
  • Repo may not have a zip prepared. Add /archive/master.zip to the end of the repository URL and to generate a zipfile of the master branch.

    http://github.com/user/repository/

-to-

http://github.com/user/repository/archive/master.zip

to get the master branch source code in a zip file. You can do the same with tags and branch names, by replacing master in the URL above with the name of the branch or tag.

How do I run a shell script without using "sh" or "bash" commands?

Just make sure it is executable, using chmod +x. By default, the current directory is not on your PATH, so you will need to execute it as ./script.sh - or otherwise reference it by a qualified path. Alternatively, if you truly need just script.sh, you would need to add it to your PATH. (You may not have access to modify the system path, but you can almost certainly modify the PATH of your own current environment.) This also assumes that your script starts with something like #!/bin/sh.

You could also still use an alias, which is not really related to shell scripting but just the shell, and is simple as:

alias script.sh='sh script.sh'

Which would allow you to use just simply script.sh (literally - this won't work for any other *.sh file) instead of sh script.sh.

What are "named tuples" in Python?

named tuples allow backward compatibility with code that checks for the version like this

>>> sys.version_info[0:2]
(3, 1)

while allowing future code to be more explicit by using this syntax

>>> sys.version_info.major
3
>>> sys.version_info.minor
1

create a white rgba / CSS3

The code you have is a white with low opacity.

If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.

Here is a simple demo.

If you want it to look 'more white', make it less opaque:

background:rgba(255,255,255, 0.9);

Demo

How to write new line character to a file in Java

Here is a snippet that gets the default newline character for the current platform. Use System.getProperty("os.name") and System.getProperty("os.version"). Example:

public static String getSystemNewline(){
    String eol = null;
    String os = System.getProperty("os.name").toLowerCase();
    if(os.contains("mac"){
        int v = Integer.parseInt(System.getProperty("os.version"));
        eol = (v <= 9 ? "\r" : "\n");
    }
    if(os.contains("nix"))
        eol = "\n";
    if(os.contains("win"))
        eol = "\r\n";

    return eol;
}

Where eol is the newline

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

Numpy arrays do not have an append method. Use the Numpy append function instead:

import numpy as np

array_3 = np.append(array_1, array_2, axis=n)
# you can either specify an integer axis value n or remove the keyword argument completely

For example, if array_1 and array_2 have the following values:

array_1 = np.array([1, 2])
array_2 = np.array([3, 4])

If you call np.append without specifying an axis value, like so:

array_3 = np.append(array_1, array_2)

array_3 will have the following value:

array([1, 2, 3, 4])

Else, if you call np.append with an axis value of 0, like so:

array_3 = np.append(array_1, array_2, axis=0)

array_3 will have the following value:

 array([[1, 2],
        [3, 4]]) 

More information on the append function here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

I am seeing the same thing. The error does not happen on insert of a row but on an update. the table I am referencing has two DateTime columns neither of which are nullable.

I have gotten the scenario down to getting the row and immediately saving it (no data changes). The get works fine but the update fails.

We are using NHibernate 3.3.1.4000

How to enable named/bind/DNS full logging?

Run command rndc querylog on or add querylog yes; to options{}; section in named.conf to activate that channel.

Also make sure you’re checking correct directory if your bind is chrooted.

How do I find the length of an array?

Here is one implementation of ArraySize from Google Protobuf.

#define GOOGLE_ARRAYSIZE(a) \
  ((sizeof(a) / sizeof(*(a))) / static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))

// test codes...
char* ptr[] = { "you", "are", "here" };
int testarr[] = {1, 2, 3, 4};
cout << GOOGLE_ARRAYSIZE(testarr) << endl;
cout << GOOGLE_ARRAYSIZE(ptr) << endl;

ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in the array) and sizeof(*(arr)) (the # of bytes in one array element). If the former is divisible by the latter, perhaps arr is indeed an array, in which case the division result is the # of elements in the array. Otherwise, arr cannot possibly be an array, and we generate a compiler error to prevent the code from compiling.

Since the size of bool is implementation-defined, we need to cast !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final result has type size_t.

This macro is not perfect as it wrongfully accepts certain pointers, namely where the pointer size is divisible by the pointee size. Since all our code has to go through a 32-bit compiler, where a pointer is 4 bytes, this means all pointers to a type whose size is 3 or greater than 4 will be (righteously) rejected.

How to get CPU temperature?

It can be done in your code via WMI. I've found a tool from Microsoft that creates code for it.

The WMI Code Creator tool allows you to generate VBScript, C#, and VB .NET code that uses WMI to complete a management task such as querying for management data, executing a method from a WMI class, or receiving event notifications using WMI.

You can download it here.

Python Requests package: Handling xml response

requests does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.

Python comes with built-in XML parsers. I recommend you use the ElementTree API:

import requests
from xml.etree import ElementTree

response = requests.get(url)

tree = ElementTree.fromstring(response.content)

or, if the response is particularly large, use an incremental approach:

    response = requests.get(url, stream=True)
    # if the server sent a Gzip or Deflate compressed response, decompress
    # as we read the raw stream:
    response.raw.decode_content = True

    events = ElementTree.iterparse(response.raw)
    for event, elem in events:
        # do something with `elem`

The external lxml project builds on the same API to give you more features and power still.

Unable to make the session state request to the session state server

One of my clients was facing the same issue. Following steps are taken to fix this.

 (1) Open Run. 

 (2) Type Services.msc

 (3) Select ASP.NET State Service

 (4) Right Click and Start it.

How to tell Jackson to ignore a field during serialization if its value is null?

To suppress serializing properties with null values using Jackson >2.0, you can configure the ObjectMapper directly, or make use of the @JsonInclude annotation:

mapper.setSerializationInclusion(Include.NON_NULL);

or:

@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

Alternatively, you could use @JsonInclude in a getter so that the attribute would be shown if the value is not null.

A more complete example is available in my answer to How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson.

Start an activity from a fragment

with Kotlin I execute this code:

requireContext().startActivity<YourTargetActivity>()

Run chrome in fullscreen mode on Windows

Update 03-Oct-19

new script that displays 10second countdown then launches chrome/chromiumn in fullscreen kiosk mode.

more updates to chrome required script update to allow autoplaying video with audio. Note --overscroll-history-navigation=0 isn't working currently will need to disable this flag by going to chrome://flags/#overscroll-history-navigation in your browser and setting to disabled.

@echo off
echo Countdown to application launch...
timeout /t 10
"C:\Program Files (x86)\chrome-win32\chrome.exe" --chrome --kiosk http://localhost/xxxx --incognito --disable-pinch --no-user-gesture-required --overscroll-history-navigation=0
exit

might need to set chrome://flags/#autoplay-policy if running an older version of chrome (60 below)

Update 11-May-16

There have been many updates to chrome since I posted this and have had to alter the script alot to keep it working as I needed.

Couple of issues with newer versions of chrome:

  • built in pinch to zoom
  • Chrome restore error always showing after forced shutdown
  • auto update popup

Because of the restore error switched out to incognito mode as this launches a clear version all the time and does not save what the user was viewing and so if it crashes there is nothing to restore. Also the auto up in newer versions of chrome being a pain to try and disable I switched out to use chromium as it does not auto update and still gives all the modern features of chrome. Note make sure you download the top version of chromium this comes with all audio and video codecs as the basic version of chromium does not support all codecs.

Chromium download link

@echo off

echo Step 1 of 2: Waiting a few seconds before starting the Kiosk...

"C:\windows\system32\ping" -n 5 -w 1000 127.0.0.1 >NUL

echo Step 2 of 5: Waiting a few more seconds before starting the browser...

"C:\windows\system32\ping" -n 5 -w 1000 127.0.0.1 >NUL

echo Final 'invisible' step: Starting the browser, Finally...

"C:\Program Files (x86)\Google\Chromium\chrome.exe" --chrome --kiosk http://127.0.0.1/xxxx --incognito --disable-pinch --overscroll-history-navigation=0

exit

Outdated

I use this for exhibitions to lock down screens. I think its what your looking for.

  • Start chrome and go to www.google.com drag and drop the url out onto the desktop
  • rename it to something handy for this example google_homepage
  • drop this now into your c directory, click on my computer c: and drop this file in there
  • start chrome again go to settings and under on start up select open a specific page and set your home page here.

Next part is the script that I use to start close and restart chrome again in kiosk mode. The locations is where I have chrome installed so it might be abit different for you depending on your install.

Open your text editor of choice or just notepad and past the below code in, make sure its in the same format/order as below. Save it to your desktop as what ever you like so for this example chrome_startup_script.txt next right click it and rename, remove the txt from the end and put in bat instead. double click this to launch the script to see if its working correctly.

A command line box should appear and run through the script, chrome will start and then close down the reason to do this is to remove any error reports such as if the pc crashed, when chrome starts again without this it would show the yellow error bar at the top saying chrome did not shut down properly would you like to restore it. After a few seconds chrome should start again and in kiosk mode and will point to what ever homepage you have set.

@echo off
echo Step 1 of 5: Waiting a few seconds before starting the Kiosk...
"C:\windows\system32\ping" -n 31 -w 1000 127.0.0.1 >NUL
echo Step 2 of 5: Starting browser as a pre-start to delete error messages...
"C:\google_homepage.url"
echo Step 3 of 5: Waiting a few seconds before killing the browser task...
"C:\windows\system32\ping" -n 11 -w 1000 127.0.0.1 >NUL
echo Step 4 of 5: Killing the browser task gracefully to avoid session restore...
Taskkill /IM chrome.exe
echo Step 5 of 5: Waiting a few seconds before restarting the browser...
"C:\windows\system32\ping" -n 11 -w 1000 127.0.0.1 >NUL
echo Final 'invisible' step: Starting the browser, Finally...
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --kiosk --overscroll-history-navigation=0"
exit

Note: The number after the -n of the ping is the amount of seconds (minus one second) to wait before starting the link (or application in the next line)

Finally if this is all working then you can drag and drop the .bat file into the startup folder in windows and this script will launch each time windows starts.


Update:

With recent versions of chrome they have really got into enabling touch gestures, this means that swiping left or right on a touchscreen will cause the browser to go forward or backward in history. To prevent this we need to disable the history navigation on the back and forward buttons to do that add the following --overscroll-history-navigation=0 to the end of the script.

How to drop a PostgreSQL database if there are active connections to it?

I noticed that postgres 9.2 now calls the column pid rather than procpid.

I tend to call it from the shell:

#!/usr/bin/env bash
# kill all connections to the postgres server
if [ -n "$1" ] ; then
  where="where pg_stat_activity.datname = '$1'"
  echo "killing all connections to database '$1'"
else
  echo "killing all connections to database"
fi

cat <<-EOF | psql -U postgres -d postgres 
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
${where}
EOF

Hope that is helpful. Thanks to @JustBob for the sql.

maven compilation failure

My guess is a wrong version of project A jar in your local maven repository. It seems that the dependency is resolved otherwise I think maven does not start compiling but usually these compiling error means that you have a version mix up. try to make a maven clean install of your project A and see if it changes something for the project B... Also a little more information on your setting could be useful:

  • How is maven launched? what command? on a shell, an IDE (using a plugin or not), on a CI server?
  • What maven command are you using?

How to display all methods of an object?

The short answer is you can't because Math and Date (off the top of my head, I'm sure there are others) are't normal objects. To see this, create a simple test script:

<html>
  <body>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
        alert("Math: " + Math);
        alert("Math: " + Math.sqrt);
        alert("Date: " + Date);
        alert("Array: " + Array);
        alert("jQuery: " + jQuery);
        alert("Document: " + document);
        alert("Document: " + document.ready);
      });
    </script>
  </body>
</html>

You see it presents as an object the same ways document does overall, but when you actually try and see in that object, you see that it's native code and something not exposed the same way for enumeration.

Getting parts of a URL (Regex)

I'm a few years late to the party, but I'm surprised no one has mentioned the Uniform Resource Identifier specification has a section on parsing URIs with a regular expression. The regular expression, written by Berners-Lee, et al., is:

^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
 12            3  4          5       6  7        8 9

The numbers in the second line above are only to assist readability; they indicate the reference points for each subexpression (i.e., each paired parenthesis). We refer to the value matched for subexpression as $. For example, matching the above expression to

http://www.ics.uci.edu/pub/ietf/uri/#Related

results in the following subexpression matches:

$1 = http:
$2 = http
$3 = //www.ics.uci.edu
$4 = www.ics.uci.edu
$5 = /pub/ietf/uri/
$6 = <undefined>
$7 = <undefined>
$8 = #Related
$9 = Related

For what it's worth, I found that I had to escape the forward slashes in JavaScript:

^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?

Is floating point math broken?

Binary floating point math is like this. In most programming languages, it is based on the IEEE 754 standard. The crux of the problem is that numbers are represented in this format as a whole number times a power of two; rational numbers (such as 0.1, which is 1/10) whose denominator is not a power of two cannot be exactly represented.

For 0.1 in the standard binary64 format, the representation can be written exactly as

  • 0.1000000000000000055511151231257827021181583404541015625 in decimal, or
  • 0x1.999999999999ap-4 in C99 hexfloat notation.

In contrast, the rational number 0.1, which is 1/10, can be written exactly as

  • 0.1 in decimal, or
  • 0x1.99999999999999...p-4 in an analogue of C99 hexfloat notation, where the ... represents an unending sequence of 9's.

The constants 0.2 and 0.3 in your program will also be approximations to their true values. It happens that the closest double to 0.2 is larger than the rational number 0.2 but that the closest double to 0.3 is smaller than the rational number 0.3. The sum of 0.1 and 0.2 winds up being larger than the rational number 0.3 and hence disagreeing with the constant in your code.

A fairly comprehensive treatment of floating-point arithmetic issues is What Every Computer Scientist Should Know About Floating-Point Arithmetic. For an easier-to-digest explanation, see floating-point-gui.de.

Side Note: All positional (base-N) number systems share this problem with precision

Plain old decimal (base 10) numbers have the same issues, which is why numbers like 1/3 end up as 0.333333333...

You've just stumbled on a number (3/10) that happens to be easy to represent with the decimal system, but doesn't fit the binary system. It goes both ways (to some small degree) as well: 1/16 is an ugly number in decimal (0.0625), but in binary it looks as neat as a 10,000th does in decimal (0.0001)** - if we were in the habit of using a base-2 number system in our daily lives, you'd even look at that number and instinctively understand you could arrive there by halving something, halving it again, and again and again.

** Of course, that's not exactly how floating-point numbers are stored in memory (they use a form of scientific notation). However, it does illustrate the point that binary floating-point precision errors tend to crop up because the "real world" numbers we are usually interested in working with are so often powers of ten - but only because we use a decimal number system day-to-day. This is also why we'll say things like 71% instead of "5 out of every 7" (71% is an approximation, since 5/7 can't be represented exactly with any decimal number).

So no: binary floating point numbers are not broken, they just happen to be as imperfect as every other base-N number system :)

Side Side Note: Working with Floats in Programming

In practice, this problem of precision means you need to use rounding functions to round your floating point numbers off to however many decimal places you're interested in before you display them.

You also need to replace equality tests with comparisons that allow some amount of tolerance, which means:

Do not do if (x == y) { ... }

Instead do if (abs(x - y) < myToleranceValue) { ... }.

where abs is the absolute value. myToleranceValue needs to be chosen for your particular application - and it will have a lot to do with how much "wiggle room" you are prepared to allow, and what the largest number you are going to be comparing may be (due to loss of precision issues). Beware of "epsilon" style constants in your language of choice. These are not to be used as tolerance values.

Increasing the timeout value in a WCF service

Are you referring to the server side or the client side?

For a client, you would want to adjust the sendTimeout attribute of a binding element. For a service, you would want to adjust the receiveTimeout attribute of a binding elemnent.

<system.serviceModel>
  <bindings>
    <netTcpBinding>
      <binding name="longTimeoutBinding"
        receiveTimeout="00:10:00" sendTimeout="00:10:00">
        <security mode="None"/>
      </binding>
    </netTcpBinding>
  </bindings>

  <services>
    <service name="longTimeoutService"
      behaviorConfiguration="longTimeoutBehavior">
      <endpoint address="net.tcp://localhost/longtimeout/"
        binding="netTcpBinding" bindingConfiguration="longTimeoutBinding" />
    </service>
....

Of course, you have to map your desired endpoint to that particular binding.

ORA-01461: can bind a LONG value only for insert into a LONG column-Occurs when querying

A collegue of me and I found out the following:

When we use the Microsoft .NET Oracle driver to connect to an oracle Database (System.Data.OracleClient.OracleConnection)

And we are trying to insert a string with a length between 2000 and 4000 characters into an CLOB or NCLOB field using a database-parameter

oraCommand.CommandText = "INSERT INTO MY_TABLE (NCLOB_COLUMN) VALUES (:PARAMETER1)";
// Add string-parameters with different lengths
// oraCommand.Parameters.Add("PARAMETER1", new string(' ', 1900)); // ok
oraCommand.Parameters.Add("PARAMETER1", new string(' ', 2500));  // Exception
//oraCommand.Parameters.Add("PARAMETER1", new string(' ', 4100)); // ok
oraCommand.ExecuteNonQuery();
  • any string with a length under 2000 characters will not throw this exception
  • any string with a length of more than 4000 characters will not throw this exception
  • only strings with a length between 2000 and 4000 characters will throw this exception

We opened a ticket at microsoft for this bug many years ago, but it has still not been fixed.

What does %>% mean in R

Use ?'%*%' to get the documentation.

%*% is matrix multiplication. For matrix multiplication, you need an m x n matrix times an n x p matrix.

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

For me the error was caused by wrong type hint of url string. I used:

export class TodoService {

  apiUrl: String = 'https://jsonplaceholder.typicode.com/todos' // wrong uppercase String

  constructor(private httpClient: HttpClient) { }

  getTodos(): Observable<Todo[]> {
    return this.httpClient.get<Todo[]>(this.apiUrl)
  }
}

where I should have used

export class TodoService {

  apiUrl: string = 'https://jsonplaceholder.typicode.com/todos' // lowercase string!

  constructor(private httpClient: HttpClient) { }

  getTodos(): Observable<Todo[]> {
    return this.httpClient.get<Todo[]>(this.apiUrl)
  }
}

How to set the size of a column in a Bootstrap responsive table

You could use inline styles and define the width in the <th> tag. Make it so that the sum of the widths = 100%.

    <tr>
        <th style="width:10%">Size</th>
        <th style="width:30%">Bust</th>
        <th style="width:50%">Waist</th>
        <th style="width:10%">Hips</th>
    </tr>

Bootply demo

Typically using inline styles is not ideal, however this does provide flexibility because you can get very specific and granular with exact widths.

Add line break to 'git commit -m' from the command line

I hope this isn't leading too far away from the posted question, but setting the default editor and then using

git commit -e

might be much more comfortable.

What's the difference between & and && in MATLAB?

The single ampersand & is the logical AND operator. The double ampersand && is again a logical AND operator that employs short-circuiting behaviour. Short-circuiting just means the second operand (right hand side) is evaluated only when the result is not fully determined by the first operand (left hand side)

A & B (A and B are evaluated)

A && B (B is only evaluated if A is true)

jQuery: How to capture the TAB keypress within a Textbox

This worked for me:

$("[id*=txtName]").on('keydown', function(e) { var keyCode = e.keyCode || e.which; if (keyCode == 9) { e.preventDefault(); alert('Tab Pressed'); } });

JWT refresh token flow

Below are the steps to do revoke your JWT access token:

  1. When you do log in, send 2 tokens (Access token, Refresh token) in response to the client.
  2. The access token will have less expiry time and Refresh will have long expiry time.
  3. The client (Front end) will store refresh token in his local storage and access token in cookies.
  4. The client will use an access token for calling APIs. But when it expires, pick the refresh token from local storage and call auth server API to get the new token.
  5. Your auth server will have an API exposed which will accept refresh token and checks for its validity and return a new access token.
  6. Once the refresh token is expired, the User will be logged out.

Please let me know if you need more details, I can share the code (Java + Spring boot) as well.

For your questions:

Q1: It's another JWT with fewer claims put in with long expiry time.

Q2: It won't be in a database. The backend will not store anywhere. They will just decrypt the token with private/public key and validate it with its expiry time also.

Q3: Yes, Correct

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:

HTML

<div class="abc"></div>
<div class="abc"></div>

JS

var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div');
div.id = 'hello1';

var body = document.querySelector('body');
body.appendChild(div);

Update

You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0];
    s.id = btoa({{str(produit["avt"]["fto"])}});
</script>

Your requirements still aren't 100% clear though.

How to present a simple alert message in java?

Assuming you already have a JFrame to call this from:

JOptionPane.showMessageDialog(frame, "thank you for using java");

See The Java Tutorials: How to Make Dialogs
See the JavaDoc

How to validate a file upload field using Javascript/jquery

Check it's value property:

In jQuery (since your tag mentions it):

$('#fileInput').val()

Or in vanilla JavaScript:

document.getElementById('myFileInput').value

How can I list all collections in the MongoDB shell?

For switching to the database.

By:

use {your_database_name} example:

use friends

where friends is the name of your database.

Then write:

db.getCollectionNames()
show collections

This will give you the name of collections.

How to use Git and Dropbox together?

There's also an open source project (a collection of cross platform [Linux, Mac, Win] scripts) that does all the nitty-gritty details of the repository management with a handful (3-4) of commands.

https://github.com/karalabe/gitbox/wiki

Sample usage is:

$ gitbox create myapp
Creating empty repository...
Initializing new repository...
Repository successfully created.

$ gitbox clone myapp
Cloning repository...
Repository successfully cloned.

After which normal git usage:

$ echo “Some change” > somefile.txt
$ git add somefile.txt
$ git commit –m “Created some file”
$ git push

Check the project wiki and the manuals for full command reference and tutorials.

MySQL foreach alternative for procedure

This can be done with MySQL, although it's highly unintuitive:

CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
  DECLARE a,b INT;
  DECLARE cur_1 CURSOR FOR SELECT s1 FROM t;
  DECLARE CONTINUE HANDLER FOR NOT FOUND
  SET b = 1;
  OPEN cur_1;
  REPEAT
    FETCH cur_1 INTO a;
    UNTIL b = 1
  END REPEAT;
  CLOSE cur_1;
  SET return_val = a;
END;//

Check out this guide: mysql-storedprocedures.pdf

Intercept page exit event

Instead of an annoying confirmation popup, it would be nice to delay leaving just a bit (matter of milliseconds) to manage successfully posting the unsaved data to the server, which I managed for my site using writing dummy text to the console like this:

window.onbeforeunload=function(e){
  // only take action (iterate) if my SCHEDULED_REQUEST object contains data        
  for (var key in SCHEDULED_REQUEST){   
    postRequest(SCHEDULED_REQUEST); // post and empty SCHEDULED_REQUEST object
    for (var i=0;i<1000;i++){
      // do something unnoticable but time consuming like writing a lot to console
      console.log('buying some time to finish saving data'); 
    };
    break;
  };
}; // no return string --> user will leave as normal but data is send to server

Edit: See also Synchronous_AJAX and how to do that with jquery

Path to MSBuild

This powershell method gets the path to msBuild from multiple sources. Trying in order:

  1. First using vswhere (because Visual Studio seems to have more up to date versions of msBuild) e.g.

    C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe
    
  2. If not found trying the registry (framework version) e.g.

    C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe
    

Powershell code:

Function GetMsBuildPath {

    Function GetMsBuildPathFromVswhere {
        # Based on https://github.com/microsoft/vswhere/wiki/Find-MSBuild/62adac8eb22431fa91d94e03503d76d48a74939c
        $vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
        $path = & $vswhere -latest -prerelease -products * -requires Microsoft.Component.MSBuild -property installationPath
        if ($path) {
            $tool = join-path $path 'MSBuild\Current\Bin\MSBuild.exe'
            if (test-path $tool) {
                return $tool
            }
            $tool = join-path $path 'MSBuild\15.0\Bin\MSBuild.exe'
            if (test-path $tool) {
                return $tool
            }
        }
    }

    Function GetMsBuildPathFromRegistry {
        # Based on Martin Brandl's answer: https://stackoverflow.com/a/57214958/146513
        $msBuildDir = Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\' |
            Get-ItemProperty -Name MSBuildToolsPath |
            Sort-Object PSChildName |
            Select-Object -ExpandProperty MSBuildToolsPath -last 1
        $msBuildPath = join-path $msBuildDir 'msbuild.exe'
        if (test-path $msBuildPath) {
            return $msBuildPath
        }
    }

    $msBuildPath = GetMsBuildPathFromVswhere
    if (-Not $msBuildPath) {
        $msBuildPath = GetMsBuildPathFromRegistry
    }
    return $msBuildPath
}

jQuery UI Accordion Expand/Collapse All

You can try this lightweight small plugin.

It will allow you customize it as per your requirement. It will have Expand/Collapse functionality.

URL: http://accordion-cd.blogspot.com/

How can I split a shell command over multiple lines when using an IF statement?

For Windows/WSL/Cygwin etc users:

Make sure that your line endings are standard Unix line feeds, i.e. \n (LF) only.

Using Windows line endings \r\n (CRLF) line endings will break the command line break.


This is because having \ at the end of a line with Windows line ending translates to \ \r \n.
As Mark correctly explains above:

The line-continuation will fail if you have whitespace after the backslash and before the newline.

This includes not just space () or tabs (\t) but also the carriage return (\r).

JSON.parse unexpected token s

valid json string must have double quote.

JSON.parse({"u1":1000,"u2":1100})       // will be ok

no quote cause error

JSON.parse({u1:1000,u2:1100})    
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2

single quote cause error

JSON.parse({'u1':1000,'u2':1100})    
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2

You must valid json string at https://jsonlint.com

Unsupported operation :not writeable python

You open the variable "file" as a read only then attempt to write to it:

file = open('ValidEmails.txt','r')

Instead, use the 'w' flag.

file = open('ValidEmails.txt','w')
...
file.write(email)

How to split a string by spaces in a Windows batch file?

you can use vbscript instead of batch(cmd.exe)

Set objFS = CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
str1 = objArgs(0)
s=Split(str1," ")
For i=LBound(s) To UBound(s)
    WScript.Echo s(i)
    WScript.Echo s(9) ' get the 10th element
Next

usage:

c:\test> cscript /nologo test.vbs "AAA BBB CCC"

How to add a custom right-click menu to a webpage?

You should remember if you want to use the Firefox only solution, if you want to add it to the whole document you should add contextmenu="mymenu" to the <html> tag not to the body tag.
You should pay attention to this.

Remove stubborn underline from link

Just add this attribute to your anchor tag

style="text-decoration:none;"

Example:

<a href="page.html"  style="text-decoration:none;"></a>

Or use the CSS way.

.classname a {
    color: #FFFFFF;
    text-decoration: none;
}

How do I start/stop IIS Express Server?

Closing IIS Express

By default Visual Studio places the IISExpress icon in your system tray at the lower right hand side of your screen, by the clock. You can right click it and choose exit. If you don't see the icon, try clicking the small arrow to view the full list of icons in the system tray.

IIS Express icon

then right click and choose Exit:

enter image description here


Changing the Port

Another option is to change the port by modifying the project properties. You'll need to do this for each web project in your solution.

  1. Visual Studio > Solution Explorer
  2. Right click the web project and choose Properties
  3. Go to the Web tab
  4. In the 'Servers' section, change the port in the Project URL box
  5. Repeat for each web project in the solution

Changing the IIS Express port


If All Else Fails

If that doesn't work, you can try to bring up Task Manager and close the IIS Express System Tray (32 bit) process and IIS Express Worker Process (32 bit).

Terminating the IIS Express Worker Thread process

If it still doesn't work, as ni5ni6 pointed out, there is a 'Web Deployment Agent Service' running on the port 80. Use this article to track down which process uses it, and turn it off:

https://sites.google.com/site/anashkb/port-80-in-use

How to simulate a click by using x,y coordinates in JavaScript?

it doenst work for me but it prints the correct element to the console

this is the code:

function click(x, y)
{
    var ev = new MouseEvent('click', {
        'view': window,
        'bubbles': true,
        'cancelable': true,
        'screenX': x,
        'screenY': y
    });

    var el = document.elementFromPoint(x, y);
    console.log(el); //print element to console
    el.dispatchEvent(ev);
}
click(400, 400);

Using OR in SQLAlchemy

This has been really helpful. Here is my implementation for any given table:

def sql_replace(self, tableobject, dictargs):

    #missing check of table object is valid
    primarykeys = [key.name for key in inspect(tableobject).primary_key]

    filterargs = []
    for primkeys in primarykeys:
        if dictargs[primkeys] is not None:
            filterargs.append(getattr(db.RT_eqmtvsdata, primkeys) == dictargs[primkeys])
        else:
            return

    query = select([db.RT_eqmtvsdata]).where(and_(*filterargs))

    if self.r_ExecuteAndErrorChk2(query)[primarykeys[0]] is not None:
        # update
        filter = and_(*filterargs)
        query = tableobject.__table__.update().values(dictargs).where(filter)
        return self.w_ExecuteAndErrorChk2(query)

    else:
        query = tableobject.__table__.insert().values(dictargs)
        return self.w_ExecuteAndErrorChk2(query)

# example usage
inrow = {'eqmtvs_id': eqmtvsid, 'datetime': dtime, 'param_id': paramid}

self.sql_replace(tableobject=db.RT_eqmtvsdata, dictargs=inrow)

Split string on the first white space occurrence

Late to the game, I know but there seems to be a very simple way to do this:

_x000D_
_x000D_
const str = "72 tocirah sneab";_x000D_
const arr = str.split(/ (.*)/);_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

This will leave arr[0] with "72" and arr[1] with "tocirah sneab". Note that arr[2] will be empty, but you can just ignore it.

For reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#Capturing_parentheses

How can you dynamically create variables via a while loop?

vars()['meta_anio_2012'] = 'translate'

How to increase Bootstrap Modal Width?

I have also faced the same issue when increasing the width of the modal, the modal is not displaying in the centre. After playing around, I found the below solution.

.modal-dialog {
    max-width: 850px;
    margin: 2rem auto;
}

Upvote if this works for you. Happy Coding!

Write and read a list from file

If you don't need it to be human-readable/editable, the easiest solution is to just use pickle.

To write:

with open(the_filename, 'wb') as f:
    pickle.dump(my_list, f)

To read:

with open(the_filename, 'rb') as f:
    my_list = pickle.load(f)

If you do need them to be human-readable, we need more information.

If my_list is guaranteed to be a list of strings with no embedded newlines, just write them one per line:

with open(the_filename, 'w') as f:
    for s in my_list:
        f.write(s + '\n')

with open(the_filename, 'r') as f:
    my_list = [line.rstrip('\n') for line in f]

If they're Unicode strings rather than byte strings, you'll want to encode them. (Or, worse, if they're byte strings, but not necessarily in the same encoding as your system default.)

If they might have newlines, or non-printable characters, etc., you can use escaping or quoting. Python has a variety of different kinds of escaping built into the stdlib.

Let's use unicode-escape here to solve both of the above problems at once:

with open(the_filename, 'w') as f:
    for s in my_list:
        f.write((s + u'\n').encode('unicode-escape'))

with open(the_filename, 'r') as f:
    my_list = [line.decode('unicode-escape').rstrip(u'\n') for line in f]

You can also use the 3.x-style solution in 2.x, with either the codecs module or the io module:*

import io

with io.open(the_filename, 'w', encoding='unicode-escape') as f:
    f.writelines(line + u'\n' for line in my_list)

with open(the_filename, 'r') as f:
    my_list = [line.rstrip(u'\n') for line in f]

* TOOWTDI, so which is the one obvious way? It depends… For the short version: if you need to work with Python versions before 2.6, use codecs; if not, use io.

How do I do multiple CASE WHEN conditions using SQL Server 2008?

case 
    when a.REASONID in ('02','03','04','05','06') then
        case b.CALSOC 
            when '1' then 'yes' 
            when '2' then 'no' 
            else 'no' 
        end
    else 'no' 
end 

Passing Arrays to Function in C++

The question has already been answered, but I thought I'd add an answer with more precise terminology and references to the C++ standard.

Two things are going on here, array parameters being adjusted to pointer parameters, and array arguments being converted to pointer arguments. These are two quite different mechanisms, the first is an adjustment to the actual type of the parameter, whereas the other is a standard conversion which introduces a temporary pointer to the first element.

Adjustments to your function declaration:

dcl.fct#5:

After determining the type of each parameter, any parameter of type “array of T” (...) is adjusted to be “pointer to T”.

So int arg[] is adjusted to be int* arg.

Conversion of your function argument:

conv.array#1

An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The temporary materialization conversion is applied. The result is a pointer to the first element of the array.

So in printarray(firstarray, 3);, the lvalue firstarray of type "array of 3 int" is converted to a prvalue (temporary) of type "pointer to int", pointing to the first element.

Android Whatsapp/Chat Examples

Check out yowsup
https://github.com/tgalal/yowsup

Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.

A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.

Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.

Determine if an element has a CSS class with jQuery

Without jQuery:

var hasclass=!!(' '+elem.className+' ').indexOf(' check_class ')+1;

Or:

function hasClass(e,c){
    return e&&(e instanceof HTMLElement)&&!!((' '+e.className+' ').indexOf(' '+c+' ')+1);
}
/*example of usage*/
var has_class_medium=hasClass(document.getElementsByTagName('input')[0],'medium');

This is WAY faster than jQuery!

How to get first and last day of week in Oracle?

Actually, I did something like this:

    select case myconfigtable.valpar
       when 'WEEK' then to_char(next_day(datetime-7,'Monday'),'DD/MM/YYYY')|| ' - '|| to_char(next_day(datetime,'Sunday'),'DD/MM/YYYY')
       when 'MONTH' then to_char(to_date(yearweek,'yyyyMM'),'DD/MM/YYYY')  || ' - '|| to_char(last_day(to_date(yearweek,'yyyyMM')),'DD/MM/YYYY')
       else 'NA'
       end
from
(
select to_date(YEAR||'01','YYYYMM') + 7 * (WEEK - 1) datetime, yearweek
       from
       (
       select substr(yearweek,1,4) YEAR,
              to_number(substr(yearweek,5)) WEEK,
              yearweek
       from (select '201018' yearweek from dual
            )
       )
), myconfigtable myconfigtable
 where myconfigtable.codpar='TYPEOFPERIOD'

Argument of type 'X' is not assignable to parameter of type 'X'

This problem basically comes when your compiler gets failed to understand the difference between cast operator of the type string to Number.

you can use the Number object and pass your value to get the appropriate results for it by using Number(<<<<...Variable_Name......>>>>)

Setting Short Value Java

In Java, integer literals are of type int by default. For some other types, you may suffix the literal with a case-insensitive letter like L, D, F to specify a long, double, or float, respectively. Note it is common practice to use uppercase letters for better readability.

The Java Language Specification does not provide the same syntactic sugar for byte or short types. Instead, you may declare it as such using explicit casting:

byte foo = (byte)0;
short bar = (short)0;

In your setLongValue(100L) method call, you don't have to necessarily include the L suffix because in this case the int literal is automatically widened to a long. This is called widening primitive conversion in the Java Language Specification.

Create auto-numbering on images/figures in MS Word

Office 2007

Right click the figure, select Insert Caption, Select Numbering, check box next to 'Include chapter number', select OK, Select OK again, then you figure identifier should be updated.

Calculate date/time difference in java

If you are able to use external libraries I would recommend you to use Joda-Time, noting that:

Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

Example for between calculation:

Seconds.between(startDate, endDate);
Days.between(startDate, endDate);

Insert line after first match using sed

I had a similar task, and was not able to get the above perl solution to work.

Here is my solution:

perl -i -pe "BEGIN{undef $/;} s/^\[mysqld\]$/[mysqld]\n\ncollation-server = utf8_unicode_ci\n/sgm" /etc/mysql/my.cnf

Explanation:

Uses a regular expression to search for a line in my /etc/mysql/my.cnf file that contained only [mysqld] and replaced it with

[mysqld] collation-server = utf8_unicode_ci

effectively adding the collation-server = utf8_unicode_ci line after the line containing [mysqld].

How to Call VBA Function from Excel Cells?

Here's the answer

Steps to follow:

  1. Open the Visual Basic Editor. In Excel, hit Alt+F11 if on Windows, Fn+Option+F11 if on a Mac.

  2. Insert a new module. From the menu: Insert -> Module (Don't skip this!).

  3. Create a Public function. Example:

    Public Function findArea(ByVal width as Double, _
                             ByVal height as Double) As Double
        ' Return the area
        findArea = width * height
    End Function
    
  4. Then use it in any cell like you would any other function: =findArea(B12,C12).

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

let border = CALayer()
     let lineWidth = CGFloat(0.3)
     border.borderColor = UIColor.lightGray.cgColor
     border.frame = CGRect(x: 0, y: emailTextField.frame.size.height - lineWidth, width:  emailTextField.frame.size.width, height: emailTextField.frame.size.height)
     border.borderWidth = lineWidth
     emailTextField.layer.addSublayer(border)
     emailTextField.layer.masksToBounds = true

Tutorial

How can I add a vertical scrollbar to my div automatically?

You have to add max-height property.

_x000D_
_x000D_
.ScrollStyle_x000D_
{_x000D_
    max-height: 150px;_x000D_
    overflow-y: scroll;_x000D_
}
_x000D_
<div class="ScrollStyle">_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get JavaScript variable value in PHP

This could be a little tricky thing but the secure way is to set a javascript cookie, then picking it up by php cookie variable.Then Assign this php variable to an php session that will hold the data more securely than cookie.Then delete the cookie using javascript and redirect the page to itself. Given that you have added an php command to catch the variable, you will get it.

What is Express.js?

  1. What is Express.js?

Express.js is a Node.js web application server framework, designed for building single-page, multi-page, and hybrid web applications. It is the de facto standard server framework for node.js.

Frameworks built on Express.

Several popular Node.js frameworks are built on Express:

LoopBack: Highly-extensible, open-source Node.js framework for quickly creating dynamic end-to-end REST APIs.

Sails: MVC framework for Node.js for building practical, production-ready apps.

Kraken: Secure and scalable layer that extends Express by providing structure and convention.

MEAN: Opinionated fullstack JavaScript framework that simplifies and accelerates web application development.

  1. What is the purpose of it with Node.js?
  2. Why do we actually need Express.js? How it is useful for us to use with Node.js?

Express adds dead simple routing and support for Connect middleware, allowing many extensions and useful features.

For example,

  • Want sessions? It's there
  • Want POST body / query string parsing? It's there
  • Want easy templating through jade, mustache, ejs, etc? It's there
  • Want graceful error handling that won't cause the entire server to crash?

Display/Print one column from a DataFrame of Series in Pandas

By using to_string

print(df.Name.to_string(index=False))


 Adam
  Bob
Cathy

How do I turn a python datetime into a string, with readable format date?

very old question, i know. but with the new f-strings (starting from python 3.6) there are fresh options. so here for completeness:

from datetime import datetime

dt = datetime.now()

# str.format
strg = '{:%B %d, %Y}'.format(dt)
print(strg)  # July 22, 2017

# datetime.strftime
strg = dt.strftime('%B %d, %Y')
print(strg)  # July 22, 2017

# f-strings in python >= 3.6
strg = f'{dt:%B %d, %Y}'
print(strg)  # July 22, 2017

strftime() and strptime() Behavior explains what the format specifiers mean.

RegEx for Javascript to allow only alphanumeric

Alphanumeric with case sensitive:

if (/^[a-zA-Z0-9]+$/.test("SoS007")) {
  alert("match")
}

Getting unique items from a list

In .Net 2.0 I`m pretty sure about this solution:

public IEnumerable<T> Distinct<T>(IEnumerable<T> source)
{
     List<T> uniques = new List<T>();
     foreach (T item in source)
     {
         if (!uniques.Contains(item)) uniques.Add(item);
     }
     return uniques;
}

jquery (or pure js) simulate enter key pressed for testing

For those who want to do this in pure javascript, look at:

Using standard KeyboardEvent

As Joe comment it, KeyboardEvent is now the standard.

Same example to fire an enter (keyCode 13):

const ke = new KeyboardEvent('keydown', {
    bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);

You can use this page help you to find the right keyboard event.


Outdated answer:

You can do something like (here for Firefox)

var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
    'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);

How to add a primary key to a MySQL table?

If your table is quite big better not use the statement:

alter table goods add column `id` int(10) unsigned primary KEY AUTO_INCREMENT;

because it makes a copy of all data in a temporary table, alter table and then copies it back. Better do it manually. Rename your table:

rename table goods to goods_old;

create new table with primary key and all necessary indexes:

create table goods (
    id  int(10) unsigned not null AUTO_INCREMENT
    ... other columns ...
    primary key (id)
);

move all data from the old table into new, disabling keys and indexes to speed up copying:

-- USE THIS FOR MyISAM TABLES:

SET UNIQUE_CHECKS=0;
    ALTER TABLE goods DISABLE KEYS;
        INSERT INTO goods (... your column names ...) SELECT ... your column names FROM goods_old; 
    ALTER TABLE goods ENABLE KEYS;
SET UNIQUE_CHECKS=1;

OR

-- USE THIS FOR InnoDB TABLES:

SET AUTOCOMMIT = 0; SET UNIQUE_CHECKS=0; SET FOREIGN_KEY_CHECKS=0;
    INSERT INTO goods (... your column names ...) SELECT ... your column names FROM goods_old; 
SET FOREIGN_KEY_CHECKS=1; SET UNIQUE_CHECKS=1; COMMIT; SET AUTOCOMMIT = 1;

It takes 2 000 seconds to add PK to a table with ~200 mln rows.

Android: How to rotate a bitmap on a center point

Edited: optimized code.

public static Bitmap RotateBitmap(Bitmap source, float angle)
{
      Matrix matrix = new Matrix();
      matrix.postRotate(angle);
      return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}

To get Bitmap from resources:

Bitmap source = BitmapFactory.decodeResource(this.getResources(), R.drawable.your_img);

Converting BigDecimal to Integer

Well, you could call BigDecimal.intValue():

Converts this BigDecimal to an int. This conversion is analogous to a narrowing primitive conversion from double to short as defined in the Java Language Specification: any fractional part of this BigDecimal will be discarded, and if the resulting "BigInteger" is too big to fit in an int, only the low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this BigDecimal value as well as return a result with the opposite sign.

You can then either explicitly call Integer.valueOf(int) or let auto-boxing do it for you if you're using a sufficiently recent version of Java.

Java 8 lambda Void argument

The syntax you're after is possible with a little helper function that converts a Runnable into Action<Void, Void> (you can place it in Action for example):

public static Action<Void, Void> action(Runnable runnable) {
    return (v) -> {
        runnable.run();
        return null;
    };
}

// Somewhere else in your code
 Action<Void, Void> action = action(() -> System.out.println("foo"));

What is the path for the startup folder in windows 2008 server

In Server 2008 the startup folder for individual users is here:

C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

For All Users it's here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Hope that helps

How to get the xml node value in string

The problem in your code is xml.LoadXml(filePath);

LoadXml method take parameter as xml data not the xml file path

Try this code

   string xmlFile = File.ReadAllText(@"D:\Work_Time_Calculator\10-07-2013.xml");
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(xmlFile);
                XmlNodeList nodeList = xmldoc.GetElementsByTagName("Short_Fall");
                string Short_Fall=string.Empty;
                foreach (XmlNode node in nodeList)
                {
                    Short_Fall = node.InnerText;
                }

Edit

Seeing the last edit of your question i found the solution,

Just replace the below 2 lines

XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall");
string id = node["Short_Fall"].InnerText; // Exception occurs here ("Object reference not set to an instance of an object.")

with

string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;

It should solve your problem or you can use the solution i provided earlier.

IntelliJ show JavaDocs tooltip on mouse over

I tried many ways mentioned here, especially the preference - editor - general - code completion - show documentation popup in.. isn't working in version 2019.2.2

Finally, i am just using F1 while caret is on the type/method and it displays the documentation nicely. This is not ideal but helpful.

What is the purpose of global.asax in asp.net

Global asax events explained

Application_Init: Fired when an application initializes or is first called. It's invoked for all HttpApplication object instances.

Application_Disposed: Fired just before an application is destroyed. This is the ideal location for cleaning up previously used resources.

Application_Error: Fired when an unhandled exception is encountered within the application.

Application_Start: Fired when the first instance of the HttpApplication class is created. It allows you to create objects that are accessible by all HttpApplication instances.

Application_End: Fired when the last instance of an HttpApplication class is destroyed. It's fired only once during an application's lifetime.

Application_BeginRequest: Fired when an application request is received. It's the first event fired for a request, which is often a page request (URL) that a user enters.

Application_EndRequest: The last event fired for an application request.

Application_PreRequestHandlerExecute: Fired before the ASP.NET page framework begins executing an event handler like a page or Web service.

Application_PostRequestHandlerExecute: Fired when the ASP.NET page framework is finished executing an event handler.

Applcation_PreSendRequestHeaders: Fired before the ASP.NET page framework sends HTTP headers to a requesting client (browser).

Application_PreSendContent: Fired before the ASP.NET page framework sends content to a requesting client (browser).

Application_AcquireRequestState: Fired when the ASP.NET page framework gets the current state (Session state) related to the current request.

Application_ReleaseRequestState: Fired when the ASP.NET page framework completes execution of all event handlers. This results in all state modules to save their current state data.

Application_ResolveRequestCache: Fired when the ASP.NET page framework completes an authorization request. It allows caching modules to serve the request from the cache, thus bypassing handler execution.

Application_UpdateRequestCache: Fired when the ASP.NET page framework completes handler execution to allow caching modules to store responses to be used to handle subsequent requests.

Application_AuthenticateRequest: Fired when the security module has established the current user's identity as valid. At this point, the user's credentials have been validated.

Application_AuthorizeRequest: Fired when the security module has verified that a user can access resources.

Session_Start: Fired when a new user visits the application Web site.

Session_End: Fired when a user's session times out, ends, or they leave the application Web site.

Deprecation warning in Moment.js - Not in a recognized ISO format

Doing this works for me:

moment(new Date("27/04/2016")).format

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

IIS 500.19 with 0x80070005 The requested page cannot be accessed because the related configuration data for the page is invalid error

Try installing the 'Application Development' sub component of IIS as mentioned in this SO

  • Click "Start button" in the search box, enter "Turn windows features on or off"
  • in the features window, Click: "Internet Information Services"
  • Click: "World Wide Web Services"
  • Click: "Application Development Features"
  • Check (enable) the features. I checked all but CGI.

enter image description here

Convert a string to a double - is this possible?

Use doubleval(). But be very careful about using decimals in financial transactions, and validate that user input very carefully.

Handling the TAB character in Java

Yes the tab character is one character. You can match it in java with "\t".

Iterator over HashMap in Java

  1. Using EntrySet() and for each loop

       for(Map.Entry<String, String> entry: hashMap.entrySet()) {
         System.out.println("Key Of map = "+ entry.getKey() + 
                          " , value of map = " + entry.getValue() );
     }
    
  2. Using keyset() and for each loop

             for(String key : hashMap.keySet()) {
                System.out.println("Key Of map = "+ key + " , 
                          value of map = " + hashMap.get(key) );
               }
    
  3. Using EntrySet() and java Iterator

          for(String key : hashMap.keySet()) {
            System.out.println("Key Of map = "+ key + " , 
                          value of map = " + hashMap.get(key) );
            }
    
  4. Using keyset() and java Iterator

         Iterator<String> keysIterator = keySet.iterator();
        while (keysIterator.hasNext()) {
            String key = keysIterator.next();
            System.out.println("Key Of map = "+ key + " , value of map = " + hashMap.get(key) );
       }
    

Reference : How to iterate over Map or HashMap in java

Create the perfect JPA entity

My 2 cents addition to the answers here are:

  1. With reference to Field or Property access (away from performance considerations) both are legitimately accessed by means of getters and setters, thus, my model logic can set/get them in the same manner. The difference comes to play when the persistence runtime provider (Hibernate, EclipseLink or else) needs to persist/set some record in Table A which has a foreign key referring to some column in Table B. In case of a Property access type, the persistence runtime system uses my coded setter method to assign the cell in Table B column a new value. In case of a Field access type, the persistence runtime system sets the cell in Table B column directly. This difference is not of importance in the context of a uni-directional relationship, yet it is a MUST to use my own coded setter method (Property access type) for a bi-directional relationship provided the setter method is well designed to account for consistency. Consistency is a critical issue for bi-directional relationships refer to this link for a simple example for a well-designed setter.

  2. With reference to Equals/hashCode: It is impossible to use the Eclipse auto-generated Equals/hashCode methods for entities participating in a bi-directional relationship, otherwise they will have a circular reference resulting in a stackoverflow Exception. Once you try a bidirectional relationship (say OneToOne) and auto-generate Equals() or hashCode() or even toString() you will get caught in this stackoverflow exception.

Should you always favor xrange() over range()?

  • range(): range(1, 10) returns a list from 1 to 10 numbers & hold whole list in memory.
  • xrange(): Like range(), but instead of returning a list, returns an object that generates the numbers in the range on demand. For looping, this is lightly faster than range() and more memory efficient. xrange() object like an iterator and generates the numbers on demand (Lazy Evaluation).
In [1]: range(1,10)
Out[1]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

In [2]: xrange(10)
Out[2]: xrange(10)

In [3]: print xrange.__doc__
Out[3]: xrange([start,] stop[, step]) -> xrange object

range() does the same thing as xrange() used to do in Python 3 and there is not term xrange() exist in Python 3. range() can actually be faster in some scenario if you iterating over the same sequence multiple times. xrange() has to reconstruct the integer object every time, but range() will have real integer objects.

Connect with SSH through a proxy

@rogerdpack for windows platform it is really hard to find a nc.exe with -X(http_proxy), however, I have found nc can be replaced by ncat, full example as follows:

Host github.com
     HostName github.com
         #ProxyCommand nc -X connect -x 127.0.0.1:1080 %h %p
         ProxyCommand ncat --proxy 127.0.0.1:1080 %h %p
     User git
     Port 22
     IdentityFile D:\Users\Administrator\.ssh\github_key

and ncat with --proxy can do a perfect work

Intro to GPU programming

CUDA is an excellent framework to start with. It lets you write GPGPU kernels in C. The compiler will produce GPU microcode from your code and send everything that runs on the CPU to your regular compiler. It is NVIDIA only though and only works on 8-series cards or better. You can check out CUDA zone to see what can be done with it. There are some great demos in the CUDA SDK. The documentation that comes with the SDK is a pretty good starting point for actually writing code. It will walk you through writing a matrix multiplication kernel, which is a great place to begin.

C# Connecting Through Proxy

This is easily achieved either programmatically, in your code, or declaratively in either the web.config or the app.config.

You can programmatically create a proxy like so:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("[ultimate destination of your request]");
WebProxy myproxy = new WebProxy("[your proxy address]", [your proxy port number]);
myproxy.BypassProxyOnLocal = false;
request.Proxy = myproxy;
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse) request.GetResponse();

You're basically assigning the WebProxy object to the request object's proxy property. This request will then use the proxy you define.

To achieve the same thing declaratively, you can do the following:

<system.net>
  <defaultProxy>
    <proxy
      proxyaddress="http://[your proxy address and port number]"
      bypassonlocal="false"
    />
  </defaultProxy>
</system.net>

within your web.config or app.config. This sets a default proxy that all http requests will use. Depending upon exactly what you need to achieve, you may or may not require some of the additional attributes of the defaultProxy / proxy element, so please refer to the documentation for those.

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

Try to use:

mvn jacoco:report -debug

to see the details about your reporting process.

I configured my jacoco like this:

<configuration>
    <dataFile>~/jacoco.exec</dataFile>
    <outputDirectory>~/jacoco</outputDirectory>
</configuration>

Then mvn jacoco:report -debug shows it using the default configuration, which means jacoco.exec is not in ~/jacoco.exec. The error says missing execution data file.

So just use the default configuration:

<execution>
    <id>default-report</id>
    <goals>
    </goals>
    <configuration>
        <dataFile>${project.build.directory}/jacoco.exec</dataFile>
        <outputDirectory>${project.reporting.outputDirectory}/jacoco</outputDirectory>
    </configuration>
</execution>

And everything works fine.

How to pass objects to functions in C++?

There are some differences in calling conventions in C++ and Java. In C++ there are technically speaking only two conventions: pass-by-value and pass-by-reference, with some literature including a third pass-by-pointer convention (that is actually pass-by-value of a pointer type). On top of that, you can add const-ness to the type of the argument, enhancing the semantics.

Pass by reference

Passing by reference means that the function will conceptually receive your object instance and not a copy of it. The reference is conceptually an alias to the object that was used in the calling context, and cannot be null. All operations performed inside the function apply to the object outside the function. This convention is not available in Java or C.

Pass by value (and pass-by-pointer)

The compiler will generate a copy of the object in the calling context and use that copy inside the function. All operations performed inside the function are done to the copy, not the external element. This is the convention for primitive types in Java.

An special version of it is passing a pointer (address-of the object) into a function. The function receives the pointer, and any and all operations applied to the pointer itself are applied to the copy (pointer), on the other hand, operations applied to the dereferenced pointer will apply to the object instance at that memory location, so the function can have side effects. The effect of using pass-by-value of a pointer to the object will allow the internal function to modify external values, as with pass-by-reference and will also allow for optional values (pass a null pointer).

This is the convention used in C when a function needs to modify an external variable, and the convention used in Java with reference types: the reference is copied, but the referred object is the same: changes to the reference/pointer are not visible outside the function, but changes to the pointed memory are.

Adding const to the equation

In C++ you can assign constant-ness to objects when defining variables, pointers and references at different levels. You can declare a variable to be constant, you can declare a reference to a constant instance, and you can define all pointers to constant objects, constant pointers to mutable objects and constant pointers to constant elements. Conversely in Java you can only define one level of constant-ness (final keyword): that of the variable (instance for primitive types, reference for reference types), but you cannot define a reference to an immutable element (unless the class itself is immutable).

This is extensively used in C++ calling conventions. When the objects are small you can pass the object by value. The compiler will generate a copy, but that copy is not an expensive operation. For any other type, if the function will not change the object, you can pass a reference to a constant instance (usually called constant reference) of the type. This will not copy the object, but pass it into the function. But at the same time the compiler will guarantee that the object is not changed inside the function.

Rules of thumb

This are some basic rules to follow:

  • Prefer pass-by-value for primitive types
  • Prefer pass-by-reference with references to constant for other types
  • If the function needs to modify the argument use pass-by-reference
  • If the argument is optional, use pass-by-pointer (to constant if the optional value should not be modified)

There are other small deviations from these rules, the first of which is handling ownership of an object. When an object is dynamically allocated with new, it must be deallocated with delete (or the [] versions thereof). The object or function that is responsible for the destruction of the object is considered the owner of the resource. When a dynamically allocated object is created in a piece of code, but the ownership is transfered to a different element it is usually done with pass-by-pointer semantics, or if possible with smart pointers.

Side note

It is important to insist in the importance of the difference between C++ and Java references. In C++ references are conceptually the instance of the object, not an accessor to it. The simplest example is implementing a swap function:

// C++
class Type; // defined somewhere before, with the appropriate operations
void swap( Type & a, Type & b ) {
   Type tmp = a;
   a = b;
   b = tmp;
}
int main() {
   Type a, b;
   Type old_a = a, old_b = b;
   swap( a, b );
   assert( a == old_b );
   assert( b == old_a ); 
}

The swap function above changes both its arguments through the use of references. The closest code in Java:

public class C {
   // ...
   public static void swap( C a, C b ) {
      C tmp = a;
      a = b;
      b = tmp;
   }
   public static void main( String args[] ) {
      C a = new C();
      C b = new C();
      C old_a = a;
      C old_b = b;
      swap( a, b ); 
      // a and b remain unchanged a==old_a, and b==old_b
   }
}

The Java version of the code will modify the copies of the references internally, but will not modify the actual objects externally. Java references are C pointers without pointer arithmetic that get passed by value into functions.

Android file chooser

I used AndExplorer for this purpose and my solution is popup a dialog and then redirect on the market to install the misssing application:

My startCreation is trying to call external file/directory picker. If it is missing call show installResultMessage function.

private void startCreation(){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_PICK);
    Uri startDir = Uri.fromFile(new File("/sdcard"));

    intent.setDataAndType(startDir,
            "vnd.android.cursor.dir/lysesoft.andexplorer.file");
    intent.putExtra("browser_filter_extension_whitelist", "*.csv");
    intent.putExtra("explorer_title", getText(R.string.andex_file_selection_title));
    intent.putExtra("browser_title_background_color",
            getText(R.string.browser_title_background_color));
    intent.putExtra("browser_title_foreground_color",
            getText(R.string.browser_title_foreground_color));
    intent.putExtra("browser_list_background_color",
            getText(R.string.browser_list_background_color));
    intent.putExtra("browser_list_fontscale", "120%");
    intent.putExtra("browser_list_layout", "2");

    try{
         ApplicationInfo info = getPackageManager()
                                 .getApplicationInfo("lysesoft.andexplorer", 0 );

            startActivityForResult(intent, PICK_REQUEST_CODE);
    } catch( PackageManager.NameNotFoundException e ){
        showInstallResultMessage(R.string.error_install_andexplorer);
    } catch (Exception e) {
        Log.w(TAG, e.getMessage());
    }
}

This methos is just pick up a dialog and if user wants install the external application from market

private void showInstallResultMessage(int msg_id) {
    AlertDialog dialog = new AlertDialog.Builder(this).create();
    dialog.setMessage(getText(msg_id));
    dialog.setButton(getText(R.string.button_ok),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
    dialog.setButton2(getText(R.string.button_install),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("market://details?id=lysesoft.andexplorer"));
                    startActivity(intent);
                    finish();
                }
            });
    dialog.show();
}

How to Install Font Awesome in Laravel Mix

Try in your webpack.mix.js to add the '*'

.copy('node_modules/font-awesome/fonts/*', 'public/fonts')

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

Android translate animation - permanently move View to new position using AnimationListener

You should rather use ViewPropertyAnimator. This animates the view to its future position and you don't need to force any layout params on the view after the animation ends. And it's rather simple.

myView.animate().x(50f).y(100f);

myView.animate().translateX(pixelInScreen) 

Note: This pixel is not relative to the view. This pixel is the pixel position in the screen.

Taking screenshot on Emulator from Android Studio

Besides using Android Studio, you can also take a screenshot with adb which is faster.

adb shell screencap -p /sdcard/screen.png
adb pull /sdcard/screen.png
adb shell rm /sdcard/screen.png

Shorter one line alternative in Unix/OSX

adb shell screencap -p | perl -pe 's/\x0D\x0A/\x0A/g' > screen.png

Original blog post: Grab Android screenshot to computer via ADB

Batch files: List all files in a directory with relative paths

You could simply get the character length of the current directory, and remove them from your absolute list

setlocal EnableDelayedExpansion
for /L %%n in (1 1 500) do if "!__cd__:~%%n,1!" neq "" set /a "len=%%n+1"
setlocal DisableDelayedExpansion
for /r . %%g in (*.log) do (
  set "absPath=%%g"
  setlocal EnableDelayedExpansion
  set "relPath=!absPath:~%len%!"
  echo(!relPath!
  endlocal
)

GET parameters in the URL with CodeIgniter

When I first started working with CodeIgniter, not using GET really threw me off as well. But then I realized that you can simulate GET parameters by manipulating the URI using the built-in URI Class. It's fantastic and it makes your URLs look better.

Or if you really need GETs working you can put this into your controller:

parse_str($_SERVER['QUERY_STRING'], $_GET); 

Which will put the variables back into the GET array.

how to do "press enter to exit" in batch

@echo off
echo Press any key to exit . . .
pause>nul

Validate form field only on submit or user input

If you want to show error messages on form submission, you can use condition form.$submitted to check if an attempt was made to submit the form. Check following example.

<form name="myForm" novalidate ng-submit="myForm.$valid && createUser()">
  <input type="text" name="name" ng-model="user.name" placeholder="Enter name of user" required>
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user name.</div>
  </div>

  <input type="text" name="address" ng-model="user.address" placeholder="Enter Address" required ng-maxlength="30">
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user address.</div>
    <div ng-message="maxlength">Should be less than 30 chars</div>
  </div>

  <button type="submit">
    Create user
  </button>
</form>

Switch statement for string matching in JavaScript

var token = 'spo';

switch(token){
    case ( (token.match(/spo/) )? token : undefined ) :
       console.log('MATCHED')    
    break;;
    default:
       console.log('NO MATCH')
    break;;
}


--> If the match is made the ternary expression returns the original token
----> The original token is evaluated by case

--> If the match is not made the ternary returns undefined
----> Case evaluates the token against undefined which hopefully your token is not.

The ternary test can be anything for instance in your case

( !!~ base_url_string.indexOf('xxx.dev.yyy.com') )? xxx.dev.yyy.com : undefined 

===========================================

(token.match(/spo/) )? token : undefined ) 

is a ternary expression.

The test in this case is token.match(/spo/) which states the match the string held in token against the regex expression /spo/ ( which is the literal string spo in this case ).

If the expression and the string match it results in true and returns token ( which is the string the switch statement is operating on ).

Obviously token === token so the switch statement is matched and the case evaluated

It is easier to understand if you look at it in layers and understand that the turnery test is evaluated "BEFORE" the switch statement so that the switch statement only sees the results of the test.

Changing date format in R

Using one line to convert the dates to preferred format:

nzd$date <- format(as.Date(nzd$date, format="%d/%m/%Y"),"%Y/%m/%d")

How to add an image to a JPanel?

Here's how I do it (with a little more info on how to load an image):

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class ImagePanel extends JPanel{

    private BufferedImage image;

    public ImagePanel() {
       try {                
          image = ImageIO.read(new File("image name and path"));
       } catch (IOException ex) {
            // handle exception...
       }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this); // see javadoc for more info on the parameters            
    }

}

How to test if a string is JSON or not?

You can try the following one because it also validates number, null, string but the above-marked answer is not working correctly it's just a fix of the above function:

function isJson(str) {
  try {
      const obj = JSON.parse(str);
      if (obj && typeof obj === `object`) {
        return true;
      }
    } catch (err) {
      return false;
    }
   return false;
}

Add Bean Programmatically to Spring Web App Context

First initialize Property values

MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
mutablePropertyValues.add("hostName", details.getHostName());
mutablePropertyValues.add("port", details.getPort());

DefaultListableBeanFactory context = new DefaultListableBeanFactory();
GenericBeanDefinition connectionFactory = new GenericBeanDefinition();
connectionFactory.setBeanClass(Class);
connectionFactory.setPropertyValues(mutablePropertyValues);

context.registerBeanDefinition("beanName", connectionFactory);

Add to the list of beans

ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
beanFactory.registerSingleton("beanName", context.getBean("beanName"));

Replacement for deprecated sizeWithFont: in iOS 7?

Building on @bitsand, this is a new method I just added to my NSString+Extras category:

- (CGRect) boundingRectWithFont:(UIFont *) font constrainedToSize:(CGSize) constraintSize lineBreakMode:(NSLineBreakMode) lineBreakMode;
{
    // set paragraph style
    NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    [style setLineBreakMode:lineBreakMode];

    // make dictionary of attributes with paragraph style
    NSDictionary *sizeAttributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName: style};

    CGRect frame = [self boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:sizeAttributes context:nil];

    /*
    // OLD
    CGSize stringSize = [self sizeWithFont:font
                              constrainedToSize:constraintSize
                                  lineBreakMode:lineBreakMode];
    // OLD
    */

    return frame;
}

I just use the size of the resulting frame.

How to vertically align an image inside a div

You can use this:

 .loaderimage {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 60px;
    height: 60px;
    margin-top: -30px; /* 50% of the height */
    margin-left: -30px;
 }

Transform char array into String

Three years later, I ran into the same problem. Here's my solution, everybody feel free to cut-n-paste. The simplest things keep us up all night! Running on an ATMega, and Adafruit Feather M0:

void setup() {
  // turn on Serial so we can see...
  Serial.begin(9600);

  // the culprit:
  uint8_t my_str[6];    // an array big enough for a 5 character string

  // give it something so we can see what it's doing
  my_str[0] = 'H';
  my_str[1] = 'e';
  my_str[2] = 'l';
  my_str[3] = 'l';
  my_str[4] = 'o';
  my_str[5] = 0;  // be sure to set the null terminator!!!

  // can we see it?
  Serial.println((char*)my_str);

  // can we do logical operations with it as-is?
  Serial.println((char*)my_str == 'Hello');

  // okay, it can't; wrong data type (and no terminator!), so let's do this:
  String str((char*)my_str);

  // can we see it now?
  Serial.println(str);

  // make comparisons
  Serial.println(str == 'Hello');

  // one more time just because
  Serial.println(str == "Hello");

  // one last thing...!
  Serial.println(sizeof(str));
}

void loop() {
  // nothing
}

And we get:

Hello    // as expected
0        // no surprise; wrong data type and no terminator in comparison value
Hello    // also, as expected
1        // YAY!
1        // YAY!
6        // as expected

Hope this helps someone!

mySQL select IN range

To select data in numerical range you can use BETWEEN which is inclusive.

SELECT JOB FROM MYTABLE WHERE ID BETWEEN 10 AND 15;

Regex to remove letters, symbols except numbers

Simple:

var removedText = self.val().replace(/[^0-9]+/, '');

^ - means NOT

How can I change column types in Spark SQL's DataFrame?

You can use selectExpr to make it a little cleaner:

df.selectExpr("cast(year as int) as year", "upper(make) as make",
    "model", "comment", "blank")

Any way to write a Windows .bat file to kill processes?

Get Autoruns from Mark Russinovich, the Sysinternals guy that discovered the Sony Rootkit... Best software I've ever used for cleaning up things that get started automatically.

CSS no text wrap

Use the css property overflow . For example:

  .item{
    width : 100px;
    overflow:hidden;
  }

The overflow property can have one of many values like ( hidden , scroll , visible ) .. you can als control the overflow in one direction only using overflow-x or overflow-y.

I hope this helps.

Rendering HTML inside textarea

This is not possible to do with a textarea. What you are looking for is an content editable div, which is very easily done:

<div contenteditable="true"></div>

jsFiddle

_x000D_
_x000D_
div.editable {_x000D_
    width: 300px;_x000D_
    height: 200px;_x000D_
    border: 1px solid #ccc;_x000D_
    padding: 5px;_x000D_
}_x000D_
_x000D_
strong {_x000D_
  font-weight: bold;_x000D_
}
_x000D_
<div contenteditable="true">This is the first line.<br>_x000D_
See, how the text fits here, also if<br>there is a <strong>linebreak</strong> at the end?_x000D_
<br>It works nicely._x000D_
<br>_x000D_
<br><span style="color: lightgreen">Great</span>._x000D_
</div>
_x000D_
_x000D_
_x000D_

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

The startup of the emulator is very slow. The good thing is that you only need to start the emulator once. If the emulator is already running and you run your app again, the emulator reinstalls the app relatively quickly. Of course, if you want to know how fast it will run on a phone, it is best to test it on a real phone.

How do ACID and database transactions work?

[Gray] introduced the ACD properties for a transaction in 1981. In 1983 [Haerder] added the Isolation property. In my opinion, the ACD properties would be have a more useful set of properties to discuss. One interpretation of Atomicity (that the transaction should be atomic as seen from any client any time) would actually imply the isolation property. The "isolation" property is useful when the transaction is not isolated; when the isolation property is relaxed. In ANSI SQL speak: if the isolation level is weaker then SERIALIZABLE. But when the isolation level is SERIALIZABLE, the isolation property is not really of interest.

I have written more about this in a blog post: "ACID Does Not Make Sense".

http://blog.franslundberg.com/2013/12/acid-does-not-make-sense.html

[Gray] The Transaction Concept, Jim Gray, 1981. http://research.microsoft.com/en-us/um/people/gray/papers/theTransactionConcept.pdf

[Haerder] Principles of Transaction-Oriented Database Recovery, Haerder and Reuter, 1983. http://www.stanford.edu/class/cs340v/papers/recovery.pdf

python JSON object must be str, bytes or bytearray, not 'dict

json.dumps() is used to decode JSON data

import json

# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
    'int': int_data,
    'str': str_data,
    'float': float_data,
    'list': list_data,
    'nested list': nested_list
}

# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4))  # the json data will be indented

output:

String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
    1,
    1.5,
    [
        "normal string",
        1,
        1.5
    ]
]
Dictionary : {
    "int": 1,
    "str": "normal string",
    "float": 1.5,
    "list": [
        "normal string",
        1,
        1.5
    ],
    "nested list": [
        1,
        1.5,
        [
            "normal string",
            1,
            1.5
        ]
    ]
}
  • Python Object to JSON Data Conversion
|                 Python                 |  JSON  |
|:--------------------------------------:|:------:|
|                  dict                  | object |
|               list, tuple              |  array |
|                   str                  | string |
| int, float, int- & float-derived Enums | number |
|                  True                  |  true  |
|                  False                 |  false |
|                  None                  |  null  |

json.loads() is used to convert JSON data into Python data.

import json

# initialize different JSON data
arrayJson = '[1, 1.5, ["normal string", 1, 1.5]]'
objectJson = '{"a":1, "b":1.5 , "c":["normal string", 1, 1.5]}'

# convert them to Python Data
list_data = json.loads(arrayJson)
dictionary = json.loads(objectJson)

print('arrayJson to list_data :\n', list_data)
print('\nAccessing the list data :')
print('list_data[2:] =', list_data[2:])
print('list_data[:1] =', list_data[:1])

print('\nobjectJson to dictionary :\n', dictionary)
print('\nAccessing the dictionary :')
print('dictionary[\'a\'] =', dictionary['a'])
print('dictionary[\'c\'] =', dictionary['c'])

output:

arrayJson to list_data :
 [1, 1.5, ['normal string', 1, 1.5]]

Accessing the list data :
list_data[2:] = [['normal string', 1, 1.5]]
list_data[:1] = [1]

objectJson to dictionary :
 {'a': 1, 'b': 1.5, 'c': ['normal string', 1, 1.5]}

Accessing the dictionary :
dictionary['a'] = 1
dictionary['c'] = ['normal string', 1, 1.5]
  • JSON Data to Python Object Conversion
|      JSON     | Python |
|:-------------:|:------:|
|     object    |  dict  |
|     array     |  list  |
|     string    |   str  |
|  number (int) |   int  |
| number (real) |  float |
|      true     |  True  |
|     false     |  False |

How to create a connection string in asp.net c#

It occurs when IIS is not being connected to SQL SERVER. For a solution, see this screenshot: Solution

List file names based on a filename pattern and file content?

Assume LMN2011* files are inside /home/me but skipping anything in /home/me/temp or below:

find /home/me -name 'LMN2011*' -not -path "/home/me/temp/*" -print | xargs grep 'LMN20113456'

Read connection string from web.config

I guess you need to add a reference to the System.Configuration assembly if that have not already been added.

Also, you may need to insert the following line at the top of your code file:

using System.Configuration;

How to update the value of a key in a dictionary in Python?

Well you could directly substract from the value by just referencing the key. Which in my opinion is simpler.

>>> books = {}
>>> books['book'] = 3       
>>> books['book'] -= 1   
>>> books   
{'book': 2}   

In your case:

book_shop[ch1] -= 1

How to declare global variables in Android?

Just you need to define an application name like below which will work:

<application
  android:name="ApplicationName" android:icon="@drawable/icon">
</application>

Use querystring variables in MVC controller

Davids, I had the exact same problem as you. MVC is not intuitive and it seems when they designed it the kiddos didn't understand the purpose or importance of an intuitive querystring system for MVC.

Querystrings are not set in the routes at all (RouteConfig). They are add-on "extra" parameters to Actions in the Controller. This is very confusing as the Action parameters are designed to process BOTH paths AND Querystrings. If you added parameters and they did not work, add a second one for the querystring as so:

This would be your action in your Controller class that catches the ID (which is actually just a path set in your RouteConfig file as a typical default path in MVC):

public ActionResult Hello(int id)

But to catch querystrings an additional parameter in your Controller needs to be the added (which is NOT set in your RouteConfig file, by the way):

public ActionResult Hello(int id, string start, string end)

This now listens for "/Hello?start=&end=" or "/Hello/?start=&end=" or "/Hello/45?start=&end=" assuming the "id" is set to optional in the RouteConfig.cs file.

If you wanted to create a "custom route" in the RouteConfig file that has no "id" path, you could leave off the "id" or other parameter after the action in that file. In that case your parameters in your Action method in the controller would process just querystrings.

I found this extremely confusing myself so you are not alone! They should have designed a simple way to add querystring routes for both specific named strings, any querystring name, and any number of querystrings in the RouteConfig file configuration design. By not doing that it leaves the whole use of querystrings in MVC web applications as questionable, which is pretty bizarre since querystrings have been a stable part of the World Wide Web since the mid-1990's. :(

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

Having named method in place of the anonymous function in audioNode.addEventListener 's callback should eliminate the subject warning:

    componentDidMount(prevProps, prevState, prevContext) {
    let [audioNode, songLen] = [this.refs.audio, List.length-1];

    audioNode.addEventListener('ended', () => {
        this._endedPlay(songLen, () => {
            this._currSong(this.state.songIndex);
            this._Play(audioNode);
        });
    });

    audioNode.addEventListener('timeupdate', this.callbackMethod );
}

callBackMethod = () => {
    let [remainTime, remainTimeMin, remainTimeSec, remainTimeInfo] = [];

    if(!isNaN(audioNode.duration)) {
        remainTime = audioNode.duration - audioNode.currentTime;
        remainTimeMin = parseInt(remainTime/60);  // ???
        remainTimeSec = parseInt(remainTime%60);  // ???

        if(remainTimeSec < 10) {
            remainTimeSec = '0'+remainTimeSec;
        }
        remainTimeInfo = remainTimeMin + ':' + remainTimeSec;
        this.setState({'time': remainTimeInfo});
    }
}

And yes, named method is needed anyways because removeEventListener won't work with anonymous callbacks, as mentioned above several times.

Hash Map in Python

It's built-in for Python. See dictionaries.

Based on your example:

streetno = {"1": "Sachine Tendulkar",
            "2": "Dravid",
            "3": "Sehwag",
            "4": "Laxman",
            "5": "Kohli" }

You could then access it like so:

sachine = streetno["1"]

Also worth mentioning: it can use any non-mutable data type as a key. That is, it can use a tuple, boolean, or string as a key.

How to break out of nested loops?

bool stop = false;
for (int i = 0; (i < 1000) && !stop; i++)
{
    for (int j = 0; (j < 1000) && !stop; j++)
    {
        if (condition)
            stop = true;
    }
}

C++ getters/setters coding style

Avoid public variables, except for classes that are essentially C-style structs. It's just not a good practice to get into.

Once you've defined the class interface, you might never be able to change it (other than adding to it), because people will build on it and rely on it. Making a variable public means that you need to have that variable, and you need to make sure it has what the user needs.

Now, if you use a getter, you're promising to supply some information, which is currently kept in that variable. If the situation changes, and you'd rather not maintain that variable all the time, you can change the access. If the requirements change (and I've seen some pretty odd requirements changes), and you mostly need the name that's in this variable but sometimes the one in that variable, you can just change the getter. If you made the variable public, you'd be stuck with it.

This won't always happen, but I find it a lot easier just to write a quick getter than to analyze the situation to see if I'd regret making the variable public (and risk being wrong later).

Making member variables private is a good habit to get into. Any shop that has code standards is probably going to forbid making the occasional member variable public, and any shop with code reviews is likely to criticize you for it.

Whenever it really doesn't matter for ease of writing, get into the safer habit.

How to combine 2 plots (ggplot) into one plot?

Just combine them. I think this should work but it's untested:

p <- ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() + 
     geom_smooth(fill="blue", colour="darkblue", size=1)

p <- p + geom_point(data=visual2, aes(ISSUE_DATE,COUNTED)) + 
     geom_smooth(data=visual2, fill="red", colour="red", size=1)

print(p)

How to delete a line from a text file in C#?

I wrote a method to delete lines from files.

This program uses using System.IO.

See my code:

void File_DeleteLine(int Line, string Path)
{
    StringBuilder sb = new StringBuilder();
    using (StreamReader sr = new StreamReader(Path))
    {
        int Countup = 0;
        while (!sr.EndOfStream)
        {
            Countup++;
            if (Countup != Line)
            {
                using (StringWriter sw = new StringWriter(sb))
                {
                    sw.WriteLine(sr.ReadLine());
                }
            }
            else
            {
                sr.ReadLine();
            }
        }
    }
    using (StreamWriter sw = new StreamWriter(Path))
    {
        sw.Write(sb.ToString());
    }
}

How to programmatically modify WCF app.config endpoint address setting?

SomeServiceClient client = new SomeServiceClient();

var endpointAddress = client.Endpoint.Address; //gets the default endpoint address

EndpointAddressBuilder newEndpointAddress = new EndpointAddressBuilder(endpointAddress);
                newEndpointAddress.Uri = new Uri("net.tcp://serverName:8000/SomeServiceName/");
                client = new SomeServiceClient("EndpointConfigurationName", newEndpointAddress.ToEndpointAddress());

I did it like this. The good thing is it still picks up the rest of your endpoint binding settings from the config and just replaces the URI.

How do I change the UUID of a virtual disk?

Though you have solved the problem, I just post the reason here for some others with the similar problem.

The reason is there's an space in your path(directory name VirtualBox VMs) which will separate the command. So the error appears.

In PHP, how do you change the key of an array element?

You can write simple function that applies the callback to the keys of the given array. Similar to array_map

<?php
function array_map_keys(callable $callback, array $array) {
    return array_merge([], ...array_map(
        function ($key, $value) use ($callback) { return [$callback($key) => $value]; },
        array_keys($array),
        $array
    ));
}

$array = ['a' => 1, 'b' => 'test', 'c' => ['x' => 1, 'y' => 2]];
$newArray = array_map_keys(function($key) { return 'new' . ucfirst($key); }, $array);

echo json_encode($array); // {"a":1,"b":"test","c":{"x":1,"y":2}}
echo json_encode($newArray); // {"newA":1,"newB":"test","newC":{"x":1,"y":2}}

Here is a gist https://gist.github.com/vardius/650367e15abfb58bcd72ca47eff096ca#file-array_map_keys-php.

Retrieving the COM class factory for component failed

For IIS 8 I did basically the same thing as Monic. Im running my application as its own app pool on an x64 machine 1.In DCOMCNFG, right click on the My Computer and select properties.

2.Choose the COM Securities tab.

3.In Access Permissions, click Edit Defaults and add iis apppool\myapp to it and give it Allow local access permission. Do the same for iis apppool\myapp

4.In launch and Activation Permissions, click Edit Defaults and add iis apppool\myapp to it and give it Local launch and Local Activation permission. Do the same for iis apppool\myapp.

additionally I had to make the folders outlined under C:\Windows\SysWOW64\config\systemprofile\Desktop and give read \ write permissions to iis apppool\myapp also

Best Timer for using in a Windows service

As already stated both System.Threading.Timer and System.Timers.Timer will work. The big difference between the two is that System.Threading.Timer is a wrapper arround the other one.

System.Threading.Timer will have more exception handling while System.Timers.Timer will swallow all the exceptions.

This gave me big problems in the past so I would always use 'System.Threading.Timer' and still handle your exceptions very well.

How can you get the active users connected to a postgreSQL database via SQL?

(question) Don't you get that info in

select * from pg_user;

or using the view pg_stat_activity:

select * from pg_stat_activity;

Added:

the view says:

One row per server process, showing database OID, database name, process ID, user OID, user name, current query, query's waiting status, time at which the current query began execution, time at which the process was started, and client's address and port number. The columns that report data on the current query are available unless the parameter stats_command_string has been turned off. Furthermore, these columns are only visible if the user examining the view is a superuser or the same as the user owning the process being reported on.

can't you filter and get that information? that will be the current users on the Database, you can use began execution time to get all queries from last 5 minutes for example...

something like that.

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

I found that max_new_space_size is not an option in node 4.1.1 and max_old_space_size alone did not solve my problem. I am adding the following to my shebang and the combination of these seems to work:

#!/usr/bin/env node --max_old_space_size=4096 --optimize_for_size --max_executable_size=4096 --stack_size=4096

[EDIT]: 4096 === 4GB of memory, if your device is low on memory you may want to choose a smaller amount.

[UPDATE]: Also discovered this error while running grunt which previously was run like so:

./node_modules/.bin/grunt

After updating the command to the following it stopped having memory errors:

node --max_old_space_size=2048 ./node_modules/.bin/grunt 

How to detect orientation change?

If you want to do something AFTER the rotation is complete, you can use the UIViewControllerTransitionCoordinator completion handler like this

public override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    // Hook in to the rotation animation completion handler
    coordinator.animate(alongsideTransition: nil) { (_) in
        // Updates to your UI...
        self.tableView.reloadData()
    }
}

Convert an object to an XML string

This is my solution, for any list object you can use this code for convert to xml layout. KeyFather is your principal tag and KeySon is where start your Forech.

public string BuildXml<T>(ICollection<T> anyObject, string keyFather, string keySon)
    {
        var settings = new XmlWriterSettings
        {
            Indent = true
        };
        PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
        StringBuilder builder = new StringBuilder();
        using (XmlWriter writer = XmlWriter.Create(builder, settings))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement(keyFather);
            foreach (var objeto in anyObject)
            {
                writer.WriteStartElement(keySon);
                foreach (PropertyDescriptor item in props)
                {
                    writer.WriteStartElement(item.DisplayName);
                    writer.WriteString(props[item.DisplayName].GetValue(objeto).ToString());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }
            writer.WriteFullEndElement();
            writer.WriteEndDocument();
            writer.Flush();
            return builder.ToString();
        }
    }

JavaScript: undefined !== undefined?

var a;

typeof a === 'undefined'; // true
a === undefined; // true
typeof a === typeof undefined; // true
typeof a === typeof sdfuwehflj; // true

How do I get a file extension in PHP?

I found that the pathinfo() and SplFileInfo solutions works well for standard files on the local file system, but you can run into difficulties if you're working with remote files as URLs for valid images may have a # (fragment identifiers) and/or ? (query parameters) at the end of the URL, which both those solutions will (incorrect) treat as part of the file extension.

I found this was a reliable way to use pathinfo() on a URL after first parsing it to strip out the unnecessary clutter after the file extension:

$url_components = parse_url($url); // First parse the URL
$url_path = $url_components['path']; // Then get the path component
$ext = pathinfo($url_path, PATHINFO_EXTENSION); // Then use pathinfo()

In C# check that filename is *possibly* valid (not that it exists)

I don't know of anything out of the box that can just validate all of that for you, however the Path class in .NET can help you out tremendously.

For starters, it has:

char[] invalidChars = Path.GetInvalidFileNameChars(); //returns invalid charachters

or:

Path.GetPathRoot(string); // will return the root.

Reading from file using read() function

fgets would work for you. here is very good documentation on this :-
http://www.cplusplus.com/reference/cstdio/fgets/

If you don't want to use fgets, following method will work for you :-

int readline(FILE *f, char *buffer, size_t len)
{
   char c; 
   int i;

   memset(buffer, 0, len);

   for (i = 0; i < len; i++)
   {   
      int c = fgetc(f); 

      if (!feof(f)) 
      {   
         if (c == '\r')
            buffer[i] = 0;
         else if (c == '\n')
         {   
            buffer[i] = 0;

            return i+1;
         }   
         else
            buffer[i] = c; 
      }   
      else
      {   
         //fprintf(stderr, "read_line(): recv returned %d\n", c);
         return -1; 
      }   
   }   

   return -1; 
}

How to use System.Net.HttpClient to post a complex type?

You should use the SendAsync method instead, this is a generic method, that serializes the input to the service

Widget widget = new Widget()
widget.Name = "test"
widget.Price = 1;

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:44268/api/test");
client.SendAsync(new HttpRequestMessage<Widget>(widget))
    .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode() );

If you don't want to create the concrete class, you can make it with the FormUrlEncodedContent class

var client = new HttpClient();

// This is the postdata
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("Name", "test"));
postData.Add(new KeyValuePair<string, string>("Price ", "100"));

HttpContent content = new FormUrlEncodedContent(postData); 

client.PostAsync("http://localhost:44268/api/test", content).ContinueWith(
    (postTask) =>
    {
        postTask.Result.EnsureSuccessStatusCode();
    });

Note: you need to make your id to a nullable int (int?)

How to set level logging to DEBUG in Tomcat?

Firstly, the level name to use is FINE, not DEBUG. Let's assume for a minute that DEBUG is actually valid, as it makes the following explanation make a bit more sense...

In the Handler specific properties section, you're setting the logging level for those handlers to DEBUG. This means the handlers will handle any log messages with the DEBUG level or higher. It doesn't necessarily mean any DEBUG messages are actually getting passed to the handlers.

In the Facility specific properties section, you're setting the logging level for a few explicitly-named loggers to DEBUG. For those loggers, anything at level DEBUG or above will get passed to the handlers.

The default logging level is INFO, and apart from the loggers mentioned in the Facility specific properties section, all loggers will have that level.

If you want to see all FINE messages, add this:

.level = FINE

However, this will generate a vast quantity of log messages. It's probably more useful to set the logging level for your code:

your.package.level = FINE

See the Tomcat 6/Tomcat 7 logging documentation for more information. The example logging.properties file shown there uses FINE instead of DEBUG:

...
1catalina.org.apache.juli.FileHandler.level = FINE
...

and also gives you examples of setting additional logging levels:

# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE

Get current URL from IFRAME

For security reasons, you can only get the url for as long as the contents of the iframe, and the referencing javascript, are served from the same domain. As long as that is true, something like this will work:

document.getElementById("iframe_id").contentWindow.location.href

If the two domains are mismatched, you'll run into cross site reference scripting security restrictions.

See also answers to a similar question.

Excel VBA, error 438 "object doesn't support this property or method

The Error is here

lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1

wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this

lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
          wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1

Similarly

wsPOR.Range("A2:G" & lastrow).Select

should be

wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select

Call static method with reflection

As the documentation for MethodInfo.Invoke states, the first argument is ignored for static methods so you can just pass null.

foreach (var tempClass in macroClasses)
{
   // using reflection I will be able to run the method as:
   tempClass.GetMethod("Run").Invoke(null, null);
}

As the comment points out, you may want to ensure the method is static when calling GetMethod:

tempClass.GetMethod("Run", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);

How to read a file in reverse order?

I don't think this has been mentioned before, but using deque from collections and reverse works for me:

from collections import deque

fs = open("test.txt","rU")
fr = deque(fs)
fr.reverse()  # reverse in-place, returns None

for li in fr:
   print li

fs.close()