Programs & Examples On #Simd

Single instruction, multiple data (SIMD) is the concept of having each instruction operate on a small chunk or vector of data elements. CPU vector instruction sets include: x86 SSE and AVX, ARM NEON, and PowerPC AltiVec. To efficiently use SIMD instructions, data needs to be in structure-of-arrays form and should occur in longer streams. Naively "SIMD optimized" code frequently surprises by running slower than the original.

How to compile Tensorflow with SSE4.2 and AVX instructions?

When building TensorFlow from source, you'll run the configure script. One of the questions that the configure script asks is as follows:

Please specify optimization flags to use during compilation when bazel option "--config=opt" is specified [Default is -march=native]

The configure script will attach the flag(s) you specify to the bazel command that builds the TensorFlow pip package. Broadly speaking, you can respond to this prompt in one of two ways:

  • If you are building TensorFlow on the same type of CPU type as the one on which you'll run TensorFlow, then you should accept the default (-march=native). This option will optimize the generated code for your machine's CPU type.
  • If you are building TensorFlow on one CPU type but will run TensorFlow on a different CPU type, then consider supplying a more specific optimization flag as described in the gcc documentation.

After configuring TensorFlow as described in the preceding bulleted list, you should be able to build TensorFlow fully optimized for the target CPU just by adding the --config=opt flag to any bazel command you are running.

How to add an extra row to a pandas dataframe

Upcoming pandas 0.13 version will allow to add rows through loc on non existing index data. However, be aware that under the hood, this creates a copy of the entire DataFrame so it is not an efficient operation.

Description is here and this new feature is called Setting With Enlargement.

org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android

i was facing exactly the same issue and i made following changes to my URL after which it was working perfectly fine..

From:

http://localhost/Image4android/get_all_images.php

To:

http://192.168.1.2/Image4android/get_all_images.php

where the ip: 192.168.1.2 is IPv4 address. In windows Run > CMD > Ipconfig

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

Check Inside the Following Directory for the jar file el-api.jar :C:\apache-tomcat-7.0.39\lib\el-api.jar if it exists then in this directory of your web application WEB-INF\lib\el-api.jar the jar should be removed

How can I calculate the number of lines changed between two commits in Git?

git diff --shortstat

gives you just the number of lines changed and added. This only works with unstaged changes. To compare against a branch:

git diff --shortstat some-branch

How to execute logic on Optional if not present?

There is an .orElseRun method, but it is called .orElseGet.

The main problem with your pseudocode is that .isPresent doesn't return an Optional<>. But .map returns an Optional<> which has the orElseRun method.

If you really want to do this in one statement this is possible:

public Optional<Obj> getObjectFromDB() {
    return dao.find()
        .map( obj -> { 
            obj.setAvailable(true);
            return Optional.of(obj); 
         })
        .orElseGet( () -> {
            logger.fatal("Object not available"); 
            return Optional.empty();
    });
}

But this is even clunkier than what you had before.

Restore a deleted file in the Visual Studio Code Recycle Bin

Just look up the files you deleted, inside Recycle Bin. Right click on it and do restore as you do normally with other deleted files. It is similar as you do normally because VS code also uses normal trash of your system.

Simple calculations for working with lat/lon and km distance?

The approximate conversions are:

  • Latitude: 1 deg = 110.574 km
  • Longitude: 1 deg = 111.320*cos(latitude) km

This doesn't fully correct for the Earth's polar flattening - for that you'd probably want a more complicated formula using the WGS84 reference ellipsoid (the model used for GPS). But the error is probably negligible for your purposes.

Source: http://en.wikipedia.org/wiki/Latitude

Caution: Be aware that latlong coordinates are expressed in degrees, while the cos function in most (all?) languages typically accepts radians, therefore a degree to radians conversion is needed.

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

'list' object has no attribute 'shape'

If you have list, you can print its shape as if it is converted to array

import numpy as np
print(np.asarray(X).shape)

Javac is not found

do this: 1. run CMD (WIN+R then type in CMD) 2. Type this:

set PATH=%PATH%; java installation path\bin

Replace "java installation path" with the directory JDK is installed in, such as C:\Program Files (x86)\Java. Be sure to add the \bin after the JDK directory, because this points to "javac" and "java" (BIN stands for "binaries")

This way, you can run the Java compiler from anywhere. It is impossible to CD to the JDK directory because it has a space in Program Files, and DOS will not let you CD to these directories.

jQuery - Getting form values for ajax POST

you can use val function to collect data from inputs:

jQuery("#myInput1").val();

http://api.jquery.com/val/

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

If you have 32-bit Windows, this method is not working without following settings.

  1. Run prompt cmd.exe (important : Run As Administrator)
  2. type bcdedit.exe and run
  3. Look at the "increaseuserva" params and there is no then write following statement
  4. bcdedit /set increaseuserva 3072
  5. and again step 2 and check params

We added this settings and this block started.

if exist "$(DevEnvDir)..\tools\vsvars32.bat" (
   call "$(DevEnvDir)..\tools\vsvars32.bat"
   editbin /largeaddressaware "$(TargetPath)"
)

More info - command increaseuserva: https://docs.microsoft.com/en-us/windows-hardware/drivers/devtest/bcdedit--set

How do I cancel form submission in submit button onclick event?

You need onSubmit. Not onClick otherwise someone can just press enter and it will bypass your validation. As for canceling. you need to return false. Here's the code:

<form onSubmit="return btnClick()">
<input type='submit' value='submit request'>

function btnClick() {
    if (!validData()) return false;
}

Edit onSubmit belongs in the form tag.

connecting MySQL server to NetBeans

I just had the same issue with Netbeans 8.2 and trying to connect to mySQL server on a Mac OS machine. The only thing that worked for me was to add the following to the url of the connection string: &serverTimezone=UTC (or if you are connecting via Hibernate.cfg.xml then escape the & as &) Not surprisingly I found the solution on this stack overflow post also:

MySQL JDBC Driver 5.1.33 - Time Zone Issue

Best Regards, Claudio

Take a char input from the Scanner

you just need to write this for getting value in char type.

char c = reader.next().charAt(0);

PHP cURL, extract an XML response

$sXML = download_page('http://alanstorm.com/atom');
// Comment This    
// $oXML = new SimpleXMLElement($sXML);
// foreach($oXML->entry as $oEntry){
//  echo $oEntry->title . "\n";
// }
// Use json encode
$xml = simplexml_load_string($sXML);
$json = json_encode($xml);
$arr = json_decode($json,true);
print_r($arr);

using jQuery .animate to animate a div from right to left?

I think the reason it doesn't work has something to do with the fact that you have the right position set, but not the left.

If you manually set the left to the current position, it seems to go:

Live example: http://jsfiddle.net/XqqtN/

var left = $('#coolDiv').offset().left;  // Get the calculated left position

$("#coolDiv").css({left:left})  // Set the left to its calculated position
             .animate({"left":"0px"}, "slow");

EDIT:

Appears as though Firefox behaves as expected because its calculated left position is available as the correct value in pixels, whereas Webkit based browsers, and apparently IE, return a value of auto for the left position.

Because auto is not a starting position for an animation, the animation effectively runs from 0 to 0. Not very interesting to watch. :o)

Setting the left position manually before the animate as above fixes the issue.


If you don't like cluttering the landscape with variables, here's a nice version of the same thing that obviates the need for a variable:

$("#coolDiv").css('left', function(){ return $(this).offset().left; })
             .animate({"left":"0px"}, "slow");    ?

Python Graph Library

Also, you might want to take a look at NetworkX

Nth max salary in Oracle

We could write as below mentioned also.

select min(sal) from (select sal from emp where rownum=<&n order by sal desc);

How to properly override clone method?

There are two cases in which the CloneNotSupportedException will be thrown:

  1. The class being cloned does not implemented Cloneable (assuming that the actual cloning eventually defers to Object's clone method). If the class you are writing this method in implements Cloneable, this will never happen (since any sub-classes will inherit it appropriately).
  2. The exception is explicitly thrown by an implementation - this is the recommended way to prevent clonability in a subclass when the superclass is Cloneable.

The latter case cannot occur in your class (as you're directly calling the superclass' method in the try block, even if invoked from a subclass calling super.clone()) and the former should not since your class clearly should implement Cloneable.

Basically, you should log the error for sure, but in this particular instance it will only happen if you mess up your class' definition. Thus treat it like a checked version of NullPointerException (or similar) - it will never be thrown if your code is functional.


In other situations you would need to be prepared for this eventuality - there is no guarantee that a given object is cloneable, so when catching the exception you should take appropriate action depending on this condition (continue with the existing object, take an alternative cloning strategy e.g. serialize-deserialize, throw an IllegalParameterException if your method requires the parameter by cloneable, etc. etc.).

Edit: Though overall I should point out that yes, clone() really is difficult to implement correctly and difficult for callers to know whether the return value will be what they want, doubly so when you consider deep vs shallow clones. It's often better just to avoid the whole thing entirely and use another mechanism.

Check if table exists without using "select from"

You can query the INFORMATION_SCHEMA tables system view:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'testtable';

If no rows returned, then the table doesn't exist.

Count elements with jQuery

Yes, there is.

$('.MyClass').size()

rsync: difference between --size-only and --ignore-times

There are several ways rsync compares files -- the authoritative source is the rsync algorithm description: https://www.andrew.cmu.edu/course/15-749/READINGS/required/cas/tridgell96.pdf. The wikipedia article on rsync is also very good.

For local files, rsync compares metadata and if it looks like it doesn't need to copy the file because size and timestamp match between source and destination it doesn't look further. If they don't match, it cp's the file. However, what if the metadata do match but files aren't actually the same? Then rsync probably didn't do what you intended.

Files that are the same size may still have changed. One simple example is a text file where you correct a typo -- like changing "teh" to "the". The file size is the same, but the corrected file will have a newer timestamp. --size-only says "don't look at the time; if size matches assume files match", which would be the wrong choice in this case.

On the other hand, suppose you accidentally did a big cp -r A B yesterday, but you forgot to preserve the time stamps, and now you want to do the operation in reverse rsync B A. All those files you cp'ed have yesterday's time stamp, even though they weren't really modified yesterday, and rsync will by default end up copying all those files, and updating the timestamp to yesterday too. --size-only may be your friend in this case (modulo the example above).

--ignore-times says to compare the files regardless of whether the files have the same modify time. Consider the typo example above, but then not only did you correct the typo but you used touch to make the corrected file have the same modify time as the original file -- let's just say you're sneaky that way. Well --ignore-times will do a diff of the files even though the size and time match.

Add/delete row from a table

Lots of good answers, but here is one more ;)

You can add handler for the click to the table

<table id = 'dsTable' onclick="tableclick(event)">

And then just find out what the target of the event was

function tableclick(e) {
    if(!e)
     e = window.event;

    if(e.target.value == "Delete")
       deleteRow( e.target.parentNode.parentNode.rowIndex );
}

Then you don't have to add event handlers for each row and your html looks neater. If you don't want any javascript in your html you can even add the handler when page loads:

document.getElementById('dsTable').addEventListener('click',tableclick,false);

??

Here is working code: http://jsfiddle.net/hX4f4/2/

How to get all the values of input array element jquery

Use:

function getvalues(){
var inps = document.getElementsByName('pname[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
    alert("pname["+i+"].value="+inp.value);
}
}

Here is Demo.

Installing tkinter on ubuntu 14.04

In Ubuntu 14.04.2 LTS:

  1. Go to Software Center and remove "IDLE(using Python-2.7)".

  2. Install "IDLE(using Python-3.4)".

Try again. This step worked for me.

How to pass data to all views in Laravel 5?

You have two options:

1. Share via ?Boot function in App\Providers\AppServiceProvider:

public function boot()
{
  view()->share('key', 'value');
}

And access $key variable in any view file.

Note: Remember that you can't access current Session, Auth, Route data here. This option is good only if you want to share static data. Suppose you want to share some data based on the current user , route, or any custom session variable you won't be able to do with this.

2. Use of a helper class:

Create a helper class anywhere in your application and register it in Alias array in app.php file in config folder.

 'aliases' => [ 
   ...,
  'Helper' => App\HelperClass\Helper::class,
 ],

and create Helper.php in HelperClass folder within App folder:

namespace App\HelperClass;
    
class Helper
{
    public static function Sample()
    {
        //Your Code Here
    }
}

and access it anywhere like Helper::Sample().

You will not be restricted here to use Auth, Route, Session, or any other classes.

How to upload image in CodeIgniter?

Below code for an uploading a single file at a time. This is correct and perfect to upload a single file. Read all commented instructions and follow the code. Definitely, it is worked.

public function upload_file() {
    ***// Upload folder location***
    $config['upload_path'] = './public/upload/';

    ***// Allowed file type***
    $config['allowed_types'] = 'jpg|jpeg|png|pdf';

    ***// Max size, i will set 2MB***
    $config['max_size'] = '2024';

    $config['max_width'] = '1024';
    $config['max_height'] = '768';

    ***// load upload library***            
    $this->load->library('upload', $config);

    ***// do_upload is the method, to send the particular image and file on that 
       // particular 
       // location that is detail in $config['upload_path']. 
       // In bracks will set name upload, here you need to set input name attribute 
       // value.***

    if($this->upload->do_upload('upload')) {
       $data = $this->upload->data();
       $post['upload'] = $data['file_name'];
    } else {
      $error = array('error' => $this->upload->display_errors());
    }
 }

Non-static method requires a target

I've found this issue to be prevalent in Entity Framework when we instantiate an Entity manually rather than through DBContext which will resolve all the Navigation Properties. If there are Foreign Key references (Navigation Properties) between tables and you use those references in your lambda (e.g. ProductDetail.Products.ID) then that "Products" context remains null if you manually created the Entity.

Dynamically creating keys in a JavaScript associative array

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// Show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

This is ok, but it iterates through every property of the array object.

If you want to only iterate through the properties myArray.one, myArray.two... you try like this:

myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
myArray.push("one");
myArray.push("two");
myArray.push("three");
for(var i=0;i<maArray.length;i++){
    console.log(myArray[myArray[i]])
}

Now you can access both by myArray["one"] and iterate only through these properties.

GIT commit as different user without email / or only email

The --author option doesn't work:

*** Please tell me who you are.

Run

  git config --global user.email "[email protected]"
  git config --global user.name "Your Name"

This does:

git -c user.name='A U Thor' -c [email protected] commit

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

  1. Step 1: Select all your aspx code, Cut [ CTRL+X ] that code and Save.

  2. Step 2: Again paste the same code in the same page and save again

Now your .desinger page will refresh with all controls in .aspx page.

Open a URL in a new tab (and not a new window)

I think that you can't control this. If the user had setup their browser to open links in a new window, you can't force this to open links in a new tab.

JavaScript open in a new window, not tab

Concatenate two string literals

Since C++14 you can use two real string literals:

const string hello = "Hello"s;

const string message = hello + ",world"s + "!"s;

or

const string exclam = "!"s;

const string message = "Hello"s + ",world"s + exclam;

React won't load local images

you must import the image first then use it. It worked for me.


import image from '../image.png'

const Header = () => {
   return (
     <img src={image} alt='image' />
   )
}


How can I get the data type of a variable in C#?

There is an important and subtle issue that none of them addresses directly. There are two ways of considering type in C#: static type and run-time type.

Static type is the type of a variable in your source code. It is therefore a compile-time concept. This is the type that you see in a tooltip when you hover over a variable or property in your development environment.

You can obtain static type by writing helper generic method to let type inference take care of it for you:

   Type GetStaticType<T>(T x) { return typeof(T); }

Run-time type is the type of an object in memory. It is therefore a run-time concept. This is the type returned by the GetType() method.

An object's run-time type is frequently different from the static type of the variable, property, or method that holds or returns it. For example, you can have code like this:

object o = "Some string";

The static type of the variable is object, but at run time, the type of the variable's referent is string. Therefore, the next line will print "System.String" to the console:

Console.WriteLine(o.GetType()); // prints System.String

But, if you hover over the variable o in your development environment, you'll see the type System.Object (or the equivalent object keyword). You also see the same using our helper function from above:

Console.WriteLine(GetStaticType(o)); // prints System.Object

For value-type variables, such as int, double, System.Guid, you know that the run-time type will always be the same as the static type, because value types cannot serve as the base class for another type; the value type is guaranteed to be the most-derived type in its inheritance chain. This is also true for sealed reference types: if the static type is a sealed reference type, the run-time value must either be an instance of that type or null.

Conversely, if the static type of the variable is an abstract type, then it is guaranteed that the static type and the runtime type will be different.

To illustrate that in code:

// int is a value type
int i = 0;
// Prints True for any value of i
Console.WriteLine(i.GetType() == typeof(int));

// string is a sealed reference type
string s = "Foo";
// Prints True for any value of s
Console.WriteLine(s == null || s.GetType() == typeof(string));

// object is an unsealed reference type
object o = new FileInfo("C:\\f.txt");
// Prints False, but could be true for some values of o
Console.WriteLine(o == null || o.GetType() == typeof(object));

// FileSystemInfo is an abstract type
FileSystemInfo fsi = new DirectoryInfo("C:\\");
// Prints False for all non-null values of fsi
Console.WriteLine(fsi == null || fsi.GetType() == typeof(FileSystemInfo));

Failed to resolve: com.google.firebase:firebase-core:16.0.1

As @Peter Haddad mentioned above,

To fix this issue I followed Google firebase integration guidelines and did the following changes in my app/build.gradle and project/build.gradle

Follow below mentioned link if you have any doubts

https://firebase.google.com/docs/android/setup

changes in app/build.gradle

_x000D_
_x000D_
implementation 'com.google.android.gms:play-services-base:15.0.2'_x000D_
implementation "com.google.firebase:firebase-core:16.0.1"_x000D_
implementation "com.google.firebase:firebase-messaging:17.4.0"
_x000D_
_x000D_
_x000D_

Changes in Project/build.gradle

_x000D_
_x000D_
repositories {_x000D_
_x000D_
        google()_x000D_
        jcenter()_x000D_
        mavenCentral()_x000D_
        maven {_x000D_
            url 'https://maven.fabric.io/public'_x000D_
        }_x000D_
    }_x000D_
    dependencies {_x000D_
        classpath 'com.android.tools.build:gradle:3.1.4'_x000D_
        classpath 'com.google.gms:google-services:4.2.0'// // google-services plugin it should be latest if you are using firebase version 16.0 +_x000D_
       _x000D_
    }_x000D_
    allprojects {_x000D_
    repositories {_x000D_
         google()// add it to top instead of bottom or somewhere in middle_x000D_
        mavenLocal()_x000D_
        mavenCentral()_x000D_
        maven {_x000D_
            url 'https://maven.google.com'_x000D_
        }_x000D_
       _x000D_
        jcenter()_x000D_
        maven {_x000D_
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm_x000D_
            url "$rootDir/../node_modules/react-native/android"_x000D_
        }_x000D_
        _x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

C# MessageBox dialog result

Rather than using if statements might I suggest using a switch instead, I try to avoid using if statements when possible.

var result = MessageBox.Show(@"Do you want to save the changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
switch (result)
{
    case DialogResult.Yes:
        SaveChanges();
        break;
    case DialogResult.No:
        Rollback();
        break;
    default:
        break;
}

How to get an Instagram Access Token

go to manage clinet page in :

http://www.instagram.com/developer/

set a redirect url

then :

use this code to get access token :

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>tst</title>
<script src="../jq.js"></script>
<script type="text/javascript">
       $.ajax({
            type: 'GET',
            url: 'https://api.instagram.com/oauth/authorize/?client_id=CLIENT-??ID&redirect_uri=REDI?RECT-URI&response_ty?pe=code'
            dataType: 'jsonp'}).done(function(response){
                var access = window.location.hash.substring(14);
                //you have access token in access var   
            });
</script>
</head>
<body>  
</body>
</html>

How to obtain values of request variables using Python and Flask

If you want to retrieve POST data:

first_name = request.form.get("firstname")

If you want to retrieve GET (query string) data:

first_name = request.args.get("firstname")

Or if you don't care/know whether the value is in the query string or in the post data:

first_name = request.values.get("firstname") 

request.values is a CombinedMultiDict that combines Dicts from request.form and request.args.

Google Geocoding API - REQUEST_DENIED

I got this problem as well using the drupal 7 Location module. Autofilling all empty locations resulted in this error. Executing one of the requests to the location api manually resulted in this error in the returned JSON:

"Browser API keys cannot have referer restrictions when used with this API."

Resolving the problem then was easy: create a new key without any restrictions and use it only for Geocoding.

Note for those new to google api keys: by restrictions they mean limiting requests using an api key to specific domains / subdomains. (eg. only request from http://yourdomain.com are allowed).

find index of an int in a list

List<string> accountList = new List<string> {"123872", "987653" , "7625019", "028401"};

int i = accountList.FindIndex(x => x.StartsWith("762"));
//This will give you index of 7625019 in list that is 2. value of i will become 2.
//delegate(string ac)
//{
//    return ac.StartsWith(a.AccountNumber);
//}
//);

Forbidden :You don't have permission to access /phpmyadmin on this server

Centos 7 php install comes with the ModSecurity package installed and enabled which prevents web access to phpMyAdmin. At the end of phpMyAdmin.conf, you should find

# This configuration prevents mod_security at phpMyAdmin directories from
# filtering SQL etc.  This may break your mod_security implementation.
#
#<IfModule mod_security.c>
#    <Directory /usr/share/phpMyAdmin/>
#        SecRuleInheritance Off
#    </Directory>
#</IfModule>

which gives you the answer to the problem. By adding

    SecRuleEngine Off

in the block "Directory /usr/share/phpMyAdmin/", you can solve the 'denied access' to phpmyadmin, but you may create security issues.

Set The Window Position of an application via command line

If you are happy to run a batch file along with a couple of tiny helper programs, a complete solution is posted here:
How can a batch file run a program and set the position and size of the window? - Stack Overflow (asked: May 1, 2012)

C++ terminate called without an active exception

First you define a thread. And if you never call join() or detach() before calling the thread destructor, the program will abort.

As follows, calling a thread destructor without first calling join (to wait for it to finish) or detach is guarenteed to immediately call std::terminate and end the program.

Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed while the thread is still joinable.

keytool error Keystore was tampered with, or password was incorrect

Summarizing the advices from this page, I finished up with the following:

keytool -genkeypair -keystore ~/.android/release.keystore -alias <my_alias> -storepass <my_cert_pass> -keyalg RSA

Then I got a set of questions regarding name, organization, location and password for my alias.

Change Timezone in Lumen or Laravel 5

Please try this - Create a directory 'config' in your lumen setup, and then create app.php file inside this 'config' dir. it will look like this -

<?php return ['app.timezone' => 'America/Los_Angeles'];

Then you can access its value anywhere like this -

$value = config('app.timezone');

If it doesn't work, you can add this lines in routes.php

date_default_timezone_set('America/Los_Angeles');

This worked for me!

Docker error: invalid reference format: repository name must be lowercase

Docker can build images automatically by reading the instructions from a Dockerfile. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. example: FROM python:3.7-alpine The 'python' should be in lowercase

JAVA_HOME is set to an invalid directory:

You should set it with C:\Program Files\Java\jdk1.8.0_12.

\bin is not required.

Calculate mean across dimension in a 2D array

If you do this a lot, NumPy is the way to go.

If for some reason you can't use NumPy:

>>> map(lambda x:sum(x)/float(len(x)), zip(*a))
[45.0, 10.5]

center image in div with overflow hidden

you the have to corp your image from sides to hide it try this

3 Easy and Fast CSS Techniques for Faux Image Cropping | Css ...

one of the demo for the first way on the site above

try demo

i will do some reading on it too

C++ display stack trace on exception

I would like to add a standard library option (i.e. cross-platform) how to generate exception backtraces, which has become available with C++11:

Use std::nested_exception and std::throw_with_nested

This won't give you a stack unwind, but in my opinion the next best thing. It is described on StackOverflow here and here, how you can get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions.

Since you can do this with any derived exception class, you can add a lot of information to such a backtrace! You may also take a look at my MWE on GitHub, where a backtrace would look something like this:

Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"

How to change JAVA.HOME for Eclipse/ANT

Simply, to enforce JAVA version to Ant in Eclipse:

Use RunAs option on Ant file then select External Tool Configuration in JRE tab define your JDK/JRE version you want to use.

Convert MySql DateTime stamp into JavaScript's Date format

From Andy's Answer, For AngularJS - Filter

angular
    .module('utils', [])
.filter('mysqlToJS', function () {
            return function (mysqlStr) {
                var t, result = null;

                if (typeof mysqlStr === 'string') {
                    t = mysqlStr.split(/[- :]/);

                    //when t[3], t[4] and t[5] are missing they defaults to zero
                    result = new Date(t[0], t[1] - 1, t[2], t[3] || 0, t[4] || 0, t[5] || 0);
                }

                return result;
            };
        });

Find current directory and file's directory

If you're searching for the location of the currently executed script, you can use sys.argv[0] to get the full path.

Omitting all xsi and xsd namespaces when serializing an object in .NET?

This is the 2nd of two answers.

If you want to just strip all namespaces arbitrarily from a document during serialization, you can do this by implementing your own XmlWriter.

The easiest way is to derive from XmlTextWriter and override the StartElement method that emits namespaces. The StartElement method is invoked by the XmlSerializer when emitting any elements, including the root. By overriding the namespace for each element, and replacing it with the empty string, you've stripped the namespaces from the output.

public class NoNamespaceXmlWriter : XmlTextWriter
{
    //Provide as many contructors as you need
    public NoNamespaceXmlWriter(System.IO.TextWriter output)
        : base(output) { Formatting= System.Xml.Formatting.Indented;}

    public override void WriteStartDocument () { }

    public override void WriteStartElement(string prefix, string localName, string ns)
    {
        base.WriteStartElement("", localName, "");
    }
}

Suppose this is the type:

// explicitly specify a namespace for this type,
// to be used during XML serialization.
[XmlRoot(Namespace="urn:Abracadabra")]
public class MyTypeWithNamespaces
{
    // private fields backing the properties
    private int _Epoch;
    private string _Label;

    // explicitly define a distinct namespace for this element
    [XmlElement(Namespace="urn:Whoohoo")]
    public string Label
    {
        set {  _Label= value; } 
        get { return _Label; } 
    }

    // this property will be implicitly serialized to XML using the
    // member name for the element name, and inheriting the namespace from
    // the type.
    public int Epoch
    {
        set {  _Epoch= value; } 
        get { return _Epoch; } 
    }
}

Here's how you would use such a thing during serialization:

        var o2= new MyTypeWithNamespaces { ..intializers.. };
        var builder = new System.Text.StringBuilder();
        using ( XmlWriter writer = new NoNamespaceXmlWriter(new System.IO.StringWriter(builder)))
        {
            s2.Serialize(writer, o2, ns2);
        }            
        Console.WriteLine("{0}",builder.ToString());

The XmlTextWriter is sort of broken, though. According to the reference doc, when it writes it does not check for the following:

  • Invalid characters in attribute and element names.

  • Unicode characters that do not fit the specified encoding. If the Unicode characters do not fit the specified encoding, the XmlTextWriter does not escape the Unicode characters into character entities.

  • Duplicate attributes.

  • Characters in the DOCTYPE public identifier or system identifier.

These problems with XmlTextWriter have been around since v1.1 of the .NET Framework, and they will remain, for backward compatibility. If you have no concerns about those problems, then by all means use the XmlTextWriter. But most people would like a bit more reliability.

To get that, while still suppressing namespaces during serialization, instead of deriving from XmlTextWriter, define a concrete implementation of the abstract XmlWriter and its 24 methods.

An example is here:

public class XmlWriterWrapper : XmlWriter
{
    protected XmlWriter writer;

    public XmlWriterWrapper(XmlWriter baseWriter)
    {
        this.Writer = baseWriter;
    }

    public override void Close()
    {
        this.writer.Close();
    }

    protected override void Dispose(bool disposing)
    {
        ((IDisposable) this.writer).Dispose();
    }

    public override void Flush()
    {
        this.writer.Flush();
    }

    public override string LookupPrefix(string ns)
    {
        return this.writer.LookupPrefix(ns);
    }

    public override void WriteBase64(byte[] buffer, int index, int count)
    {
        this.writer.WriteBase64(buffer, index, count);
    }

    public override void WriteCData(string text)
    {
        this.writer.WriteCData(text);
    }

    public override void WriteCharEntity(char ch)
    {
        this.writer.WriteCharEntity(ch);
    }

    public override void WriteChars(char[] buffer, int index, int count)
    {
        this.writer.WriteChars(buffer, index, count);
    }

    public override void WriteComment(string text)
    {
        this.writer.WriteComment(text);
    }

    public override void WriteDocType(string name, string pubid, string sysid, string subset)
    {
        this.writer.WriteDocType(name, pubid, sysid, subset);
    }

    public override void WriteEndAttribute()
    {
        this.writer.WriteEndAttribute();
    }

    public override void WriteEndDocument()
    {
        this.writer.WriteEndDocument();
    }

    public override void WriteEndElement()
    {
        this.writer.WriteEndElement();
    }

    public override void WriteEntityRef(string name)
    {
        this.writer.WriteEntityRef(name);
    }

    public override void WriteFullEndElement()
    {
        this.writer.WriteFullEndElement();
    }

    public override void WriteProcessingInstruction(string name, string text)
    {
        this.writer.WriteProcessingInstruction(name, text);
    }

    public override void WriteRaw(string data)
    {
        this.writer.WriteRaw(data);
    }

    public override void WriteRaw(char[] buffer, int index, int count)
    {
        this.writer.WriteRaw(buffer, index, count);
    }

    public override void WriteStartAttribute(string prefix, string localName, string ns)
    {
        this.writer.WriteStartAttribute(prefix, localName, ns);
    }

    public override void WriteStartDocument()
    {
        this.writer.WriteStartDocument();
    }

    public override void WriteStartDocument(bool standalone)
    {
        this.writer.WriteStartDocument(standalone);
    }

    public override void WriteStartElement(string prefix, string localName, string ns)
    {
        this.writer.WriteStartElement(prefix, localName, ns);
    }

    public override void WriteString(string text)
    {
        this.writer.WriteString(text);
    }

    public override void WriteSurrogateCharEntity(char lowChar, char highChar)
    {
        this.writer.WriteSurrogateCharEntity(lowChar, highChar);
    }

    public override void WriteValue(bool value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteValue(DateTime value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteValue(decimal value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteValue(double value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteValue(int value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteValue(long value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteValue(object value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteValue(float value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteValue(string value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteWhitespace(string ws)
    {
        this.writer.WriteWhitespace(ws);
    }


    public override XmlWriterSettings Settings
    {
        get
        {
            return this.writer.Settings;
        }
    }

    protected XmlWriter Writer
    {
        get
        {
            return this.writer;
        }
        set
        {
            this.writer = value;
        }
    }

    public override System.Xml.WriteState WriteState
    {
        get
        {
            return this.writer.WriteState;
        }
    }

    public override string XmlLang
    {
        get
        {
            return this.writer.XmlLang;
        }
    }

    public override System.Xml.XmlSpace XmlSpace
    {
        get
        {
            return this.writer.XmlSpace;
        }
    }        
}

Then, provide a derived class that overrides the StartElement method, as before:

public class NamespaceSupressingXmlWriter : XmlWriterWrapper
{
    //Provide as many contructors as you need
    public NamespaceSupressingXmlWriter(System.IO.TextWriter output)
        : base(XmlWriter.Create(output)) { }

    public NamespaceSupressingXmlWriter(XmlWriter output)
        : base(XmlWriter.Create(output)) { }

    public override void WriteStartElement(string prefix, string localName, string ns)
    {
        base.WriteStartElement("", localName, "");
    }
}

And then use this writer like so:

        var o2= new MyTypeWithNamespaces { ..intializers.. };
        var builder = new System.Text.StringBuilder();
        var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent= true };
        using ( XmlWriter innerWriter = XmlWriter.Create(builder, settings))
            using ( XmlWriter writer = new NamespaceSupressingXmlWriter(innerWriter))
            {
                s2.Serialize(writer, o2, ns2);
            }            
        Console.WriteLine("{0}",builder.ToString());

Credit for this to Oleg Tkachenko.

Python PDF library

Reportlab. There is an open source version, and a paid version which adds the Report Markup Language (an alternative method of defining your document).

Why are the Level.FINE logging messages not showing?

why is my java logging not working

provides a jar file that will help you work out why your logging in not working as expected. It gives you a complete dump of what loggers and handlers have been installed and what levels are set and at which level in the logging hierarchy.

Limiting the number of characters in a JTextField

public void Letters(JTextField a) {
    a.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(java.awt.event.KeyEvent e) {
            char c = e.getKeyChar();
            if (Character.isDigit(c)) {
                e.consume();
            }
            if (Character.isLetter(c)) {
                e.setKeyChar(Character.toUpperCase(c));
            }
        }
    });
}

public void Numbers(JTextField a) {
    a.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(java.awt.event.KeyEvent e) {
            char c = e.getKeyChar();
            if (!Character.isDigit(c)) {
                e.consume();
            }
        }
    });
}

public void Caracters(final JTextField a, final int lim) {
    a.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(java.awt.event.KeyEvent ke) {
            if (a.getText().length() == lim) {
                ke.consume();
            }
        }
    });
}

Sorting int array in descending order

    Comparator<Integer> comparator = new Comparator<Integer>() {

        @Override
        public int compare(Integer o1, Integer o2) {
            return o2.compareTo(o1);
        }
    };

    // option 1
    Integer[] array = new Integer[] { 1, 24, 4, 4, 345 };
    Arrays.sort(array, comparator);

    // option 2
    int[] array2 = new int[] { 1, 24, 4, 4, 345 };
    List<Integer>list = Ints.asList(array2);
    Collections.sort(list, comparator);
    array2 = Ints.toArray(list);

Is Python interpreted, or compiled, or both?

First off, interpreted/compiled is not a property of the language but a property of the implementation. For most languages, most if not all implementations fall in one category, so one might save a few words saying the language is interpreted/compiled too, but it's still an important distinction, both because it aids understanding and because there are quite a few languages with usable implementations of both kinds (mostly in the realm of functional languages, see Haskell and ML). In addition, there are C interpreters and projects that attempt to compile a subset of Python to C or C++ code (and subsequently to machine code).

Second, compilation is not restricted to ahead-of-time compilation to native machine code. A compiler is, more generally, a program that converts a program in one programming language into a program in another programming language (arguably, you can even have a compiler with the same input and output language if significant transformations are applied). And JIT compilers compile to native machine code at runtime, which can give speed very close to or even better than ahead of time compilation (depending on the benchmark and the quality of the implementations compared).

But to stop nitpicking and answer the question you meant to ask: Practically (read: using a somewhat popular and mature implementation), Python is compiled. Not compiled to machine code ahead of time (i.e. "compiled" by the restricted and wrong, but alas common definition), "only" compiled to bytecode, but it's still compilation with at least some of the benefits. For example, the statement a = b.c() is compiled to a byte stream which, when "disassembled", looks somewhat like load 0 (b); load_str 'c'; get_attr; call_function 0; store 1 (a). This is a simplification, it's actually less readable and a bit more low-level - you can experiment with the standard library dis module and see what the real deal looks like. Interpreting this is faster than interpreting from a higher-level representation.

That bytecode is either interpreted (note that there's a difference, both in theory and in practical performance, between interpreting directly and first compiling to some intermediate representation and interpret that), as with the reference implementation (CPython), or both interpreted and compiled to optimized machine code at runtime, as with PyPy.

python: changing row index of pandas data frame

you can do

followers_df.index = range(20)

Write HTML to string

You could use some third party open-source libraries to generated strong typed verified (X)HTML, such as CityLizard Framework or Sharp DOM.

Update For example

html
    [head
        [title["Title of the page"]]
        [meta_(
            content: "text/html;charset=UTF-8",
            http_equiv: "Content-Type")
        ]
        [link_(href: "css/style.css", rel: "stylesheet", type: "text/css")]
        [script_(type: "text/javascript", src: "/JavaScript/jquery-1.4.2.min.js")]
    ]
    [body
        [div
            [h1["Test Form to Test"]]
            [form_(action: "post", id: "Form1")
                [div
                    [label["Parameter"]]
                    [input_(type: "text", value: "Enter value")]
                    [input_(type: "submit", value: "Submit!")]
                ]
            ]
            [div
                [p["Textual description of the footer"]]
                [a_(href: "http://google.com/")
                    [span["You can find us here"]]
                ]
                [div["Another nested container"]]
            ]
        ]
    ];

Check if an array contains duplicate values

let arr = [11,22,11,22];

let hasDuplicate = arr.some((val, i) => arr.indexOf(val) !== i);
// hasDuplicate = true

True -> array has duplicates

False -> uniqe array

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

While you are in debug mode within the catch {...} block open up the "QuickWatch" window (ctrl+alt+q) and paste in there:

((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors

or:

((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors

If you are not in a try/catch or don't have access to the exception object.

This will allow you to drill down into the ValidationErrors tree. It's the easiest way I've found to get instant insight into these errors.

How to repair a serialized string which has been corrupted by an incorrect byte count length?

Another reason of this problem can be column type of "payload" sessions table. If you have huge data on session, a text column wouldn't be enough. You will need MEDIUMTEXT or even LONGTEXT.

How can I check for Python version in a program that uses new language features?

Probably the best way to do do this version comparison is to use the sys.hexversion. This is important because comparing version tuples will not give you the desired result in all python versions.

import sys
if sys.hexversion < 0x02060000:
    print "yep!"
else:
    print "oops!"

Capturing TAB key in text box

The previous answer is fine, but I'm one of those guys that's firmly against mixing behavior with presentation (putting JavaScript in my HTML) so I prefer to put my event handling logic in my JavaScript files. Additionally, not all browsers implement event (or e) the same way. You may want to do a check prior to running any logic:

document.onkeydown = TabExample;

function TabExample(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var tabKey = 9;
  if(evt.keyCode == tabKey) {
    // do work
  }
}

Where do I find the line number in the Xcode editor?

If you don't want line numbers shown all the time another way to find the line number of a piece of code is to just click in the left-most margin and create a breakpoint (a small blue arrow appears) then go to the breakpoint navigator (?7) where it will list the breakpoint with its line number. You can delete the breakpoint by right clicking on it.

How to test that a registered variable is not empty?

(ansible 2.9.6 ansible-lint 4.2.0)

See ansible-lint default rules. The condition below causes E602 Don’t compare to empty string

    when: test_myscript.stderr != ""

Correct syntax and also "Ansible Galaxy Warning-Free" option is

    when: test_myscript.stderr | length > 0

Quoting from source code

"Use when: var|length > 0 rather than when: var != "" (or ' 'conversely when: var|length == 0 rather than when: var == "")"


Notes

  1. Test empty bare variable e.g.
    - debug:
        msg: "Empty string '{{ var }}' evaluates to False"
      when: not var
      vars:
        var: ''

    - debug:
        msg: "Empty list {{ var }} evaluates to False"
      when: not var
      vars:
        var: []

give

    "msg": "Empty string '' evaluates to False"
    "msg": "Empty list [] evaluates to False"
  1. But, testing non-empty bare variable string depends on CONDITIONAL_BARE_VARS. Setting ANSIBLE_CONDITIONAL_BARE_VARS=false the condition works fine but setting ANSIBLE_CONDITIONAL_BARE_VARS=true the condition will fail
    - debug:
        msg: "String '{{ var }}' evaluates to True"
      when: var
      vars:
        var: 'abc'

gives

fatal: [localhost]: FAILED! => 
  msg: |-
    The conditional check 'var' failed. The error was: error while 
    evaluating conditional (var): 'abc' is undefined

Explicit cast to Boolean prevents the error but evaluates to False i.e. will be always skipped (unless var='True'). When the filter bool is used the options ANSIBLE_CONDITIONAL_BARE_VARS=true and ANSIBLE_CONDITIONAL_BARE_VARS=false have no effect

    - debug:
        msg: "String '{{ var }}' evaluates to True"
      when: var|bool
      vars:
        var: 'abc'

gives

skipping: [localhost]
  1. Quoting from Porting guide 2.8 Bare variables in conditionals
  - include_tasks: teardown.yml
    when: teardown

  - include_tasks: provision.yml
    when: not teardown

" based on a variable you define as a string (with quotation marks around it):"

  • In Ansible 2.7 and earlier, the two conditions above evaluated as True and False respectively if teardown: 'true'

  • In Ansible 2.7 and earlier, both conditions evaluated as False if teardown: 'false'

  • In Ansible 2.8 and later, you have the option of disabling conditional bare variables, so when: teardown always evaluates as True and when: not teardown always evaluates as False when teardown is a non-empty string (including 'true' or 'false')

  1. Quoting from CONDITIONAL_BARE_VARS

"Expect that this setting eventually will be deprecated after 2.12"

What does from __future__ import absolute_import actually do?

The difference between absolute and relative imports come into play only when you import a module from a package and that module imports an other submodule from that package. See the difference:

$ mkdir pkg
$ touch pkg/__init__.py
$ touch pkg/string.py
$ echo 'import string;print(string.ascii_uppercase)' > pkg/main1.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pkg/main1.py", line 1, in <module>
    import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
>>> 
$ echo 'from __future__ import absolute_import;import string;print(string.ascii_uppercase)' > pkg/main2.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 

In particular:

$ python2 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 1, in <module>
    from __future__ import absolute_import;import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 
$ python2 -m pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Note that python2 pkg/main2.py has a different behaviour then launching python2 and then importing pkg.main2 (which is equivalent to using the -m switch).

If you ever want to run a submodule of a package always use the -m switch which prevents the interpreter for chaining the sys.path list and correctly handles the semantics of the submodule.

Also, I much prefer using explicit relative imports for package submodules since they provide more semantics and better error messages in case of failure.

Does Notepad++ show all hidden characters?

Yes, and unfortunately you cannot turn them off, or any other special characters. The options under \View\Show Symbols only turns on or off things like tabs, spaces, EOL, etc. So if you want to read some obscure coding with text in it - you actually need to look elsewhere. I also looked at changing the coding, ASCII is not listed, and that would not make the mess invisible anyway.

Percentage width in a RelativeLayout

Interestingly enough, building on the answer from @olefevre, one can not only do 50/50 layouts with "invisible struts", but all sorts of layouts involving powers of two.

For example, here is a layout that cuts the width into four equal parts (actually three, with weights of 1, 1, 2):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <View
        android:id="@+id/strut"
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:background="#000000" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/strut" >

        <View
            android:id="@+id/left_strut"
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:layout_toLeftOf="@+id/strut"
            android:layout_centerHorizontal="true"
            android:background="#000000" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignRight="@+id/left_strut"
            android:text="Far Left" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_toRightOf="@+id/left_strut"
            android:text="Near Left" />
    </RelativeLayout>

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/strut"
            android:layout_alignParentRight="true"
            android:text="Right" />

</RelativeLayout>

Find the IP address of the client in an SSH session

Improving on a prior answer. Gives ip address instead of hostname. --ips not available on OS X.

who am i --ips|awk '{print $5}' #ubuntu 14

more universal, change $5 to $6 for OS X 10.11:

WORKSTATION=`who -m|awk '{print $5}'|sed 's/[()]//g'`
WORKSTATION_IP=`dig +short $WORKSTATION`
if [[ -z "$WORKSTATION_IP" ]]; then WORKSTATION_IP="$WORKSTATION"; fi
echo $WORKSTATION_IP

How do I add python3 kernel to jupyter (IPython)

On Ubuntu 14.04 I had to use a combination of previous answers.

First, install pip3 apt-get install python-pip3

Then with pip3 install jupyter pip3 install jupyter

Then using ipython3 install the kernel ipython3 kernel install

Return 0 if field is null in MySQL

You can use coalesce(column_name,0) instead of just column_name. The coalesce function returns the first non-NULL value in the list.

I should mention that per-row functions like this are usually problematic for scalability. If you think your database may get to be a decent size, it's often better to use extra columns and triggers to move the cost from the select to the insert/update.

This amortises the cost assuming your database is read more often than written (and most of them are).

JOptionPane Yes or No window

Something along these lines ....

   //default icon, custom title
int n = JOptionPane.showConfirmDialog(null,"Would you like green eggs and ham?","An Inane Question",JOptionPane.YES_NO_OPTION);

String result = "?";
switch (n) {
case JOptionPane.YES_OPTION:
  result = "YES";
  break;
case JOptionPane.NO_OPTION:
  result = "NO";
  break;
default:
  ;
}
System.out.println("Replace? " + result);

you may also want to look at DialogDemo

How do I measure separate CPU core usage for a process?

I thought perf stat is what you need.

It shows a specific usage of a process when you specify a --cpu=list option. Here is an example of monitoring cpu usage of building a project using perf stat --cpu=0-7 --no-aggr -- make all -j command. The output is:

CPU0         119254.719293 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU1         119254.724776 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU2         119254.724179 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU3         119254.720833 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU4         119254.714109 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU5         119254.727721 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU6         119254.723447 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU7         119254.722418 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU0                 8,108 context-switches          #    0.068 K/sec                    (100.00%)
CPU1                26,494 context-switches                                              (100.00%)
CPU2                10,193 context-switches                                              (100.00%)
CPU3                12,298 context-switches                                              (100.00%)
CPU4                16,179 context-switches                                              (100.00%)
CPU5                57,389 context-switches                                              (100.00%)
CPU6                 8,485 context-switches                                              (100.00%)
CPU7                10,845 context-switches                                              (100.00%)
CPU0                   167 cpu-migrations            #    0.001 K/sec                    (100.00%)
CPU1                    80 cpu-migrations                                                (100.00%)
CPU2                   165 cpu-migrations                                                (100.00%)
CPU3                   139 cpu-migrations                                                (100.00%)
CPU4                   136 cpu-migrations                                                (100.00%)
CPU5                   175 cpu-migrations                                                (100.00%)
CPU6                   256 cpu-migrations                                                (100.00%)
CPU7                   195 cpu-migrations                                                (100.00%)

The left column is the specific CPU index and the right most column is the usage of the CPU. If you don't specify the --no-aggr option, the result will aggregated together. The --pid=pid option will help if you want to monitor a running process.

Try -a --per-core or -a perf-socket too, which will present more classified information.

More about usage of perf stat can be seen in this tutorial: perf cpu statistic, also perf help stat will help on the meaning of the options.

Keyboard shortcut to comment lines in Sublime Text 2

First Open The Sublime Text 2.

And top menu bar on select the Preferences.

And than select the Key Bindings -User.

And than put this code,

[
    { "keys": ["ctrl+shift+c"], "command": "toggle_comment", "args": { "block": false } },

    { "keys": ["ctrl+shift+c"], "command": "toggle_comment", "args": { "block": true } }
]

I use Ctrl+Shift+C, You also different short cut key use.

Rails Model find where not equal

Rails 4

GroupUser.where.not(user_id: me)

How to iterate a loop with index and element in Swift

For those who want to use forEach.

Swift 4

extension Array {
  func forEachWithIndex(_ body: (Int, Element) throws -> Void) rethrows {
    try zip((startIndex ..< endIndex), self).forEach(body)
  }
}

Or

array.enumerated().forEach { ... }

How can I hide select options with JavaScript? (Cross browser)

Try this:

$(".hide").css("display","none");

But I think it doesn't make sense to hide it. if you wanna remove it, just:

$(".hide").remove();

Bootstrap 3 Horizontal Divider (not in a dropdown)

Currently it only works for the .dropdown-menu:

.dropdown-menu .divider {
  height: 1px;
  margin: 9px 0;
  overflow: hidden;
  background-color: #e5e5e5;
}

If you want it for other use, in your own css, following the bootstrap.css create another one:

.divider {
  height: 1px;
  width:100%;
  display:block; /* for use on default inline elements like span */
  margin: 9px 0;
  overflow: hidden;
  background-color: #e5e5e5;
}

In C#, what is the difference between public, private, protected, and having no access modifier?

Careful! Watch the accessibility of your classes. Public and protected classes and methods are by default accessible for everyone.

Also, Microsoft isn't very explicit in showing access modifiers (public, protected, etc.. keywords) when new classes in Visual Studio are created. So, take good care and think about the accessibility of your class because it's the door to your implementation internals.

How to make sure that string is valid JSON using JSON.NET

Alternate option using System.Text.Json

For .Net Core one can also use the System.Text.Json namespace and parse using the JsonDocument. Example is an extension method based on the namespace operations:

public static bool IsJsonValid(this string txt)
{
    try { return JsonDocument.Parse(txt) != null; } catch {}

    return false;
}

How do I pass parameters into a PHP script through a webpage?

$argv[0]; // the script name
$argv[1]; // the first parameter
$argv[2]; // the second parameter

If you want to all the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:

<?php
if ($_GET) {
    $argument1 = $_GET['argument1'];
    $argument2 = $_GET['argument2'];
} else {
    $argument1 = $argv[1];
    $argument2 = $argv[2];
}
?>

To call from command line chmod 755 /var/www/webroot/index.php and use

/usr/bin/php /var/www/webroot/index.php arg1 arg2

To call from the browser, use

http://www.mydomain.com/index.php?argument1=arg1&argument2=arg2

How do you do natural logs (e.g. "ln()") with numpy in Python?

Correct, np.log(x) is the Natural Log (base e log) of x.

For other bases, remember this law of logs: log-b(x) = log-k(x) / log-k(b) where log-b is the log in some arbitrary base b, and log-k is the log in base k, e.g.

here k = e

l = np.log(x) / np.log(100)

and l is the log-base-100 of x

Maximum value of maxRequestLength?

As per MSDN the default value is 4096 KB (4 MB).

UPDATE

As for the Maximum, since it is an int data type, then theoretically you can go up to 2,147,483,647. Also I wanted to make sure that you are aware that IIS 7 uses maxAllowedContentLength for specifying file upload size. By default it is set to 30000000 around 30MB and being an uint, it should theoretically allow a max of 4,294,967,295

Prevent users from submitting a form by hitting Enter

A completely different approach:

  1. The first <button type="submit"> in the form will be activated on pressing Enter.
  2. This is true even if the button is hidden with style="display:none;
  3. The script for that button can return false, which aborts the submission process.
  4. You can still have another <button type=submit> to submit the form. Just return true to cascade the submission.
  5. Pressing Enter while the real submit button is focussed will activate the real submit button.
  6. Pressing Enter inside <textarea> or other form controls will behave as normal.
  7. Pressing Enter inside <input> form controls will trigger the first <button type=submit>, which returns false, and thus nothing happens.

Thus:

<form action="...">
  <!-- insert this next line immediately after the <form> opening tag -->
  <button type=submit onclick="return false;" style="display:none;"></button>

  <!-- everything else follows as normal -->
  <!-- ... -->
  <button type=submit>Submit</button>
</form>

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

spring.jackson.serialization-inclusion=non_null used to work for us

But when we upgraded spring boot version to 1.4.2.RELEASE or higher, it stopped working.

Now, another property spring.jackson.default-property-inclusion=non_null is doing the magic.

in fact, serialization-inclusion is deprecated. This is what my intellij throws at me.

Deprecated: ObjectMapper.setSerializationInclusion was deprecated in Jackson 2.7

So, start using spring.jackson.default-property-inclusion=non_null instead

Writing JSON object to a JSON file with fs.writeFileSync

When sending data to a web server, the data has to be a string (here). You can convert a JavaScript object into a string with JSON.stringify(). Here is a working example:

var fs = require('fs');

var originalNote = {
  title: 'Meeting',
  description: 'Meeting John Doe at 10:30 am'
};

var originalNoteString = JSON.stringify(originalNote);

fs.writeFileSync('notes.json', originalNoteString);

var noteString = fs.readFileSync('notes.json');

var note = JSON.parse(noteString);

console.log(`TITLE: ${note.title} DESCRIPTION: ${note.description}`);

Hope it could help.

How do I prevent a Gateway Timeout with FastCGI on Nginx

In http nginx section (/etc/nginx/nginx.conf) add or modify:

keepalive_timeout 300s

In server nginx section (/etc/nginx/sites-available/your-config-file.com) add these lines:

client_max_body_size 50M;
fastcgi_buffers 8 1600k;
fastcgi_buffer_size 3200k;
fastcgi_connect_timeout 300s;
fastcgi_send_timeout 300s;
fastcgi_read_timeout 300s;

In php file in the case 127.0.0.1:9000 (/etc/php/7.X/fpm/pool.d/www.conf) modify:

request_terminate_timeout = 300

I hope help you.

Is there a library function for Root mean square error (RMSE) in python?

You can't find RMSE function directly in SKLearn. But , instead of manually doing sqrt , there is another standard way using sklearn. Apparently, Sklearn's mean_squared_error itself contains a parameter called as "squared" with default value as true .If we set it to false ,the same function will return RMSE instead of MSE.

# code changes implemented by Esha Prakash
from sklearn.metrics import mean_squared_error
rmse = mean_squared_error(y_true, y_pred , squared=False)

"while :" vs. "while true"

from manual:

: [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned.

As this returns always zero therefore is is similar to be used as true

Check out this answer: What Is the Purpose of the `:' (colon) GNU Bash Builtin?

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

In Object Explorer, expand the table, and expand the Keys:

enter image description here

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

jquery will provide you with this and more ...

if($("#something").val()){ //do stuff}

It took me a couple of days to pick it up, but it provides you with you with so much more functionality. An example below.

jQuery(document).ready(function() {
    /* finds closest element with class divright/left and 
    makes all checkboxs inside that div class the same as selectAll...
    */
        $("#selectAll").click(function() {
        $(this).closest('.divright').find(':checkbox').attr('checked', this.checked);
    });
});

How do you get the selected value of a Spinner?

To get the selected value of a spinner you can follow this example.

Create a nested class that implements AdapterView.OnItemSelectedListener. This will provide a callback method that will notify your application when an item has been selected from the Spinner.

Within "onItemSelected" method of that class, you can get the selected item:

public class YourItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        String selected = parent.getItemAtPosition(pos).toString();
    }

    public void onNothingSelected(AdapterView parent) {
        // Do nothing.
    }
}

Finally, your ItemSelectedListener needs to be registered in the Spinner:

spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

change cursor to finger pointer

I like using this one if I only have one link on the page:

onMouseOver="this.style.cursor='pointer'"

When does Git refresh the list of remote branches?

I believe that if you run git branch --all from Bash that the list of remote and local branches you see will reflect what your local Git "knows" about at the time you run the command. Because your Git is always up to date with regard to the local branches in your system, the list of local branches will always be accurate.

However, for remote branches this need not be the case. Your local Git only knows about remote branches which it has seen in the last fetch (or pull). So it is possible that you might run git branch --all and not see a new remote branch which appeared after the last time you fetched or pulled.

To ensure that your local and remote branch list be up to date you can do a git fetch before running git branch --all.

For further information, the "remote" branches which appear when you run git branch --all are not really remote at all; they are actually local. For example, suppose there be a branch on the remote called feature which you have pulled at least once into your local Git. You will see origin/feature listed as a branch when you run git branch --all. But this branch is actually a local Git branch. When you do git fetch origin, this tracking branch gets updated with any new changes from the remote. This is why your local state can get stale, because there may be new remote branches, or your tracking branches can become stale.

Saving results with headers in Sql Server Management Studio

The same problem exists in Visual Studio, here's how to fix it there:

Go to:

Tools > Options > SQL Server Tools > Transact-SQL Editor > Query Results > Results To Grid

Now click the check box to true: "Include column headers when copying or saving the results"

How to update column value in laravel

I tried to update a field with

$table->update(['field' => 'val']);

But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"

Hope it will help someone :)

Reference an Element in a List of Tuples

You also can use itemgetter operator:

from operator import itemgetter
my_tuples = [('c','r'), (2, 3), ('e'), (True, False),('text','sample')]
map(itemgetter(0), my_tuples)

SQL Server equivalent to MySQL enum data type?

It doesn't. There's a vague equivalent:

mycol VARCHAR(10) NOT NULL CHECK (mycol IN('Useful', 'Useless', 'Unknown'))

$(document).on("click"... not working?

An old post, but I love to share as I have the same case but I finally knew the problem :

Problem is : We make a function to work with specified an HTML element, but the HTML element related to this function is not yet created (because the element was dynamically generated). To make it works, we should make the function at the same time we create the element. Element first than make function related to it.

Simply word, a function will only works to the element that created before it (him). Any elements that created dynamically means after him.

But please inspect this sample that did not heed the above case :

<div class="btn-list" id="selected-country"></div>

Dynamically appended :

<button class="btn-map" data-country="'+country+'">'+ country+' </button>

This function is working good by clicking the button :

$(document).ready(function() {    
        $('#selected-country').on('click','.btn-map', function(){ 
        var datacountry = $(this).data('country'); console.log(datacountry);
    });
})

or you can use body like :

$('body').on('click','.btn-map', function(){ 
            var datacountry = $(this).data('country'); console.log(datacountry);
        });

compare to this that not working :

$(document).ready(function() {     
$('.btn-map').on("click", function() { 
        var datacountry = $(this).data('country'); alert(datacountry);
    });
});

hope it will help

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

How do you append to an already existing string?

#!/bin/bash
message="some text"
message="$message add some more"

echo $message

some text add some more

Changing the Git remote 'push to' default

In my case, I fixed by the following: * run git config --edit * In the git config file:

[branch "master"]
remote = origin # <--- change the default origin here

MySQL error #1054 - Unknown column in 'Field List'

I had this error aswell.

I am working in mysql workbench. When giving the values they have to be inside "". That solved it for me.

How do I automatically resize an image for a mobile site?

You can use the following css to resize the image for mobile view

object-fit: scale-down; max-width: 100%

How can I login to a website with Python?

Maybe you want to use twill. It's quite easy to use and should be able to do what you want.

It will look like the following:

from twill.commands import *
go('http://example.org')

fv("1", "email-email", "blabla.com")
fv("1", "password-clear", "testpass")

submit('0')

You can use showforms() to list all forms once you used go… to browse to the site you want to login. Just try it from the python interpreter.

importing jar libraries into android-studio

In the project right click

-> new -> module
-> import jar/AAR package
-> import select the jar file to import
-> click ok -> done

You can follow the screenshots below:

1:

Step 1

2:

enter image description here

3:

enter image description here

You will see this:

enter image description here

Effective swapping of elements of an array in Java

Incredibly late to the party (my apologies) but a more generic solution than those provided here can be implemented (will work with primitives and non-primitives alike):

public static void swap(final Object array, final int i, final int j) {
    final Object atI = Array.get(array, i);
    Array.set(array, i, Array.get(array, j));
    Array.set(array, j, atI);
}

You lose compile-time safety, but it should do the trick.

Note I: You'll get a NullPointerException if the given array is null, an IllegalArgumentException if the given array is not an array, and an ArrayIndexOutOfBoundsException if either of the indices aren't valid for the given array.

Note II: Having separate methods for this for every array type (Object[] and all primitive types) would be more performant (using the other approaches given here) since this requires some boxing/unboxing. But it'd also be a whole lot more code to write/maintain.

How to force HTTPS using a web.config file

A simple way is to tell IIS to send your custom error file for HTTP requests. The file can then contain a meta redirect, a JavaScript redirect and instructions with link, etc... Importantly, you can still check "Require SSL" for the site (or folder) and this will work.

</configuration>
</system.webServer>
    <httpErrors>
        <clear/>
        <!--redirect if connected without SSL-->
        <error statusCode="403" subStatusCode="4" path="errors\403.4_requiressl.html" responseMode="File"/>
    </httpErrors>
</system.webServer>
</configuration>

How to lock orientation of one view controller to portrait mode only in Swift

For a new version of Swift try this

override var shouldAutorotate: Bool {
    return false
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.portrait
}

override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return UIInterfaceOrientation.portrait
}

how to bind img src in angular 2 in ngFor?

Angular 2, 4 and Angular 5 compatible!

You have provided so few details, so I'll try to answer your question without them.

You can use Interpolation:

<img src={{imagePath}} />

Or you can use a template expression:

<img [src]="imagePath" />

In a ngFor loop it might look like this:

<div *ngFor="let student of students">
   <img src={{student.ImagePath}} />
</div>

Regex lookahead, lookbehind and atomic groups

Examples

Given the string foobarbarfoo:

bar(?=bar)     finds the 1st bar ("bar" which has "bar" after it)
bar(?!bar)     finds the 2nd bar ("bar" which does not have "bar" after it)
(?<=foo)bar    finds the 1st bar ("bar" which has "foo" before it)
(?<!foo)bar    finds the 2nd bar ("bar" which does not have "foo" before it)

You can also combine them:

(?<=foo)bar(?=bar)    finds the 1st bar ("bar" with "foo" before it and "bar" after it)

Definitions

Look ahead positive (?=)

Find expression A where expression B follows:

A(?=B)

Look ahead negative (?!)

Find expression A where expression B does not follow:

A(?!B)

Look behind positive (?<=)

Find expression A where expression B precedes:

(?<=B)A

Look behind negative (?<!)

Find expression A where expression B does not precede:

(?<!B)A

Atomic groups (?>)

An atomic group exits a group and throws away alternative patterns after the first matched pattern inside the group (backtracking is disabled).

  • (?>foo|foot)s applied to foots will match its 1st alternative foo, then fail as s does not immediately follow, and stop as backtracking is disabled

A non-atomic group will allow backtracking; if subsequent matching ahead fails, it will backtrack and use alternative patterns until a match for the entire expression is found or all possibilities are exhausted.

  • (foo|foot)s applied to foots will:

    1. match its 1st alternative foo, then fail as s does not immediately follow in foots, and backtrack to its 2nd alternative;
    2. match its 2nd alternative foot, then succeed as s immediately follows in foots, and stop.

Some resources

Online testers

sorting dictionary python 3

The accepted answer definitely works, but somehow miss an important point.

The OP is asking for a dictionary sorted by it's keys this is just not really possible and not what OrderedDict is doing.

OrderedDict is maintaining the content of the dictionary in insertion order. First item inserted, second item inserted, etc.

>>> d = OrderedDict()
>>> d['foo'] = 1
>>> d['bar'] = 2
>>> d
OrderedDict([('foo', 1), ('bar', 2)])

>>> d = OrderedDict()
>>> d['bar'] = 2
>>> d['foo'] = 1
>>> d
OrderedDict([('bar', 2), ('foo', 1)])

Hencefore I won't really be able to sort the dictionary inplace, but merely to create a new dictionary where insertion order match key order. This is explicit in the accepted answer where the new dictionary is b.

This may be important if you are keeping access to dictionaries through containers. This is also important if you itend to change the dictionary later by adding or removing items: they won't be inserted in key order but at the end of dictionary.

>>> d = OrderedDict({'foo': 5, 'bar': 8})
>>> d
OrderedDict([('foo', 5), ('bar', 8)])
>>> d['alpha'] = 2
>>> d
OrderedDict([('foo', 5), ('bar', 8), ('alpha', 2)])

Now, what does mean having a dictionary sorted by it's keys ? That makes no difference when accessing elements by keys, this only matter when you are iterating over items. Making that a property of the dictionary itself seems like overkill. In many cases it's enough to sort keys() when iterating.

That means that it's equivalent to do:

>>> d = {'foo': 5, 'bar': 8}
>>> for k,v in d.iteritems(): print k, v

on an hypothetical sorted by key dictionary or:

>>> d = {'foo': 5, 'bar': 8}
>>> for k, v in iter((k, d[k]) for k in sorted(d.keys())): print k, v

Of course it is not hard to wrap that behavior in an object by overloading iterators and maintaining a sorted keys list. But it is likely overkill.

Shuffling a list of objects

As you learned the in-place shuffling was the problem. I also have problem frequently, and often seem to forget how to copy a list, too. Using sample(a, len(a)) is the solution, using len(a) as the sample size. See https://docs.python.org/3.6/library/random.html#random.sample for the Python documentation.

Here's a simple version using random.sample() that returns the shuffled result as a new list.

import random

a = range(5)
b = random.sample(a, len(a))
print a, b, "two list same:", a == b
# print: [0, 1, 2, 3, 4] [2, 1, 3, 4, 0] two list same: False

# The function sample allows no duplicates.
# Result can be smaller but not larger than the input.
a = range(555)
b = random.sample(a, len(a))
print "no duplicates:", a == list(set(b))

try:
    random.sample(a, len(a) + 1)
except ValueError as e:
    print "Nope!", e

# print: no duplicates: True
# print: Nope! sample larger than population

How to select the first element in the dropdown using jquery?

if you want to check the text of selected option regardless if its the 1st child.

var a = $("#select_id option:selected").text();
alert(a); //check if the value is correct.
if(a == "value") {-- execute code --}

How to compare each item in a list with the rest, only once?

This code will count frequency and remove duplicate elements:

from collections import Counter

str1='the cat sat on the hat hat'

int_list=str1.split();

unique_list = []
for el in int_list:

    if el not in unique_list:
        unique_list.append(el)
    else:
        print "Element already in the list"

print unique_list

c=Counter(int_list)

c.values()

c.keys()

print c

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

I change the input type on my checkbox, so on my OnCheckedChangeListener i do:

passwordEdit.setInputType(InputType.TYPE_CLASS_TEXT| (isChecked? InputType.TYPE_TEXT_VARIATION_PASSWORD|~InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD));

And it finally worked.

Seems like a boolean problem with TYPE_TEXT_VARIATION_VISIBLE_PASSWORD. Invert the flag and it should fix the problem.

In your case:

password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD|~InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

Find Item in ObservableCollection without using a loop

ObservableCollection is a list so if you don't know the element position you have to look at each element until you find the expected one.

Possible optimization If your elements are sorted use a binary search to improve performances otherwise use a Dictionary as index.

Asyncio.gather vs asyncio.wait

A very important distinction, which is easy to miss, is the default bheavior of these two functions, when it comes to exceptions.


I'll use this example to simulate a coroutine that will raise exceptions, sometimes -

import asyncio
import random


async def a_flaky_tsk(i):
    await asyncio.sleep(i)  # bit of fuzz to simulate a real-world example

    if i % 2 == 0:
        print(i, "ok")
    else:
        print(i, "crashed!")
        raise ValueError

coros = [a_flaky_tsk(i) for i in range(10)]

await asyncio.gather(*coros) outputs -

0 ok
1 crashed!
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 20, in <module>
    asyncio.run(main())
  File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 17, in main
    await asyncio.gather(*coros)
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError

As you can see, the coros after index 1 never got to execute.


But await asyncio.wait(coros) continues to execute tasks, even if some of them fail -

0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
Task exception was never retrieved
future: <Task finished name='Task-10' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-8' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-2' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-9' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-3' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError

Ofcourse, this behavior can be changed for both by using -

asyncio.gather(..., return_exceptions=True)

or,

asyncio.wait([...], return_when=asyncio.FIRST_EXCEPTION)


But it doesn't end here!

Notice: Task exception was never retrieved in the logs above.

asyncio.wait() won't re-raise exceptions from the child tasks until you await them individually. (The stacktrace in the logs are just messages, they cannot be caught!)

done, pending = await asyncio.wait(coros)
for tsk in done:
    try:
        await tsk
    except Exception as e:
        print("I caught:", repr(e))

Output -

0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()

On the other hand, to catch exceptions with asyncio.gather(), you must -

results = await asyncio.gather(*coros, return_exceptions=True)
for result_or_exc in results:
    if isinstance(result_or_exc, Exception):
        print("I caught:", repr(result_or_exc))

(Same output as before)

Oracle query to fetch column names

  1. SELECT * FROM <SCHEMA_NAME.TABLE_NAME> WHERE ROWNUM = 0; --> Note that, this is Query Result, a ResultSet. This is exportable to other formats. And, you can export the Query Result to Text format. Export looks like below when I did SELECT * FROM SATURN.SPRIDEN WHERE ROWNUM = 0; :

    "SPRTELE_PIDM" "SPRTELE_SEQNO" "SPRTELE_TELE_CODE" "SPRTELE_ACTIVITY_DATE" "SPRTELE_PHONE_AREA" "SPRTELE_PHONE_NUMBER" "SPRTELE_PHONE_EXT" "SPRTELE_STATUS_IND" "SPRTELE_ATYP_CODE" "SPRTELE_ADDR_SEQNO" "SPRTELE_PRIMARY_IND" "SPRTELE_UNLIST_IND" "SPRTELE_COMMENT" "SPRTELE_INTL_ACCESS" "SPRTELE_DATA_ORIGIN" "SPRTELE_USER_ID" "SPRTELE_CTRY_CODE_PHONE" "SPRTELE_SURROGATE_ID" "SPRTELE_VERSION" "SPRTELE_VPDI_CODE"

  2. DESCRIBE <TABLE_NAME> --> Note: This is script output.

OnClick in Excel VBA

Just a follow-up to dbb's accepted answer: Rather than adding the immediate cell on the right to the selection, why not select a cell way off the working range (i.e. a dummy cell that you know the user will never need). In the following code cell ZZ1 is the dummy cell

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Application.EnableEvents = False
  Union(Target, Me.Range("ZZ1")).Select
  Application.EnableEvents = True

  ' Respond to click/selection-change here

End Sub

How to convert byte array to string

You can do it without dealing with encoding by using BlockCopy:

char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
string str = new string(chars);

convert iso date to milliseconds in javascript

if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);

How to run a Powershell script from the command line and pass a directory as a parameter

try this:

powershell "C:\Dummy Directory 1\Foo.ps1 'C:\Dummy Directory 2\File.txt'"

Get current date, given a timezone in PHP?

If you have access to PHP 5.3, the intl extension is very nice for doing things like this.

Here's an example from the manual:

$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$fmt->format(0); //0 for current time/date

In your case, you can do:

$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
        'America/New_York');
 $fmt->format($datetime); //where $datetime may be a DateTime object, an integer representing a Unix timestamp value (seconds since epoch, UTC) or an array in the format output by localtime(). 

As you can set a Timezone such as America/New_York, this is much better than using a GMT or UTC offset, as this takes into account the day light savings periods as well.

Finaly, as the intl extension uses ICU data, which contains a lot of very useful features when it comes to creating your own date/time formats.

Classes vs. Modules in VB.NET

Classes

  • classes can be instantiated as objects
  • Object data exists separately for each instantiated object.
  • classes can implement interfaces.
  • Members defined within a class are scoped within a specific instance of the class and exist only for the lifetime of the object.
  • To access class members from outside a class, you must use fully qualified names in the format of Object.Member.

Modules

  • Modules cannot be instantiated as objects,Because there is only one copy of a standard module's data, when one part of your program changes a public variable in a standard module, it will be visible to the entire program.
  • Members declared within a module are publicly accessible by default.
  • It can be accessed by any code that can access the module.
  • This means that variables in a standard module are effectively global variables because they are visible from anywhere in your project, and they exist for the life of the program.

Fastest way to flatten / un-flatten nested JSON objects

Here's my much shorter implementation:

Object.unflatten = function(data) {
    "use strict";
    if (Object(data) !== data || Array.isArray(data))
        return data;
    var regex = /\.?([^.\[\]]+)|\[(\d+)\]/g,
        resultholder = {};
    for (var p in data) {
        var cur = resultholder,
            prop = "",
            m;
        while (m = regex.exec(p)) {
            cur = cur[prop] || (cur[prop] = (m[2] ? [] : {}));
            prop = m[2] || m[1];
        }
        cur[prop] = data[p];
    }
    return resultholder[""] || resultholder;
};

flatten hasn't changed much (and I'm not sure whether you really need those isEmpty cases):

Object.flatten = function(data) {
    var result = {};
    function recurse (cur, prop) {
        if (Object(cur) !== cur) {
            result[prop] = cur;
        } else if (Array.isArray(cur)) {
             for(var i=0, l=cur.length; i<l; i++)
                 recurse(cur[i], prop + "[" + i + "]");
            if (l == 0)
                result[prop] = [];
        } else {
            var isEmpty = true;
            for (var p in cur) {
                isEmpty = false;
                recurse(cur[p], prop ? prop+"."+p : p);
            }
            if (isEmpty && prop)
                result[prop] = {};
        }
    }
    recurse(data, "");
    return result;
}

Together, they run your benchmark in about the half of the time (Opera 12.16: ~900ms instead of ~ 1900ms, Chrome 29: ~800ms instead of ~1600ms).

Note: This and most other solutions answered here focus on speed and are susceptible to prototype pollution and shold not be used on untrusted objects.

jquery : focus to div is not working

you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">

$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');

Declaring an unsigned int in Java

Just made this piece of code, wich converts "this.altura" from negative to positive number. Hope this helps someone in need

       if(this.altura < 0){    

                        String aux = Integer.toString(this.altura);
                        char aux2[] = aux.toCharArray();
                        aux = "";
                        for(int con = 1; con < aux2.length; con++){
                            aux += aux2[con];
                        }
                        this.altura = Integer.parseInt(aux);
                        System.out.println("New Value: " + this.altura);
                    }

Calling a class method raises a TypeError in Python

In python member function of a class need explicit self argument. Same as implicit this pointer in C++. For more details please check out this page.

How to migrate GIT repository from one server to a new one

Updated to use git push --mirror origin instead of git push -f origin as suggested in the comments.


This worked for me flawlessly.

git clone --mirror <URL to my OLD repo location>
cd <New directory where your OLD repo was cloned>
git remote set-url origin <URL to my NEW repo location>
git push --mirror origin

I have to mention though that this creates a mirror of your current repo and then pushes that to the new location. Therefore, this can take some time for large repos or slow connections.

String.replaceAll single backslashes with double backslashes

TLDR: use theString = theString.replace("\\", "\\\\"); instead.


Problem

replaceAll(target, replacement) uses regular expression (regex) syntax for target and partially for replacement.

Problem is that \ is special character in regex (it can be used like \d to represents digit) and in String literal (it can be used like "\n" to represent line separator or \" to escape double quote symbol which normally would represent end of string literal).

In both these cases to create \ symbol we can escape it (make it literal instead of special character) by placing additional \ before it (like we escape " in string literals via \").

So to target regex representing \ symbol will need to hold \\, and string literal representing such text will need to look like "\\\\".

So we escaped \ twice:

  • once in regex \\
  • once in String literal "\\\\" (each \ is represented as "\\").

In case of replacement \ is also special there. It allows us to escape other special character $ which via $x notation, allows us to use portion of data matched by regex and held by capturing group indexed as x, like "012".replaceAll("(\\d)", "$1$1") will match each digit, place it in capturing group 1 and $1$1 will replace it with its two copies (it will duplicate it) resulting in "001122".

So again, to let replacement represent \ literal we need to escape it with additional \ which means that:

  • replacement must hold two backslash characters \\
  • and String literal which represents \\ looks like "\\\\"

BUT since we want replacement to hold two backslashes we will need "\\\\\\\\" (each \ represented by one "\\\\").

So version with replaceAll can look like

replaceAll("\\\\", "\\\\\\\\");

Easier way

To make out life easier Java provides tools to automatically escape text into target and replacement parts. So now we can focus only on strings, and forget about regex syntax:

replaceAll(Pattern.quote(target), Matcher.quoteReplacement(replacement))

which in our case can look like

replaceAll(Pattern.quote("\\"), Matcher.quoteReplacement("\\\\"))

Even better

If we don't really need regex syntax support lets not involve replaceAll at all. Instead lets use replace. Both methods will replace all targets, but replace doesn't involve regex syntax. So you could simply write

theString = theString.replace("\\", "\\\\");

Use Device Login on Smart TV / Console

Facebook login for smarttv/devices without facebook sdk is possible throught code , check the documentation here :

https://developers.facebook.com/docs/facebook-login/for-devices

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

Trying to run a servlet in Eclipse (right-click + "Run on Server") I encountered the very same problem: "HTTP Status: 404 / Description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists." Adding an index.html did not help, neither changing various settings of the tomcat.

Finally, I found the problem in an unexpected place: In Eclipse, the Option "Build automatically" was not set. Thus the servlet was not compiled, and no File "myServlet.class" was deployed to the server (in my case in the path .wtpwebapps/projectXX/WEB-INF/classes/XXpackage/). Building the project manually and restarting the server solved the problem.

My environment: Eclipse Neon.3 Release 4.6.3, Tomcat-Version 8.5.14., OS Linux Mint 18.1.

Run command on the Ansible host

Yes, you can run commands on the Ansible host. You can specify that all tasks in a play run on the Ansible host, or you can mark individual tasks to run on the Ansible host.

If you want to run an entire play on the Ansible host, then specify hosts: 127.0.0.1 and connection:local in the play, for example:

- name: a play that runs entirely on the ansible host
  hosts: 127.0.0.1
  connection: local
  tasks:
  - name: check out a git repository
    git: repo=git://foosball.example.org/path/to/repo.git dest=/local/path

See Local Playbooks in the Ansible documentation for more details.

If you just want to run a single task on your Ansible host, you can use local_action to specify that a task should be run locally. For example:

- name: an example playbook
  hosts: webservers
  tasks:
  - ...

  - name: check out a git repository
    local_action: git repo=git://foosball.example.org/path/to/repo.git dest=/local/path

See Delegation in the Ansible documentation for more details.

Edit: You can avoid having to type connection: local in your play by adding this to your inventory:

localhost ansible_connection=local

(Here you'd use "localhost" instead of "127.0.0.1" to refer to the play).

Edit: In newer versions of ansible, you no longer need to add the above line to your inventory, ansible assumes it's already there.

How to change option menu icon in the action bar?

I got a simpler solution which worked perfectly for me :

Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.change_pass);
        toolbar.setOverflowIcon(drawable);

Pass element ID to Javascript function

Check this: http://jsfiddle.net/h7kRt/1/,

you should change in jsfiddle on top-left to No-wrap in <head>

Your code looks good and it will work inside a normal page. In jsfiddle your function was being defined inside a load handler and thus is in a different scope. By changing to No-wrap you have it in the global scope and can use it as you wanted.

Docker error : no space left on device

Docker for Mac

So docker system prune and docker system prune --volumes suggested in other answers freed up some space each time, but eventually every time I ran anything I was getting the error.

What actually fixed the root issue was deleting the Docker.raw file that Docker for Mac uses for storage, and restarting it.

To find that file open up Docker for Mac and go to*

Preferences > Resources > Advanced > Disk Image Location

*this is for version 2.2.0.5, but on older versions it should be similar

On newer versions of Docker for Mac**, it shows you the actual size of that file on disk right there in the UI, as well as its max allocated size. You'll probably see that it is massive. For example on my machine it was 41GB!

**On older versions, it doesn't show you the actual disk usage in the UI, and MacOS Finder always shows the file size as the max allocated size. You can check the actual size on disk by opening the directory in a terminal and running du -h Docker.raw

I deleted Docker.raw, restarted Docker for Mac, and the file was automatically created again and was back to being 0GB.

Everything continued to work as before, though of course I had lost my Docker cache. As expected, after running a few Docker commands the file started to fill up again with a few GB of stuff, but nowhere near 41GB.


Update

A few months later, my Docker.raw filled back up again to a similar size. So this method did work, but has to repeated every few months. For me that's fine.

A note on why this works - I have to assume it's a bug in Docker for Mac. It really seems like docker system prune / docker system prune --volumes should entirely clear the contents of this file, but it appears the file accumulates other stuff that can't be deleted by these commands. Anyway, deleting it manually solves the problem!

How to discover number of *logical* cores on Mac OS X?

It wasn't specified in the original question (although I saw OP post in comments that this wasn't an option), but many developers on macOS have the Homebrew package manager installed.

For future developers who stumble upon this question, as long as the assumption (or requirement) of Homebrew being installed exists (e.g., in an engineering organization in a company), nproc is one of the common GNU binaries that is included in the coreutils package.

brew install coreutils

If you have scripts that you would prefer to write once (for Linux + macOS) instead of twice, or to avoid having if blocks where you need to detect the OS to know whether or not to call nproc vs sysctl -n hw.logicalcpu, this may be a better option.

android:drawableLeft margin and/or padding

If the size of drawable resouce is fixed, you can do like this:

<Button
    android:background="@drawable/rounded_button_green"
    style="?android:attr/selectableItemBackground"
    android:layout_height="wrap_content"
    app:layout_widthPercent="70%"
    android:drawableRight="@drawable/ic_clear_black_24dp"
    android:paddingRight="10dp"
    android:paddingLeft="34dp"
    tools:text="example" />

The key here is that:

    android:drawableRight="@drawable/ic_clear_black_24dp"
    android:paddingRight="10dp"
    android:paddingLeft="34dp"

That is, the size of drawable resource plus paddingRight is the paddingLeft.

You can see the result in this example

Request UAC elevation from within a Python script?

The following example builds on MARTIN DE LA FUENTE SAAVEDRA's excellent work and accepted answer. In particular, two enumerations are introduced. The first allows for easy specification of how an elevated program is to be opened, and the second helps when errors need to be easily identified. Please note that if you want all command line arguments passed to the new process, sys.argv[0] should probably be replaced with a function call: subprocess.list2cmdline(sys.argv).

#! /usr/bin/env python3
import ctypes
import enum
import subprocess
import sys

# Reference:
# msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx


# noinspection SpellCheckingInspection
class SW(enum.IntEnum):
    HIDE = 0
    MAXIMIZE = 3
    MINIMIZE = 6
    RESTORE = 9
    SHOW = 5
    SHOWDEFAULT = 10
    SHOWMAXIMIZED = 3
    SHOWMINIMIZED = 2
    SHOWMINNOACTIVE = 7
    SHOWNA = 8
    SHOWNOACTIVATE = 4
    SHOWNORMAL = 1


class ERROR(enum.IntEnum):
    ZERO = 0
    FILE_NOT_FOUND = 2
    PATH_NOT_FOUND = 3
    BAD_FORMAT = 11
    ACCESS_DENIED = 5
    ASSOC_INCOMPLETE = 27
    DDE_BUSY = 30
    DDE_FAIL = 29
    DDE_TIMEOUT = 28
    DLL_NOT_FOUND = 32
    NO_ASSOC = 31
    OOM = 8
    SHARE = 26


def bootstrap():
    if ctypes.windll.shell32.IsUserAnAdmin():
        main()
    else:
       # noinspection SpellCheckingInspection
        hinstance = ctypes.windll.shell32.ShellExecuteW(
            None,
            'runas',
            sys.executable,
            subprocess.list2cmdline(sys.argv),
            None,
            SW.SHOWNORMAL
        )
        if hinstance <= 32:
            raise RuntimeError(ERROR(hinstance))


def main():
    # Your Code Here
    print(input('Echo: '))


if __name__ == '__main__':
    bootstrap()

Transfer files to/from session I'm logged in with PuTTY

In that way on windows pscp allows an upload directly (without any request for e.g. key-accepting):

pscp.exe -scp -pw 'my_pw' -v -i my.ppk -l root -batch -sshlog logfile19.txt -hostkey ba:2e:4d:12:68:82:19:a1:d2:22:bc:12:c2:1a:44:a7 hallo4.txt [email protected]:/srv/www/htdocs/xml_parser/hallo4.txt

Using an IF Statement in a MySQL SELECT query

The IF/THEN/ELSE construct you are using is only valid in stored procedures and functions. Your query will need to be restructured because you can't use the IF() function to control the flow of the WHERE clause like this.

The IF() function that can be used in queries is primarily meant to be used in the SELECT portion of the query for selecting different data based on certain conditions, not so much to be used in the WHERE portion of the query:

SELECT IF(JQ.COURSE_ID=0, 'Some Result If True', 'Some Result If False'), OTHER_COLUMNS
FROM ...
WHERE ...

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

That is because you are not fully qualifying your cells object. Try this

With Worksheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

Notice the DOT before Cells?

Add a summary row with totals

If you want to display more column values without an aggregation function use GROUPING SETS instead of ROLLUP:

SELECT
  Type = ISNULL(Type, 'Total'),
  SomeIntColumn = ISNULL(SomeIntColumn, 0),
  TotalSales = SUM(TotalSales)
FROM atable
GROUP BY GROUPING SETS ((Type, SomeIntColumn ), ())
ORDER BY SomeIntColumn --Displays summary row as the first row in query result

What is an OS kernel ? How does it differ from an operating system?

A kernel is the part of the operating system that mediates access to system resources. It's responsible for enabling multiple applications to effectively share the hardware by controlling access to CPU, memory, disk I/O, and networking.

An operating system is the kernel plus applications that enable users to get something done (i.e compiler, text editor, window manager, etc).

comparing two strings in SQL Server

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables

Why do we always prefer using parameters in SQL statements?

Using parameters helps prevent SQL Injection attacks when the database is used in conjunction with a program interface such as a desktop program or web site.

In your example, a user can directly run SQL code on your database by crafting statements in txtSalary.

For example, if they were to write 0 OR 1=1, the executed SQL would be

 SELECT empSalary from employee where salary = 0 or 1=1

whereby all empSalaries would be returned.

Further, a user could perform far worse commands against your database, including deleting it If they wrote 0; Drop Table employee:

SELECT empSalary from employee where salary = 0; Drop Table employee

The table employee would then be deleted.


In your case, it looks like you're using .NET. Using parameters is as easy as:

    string sql = "SELECT empSalary from employee where salary = @salary";

    using (SqlConnection connection = new SqlConnection(/* connection info */))
    using (SqlCommand command = new SqlCommand(sql, connection))
    {
        var salaryParam = new SqlParameter("salary", SqlDbType.Money);
        salaryParam.Value = txtMoney.Text;
    
        command.Parameters.Add(salaryParam);
        var results = command.ExecuteReader();
    }

    Dim sql As String = "SELECT empSalary from employee where salary = @salary"
    Using connection As New SqlConnection("connectionString")
        Using command As New SqlCommand(sql, connection)
            Dim salaryParam = New SqlParameter("salary", SqlDbType.Money)
            salaryParam.Value = txtMoney.Text
    
            command.Parameters.Add(salaryParam)

            Dim results = command.ExecuteReader()
        End Using
    End Using

Edit 2016-4-25:

As per George Stocker's comment, I changed the sample code to not use AddWithValue. Also, it is generally recommended that you wrap IDisposables in using statements.

What does a lazy val do?

A demonstration of lazy - as defined above - execution when defined vs execution when accessed: (using 2.12.7 scala shell)

// compiler says this is ok when it is lazy
scala> lazy val t: Int = t 
t: Int = <lazy>
//however when executed, t recursively calls itself, and causes a StackOverflowError
scala> t             
java.lang.StackOverflowError
...

// when the t is initialized to itself un-lazily, the compiler warns you of the recursive call
scala> val t: Int = t
<console>:12: warning: value t does nothing other than call itself recursively
   val t: Int = t

How do I perform a GROUP BY on an aliased column in MS-SQL Server?

SELECT       
    CASE
        WHEN LastName IS NULL THEN FirstName
        WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
    END AS 'FullName'
FROM
    customers
GROUP BY     
    LastName,
    FirstName

This works because the formula you use (the CASE statement) can never give the same answer for two different inputs.

This is not the case if you used something like:

LEFT(FirstName, 1) + ' ' + LastName

In such a case "James Taylor" and "John Taylor" would both result in "J Taylor".

If you wanted your output to have "J Taylor" twice (one for each person):

GROUP BY LastName, FirstName

If, however, you wanted just one row of "J Taylor" you'd want:

GROUP BY LastName, LEFT(FirstName, 1)

How to use Google App Engine with my own naked domain (not subdomain)?

Google does offer naked domain redirection.

  • Login to your google apps account and select "manage this domain"
  • Navigate to Domain settings
  • Within Domain Setings, navigate to Domain names
  • There's a link that says "change the A record". Clicking that will give you the destination IPs for the A records you need to create.

Difference between rake db:migrate db:reset and db:schema:load

Rails 5

db:create - Creates the database for the current RAILS_ENV environment. If RAILS_ENV is not specified it defaults to the development and test databases.

db:create:all - Creates the database for all environments.

db:drop - Drops the database for the current RAILS_ENV environment. If RAILS_ENV is not specified it defaults to the development and test databases.

db:drop:all - Drops the database for all environments.

db:migrate - Runs migrations for the current environment that have not run yet. By default it will run migrations only in the development environment.

db:migrate:redo - Runs db:migrate:down and db:migrate:up or db:migrate:rollback and db:migrate:up depending on the specified migration.

db:migrate:up - Runs the up for the given migration VERSION.

db:migrate:down - Runs the down for the given migration VERSION.

db:migrate:status - Displays the current migration status.

db:migrate:rollback - Rolls back the last migration.

db:version - Prints the current schema version.

db:forward - Pushes the schema to the next version.

db:seed - Runs the db/seeds.rb file.

db:schema:load Recreates the database from the schema.rb file. Deletes existing data.

db:schema:dump Dumps the current environment’s schema to db/schema.rb.

db:structure:load - Recreates the database from the structure.sql file.

db:structure:dump - Dumps the current environment’s schema to db/structure.sql. (You can specify another file with SCHEMA=db/my_structure.sql)

db:setup Runs db:create, db:schema:load and db:seed.

db:reset Runs db:drop and db:setup. db:migrate:reset - Runs db:drop, db:create and db:migrate.

db:test:prepare - Check for pending migrations and load the test schema. (If you run rake without any arguments it will do this by default.)

db:test:clone - Recreate the test database from the current environment’s database schema.

db:test:clone_structure - Similar to db:test:clone, but it will ensure that your test database has the same structure, including charsets and collations, as your current environment’s database.

db:environment:set - Set the current RAILS_ENV environment in the ar_internal_metadata table. (Used as part of the protected environment check.)

db:check_protected_environments - Checks if a destructive action can be performed in the current RAILS_ENV environment. Used internally when running a destructive action such as db:drop or db:schema:load.

High-precision clock in Python

You can also use time.clock() It counts the time used by the process on Unix and time since the first call to it on Windows. It's more precise than time.time().

It's the usually used function to measure performance.

Just call

import time
t_ = time.clock()
#Your code here
print 'Time in function', time.clock() - t_

EDITED: Ups, I miss the question as you want to know exactly the time, not the time spent...

Spark SQL: apply aggregate functions to a list of columns

Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.

Typically, this is how I handle this case:

val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics

val df = spark.read.table("some_table"). 
    .select(columnOfInterests.map(c => col(c)):_*)
    .groupBy(dimensions.map(d => col(d)): _*)
    .agg(metrics.map( m => m -> "sum").toMap)
    .toDF(columnOfInterests:_*)    // that's the interesting part

The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2) and sum(col3) to simply col2 and col3.

How can I check what version/edition of Visual Studio is installed programmatically?

Its not very subtle, but there is a folder in the install location that carries the installed version name.

eg I've got:

C:\Program Files\Microsoft Visual Studio 9.0\Microsoft Visual Studio 2008 Standard Edition - ENU

and

C:\Program Files\Microsoft Visual Studio 10.0\Microsoft Visual Studio 2010 Professional - ENU

You could find the install location from the registry keys you listed above.

Alternatively this will be in the registry at a number of places, eg:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Setup\Microsoft Visual Studio 2008 Standard Edition - ENU

There are loads of values and keys with the string in, you can find them by looking for "Microsoft Visual Studio 2010" in the Regedit>Edit>Find function.

You'd just need to pick the one you want and do a little bit of string matching.

How to execute only one test spec with angular-cli

Each of your .spec.ts file have all its tests grouped in describe block like this:

describe('SomeComponent', () => {...}

You can easily run just this single block, by prefixing the describe function name with f:

fdescribe('SomeComponent', () => {...}

If you have such function, no other describe blocks will run. Btw. you can do similar thing with it => fit and there is also a "blacklist" version - x. So:

  • fdescribe and fit causes only functions marked this way to run
  • xdescribe and xit causes all but functions marked this way to run

How to check if two words are anagrams

You should use something like that:

    for (int i...) {
        isFound = false;
        for (int j...) {
            if (...) {
                ...
                isFound = true;
            }
        }

Default value for isFound should be false. Just it

Close Form Button Event

private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("This will close down the whole application. Confirm?", "Close Application", MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
        MessageBox.Show("The application has been closed successfully.", "Application Closed!", MessageBoxButtons.OK);
        System.Windows.Forms.Application.Exit();
    }
    else
    {
        this.Activate();
    }  
}

How to represent the double quotes character (") in regex?

you need to use backslash before ". like \"

From the doc here you can see that

A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

and " (double quote) is a escacpe sequence

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

How to get only numeric column values?

Try using the WHERE clause:

SELECT column1 FROM table WHERE Isnumeric(column1);

PostgreSQL: Modify OWNER on all tables simultaneously in PostgreSQL

See REASSIGN OWNED command

Note: As @trygvis mentions in the answer below, the REASSIGN OWNED command is available since at least version 8.2, and is a much easier method.


Since you're changing the ownership for all tables, you likely want views and sequences too. Here's what I did:

Tables:

for tbl in `psql -qAt -c "select tablename from pg_tables where schemaname = 'public';" YOUR_DB` ; do  psql -c "alter table \"$tbl\" owner to NEW_OWNER" YOUR_DB ; done

Sequences:

for tbl in `psql -qAt -c "select sequence_name from information_schema.sequences where sequence_schema = 'public';" YOUR_DB` ; do  psql -c "alter sequence \"$tbl\" owner to NEW_OWNER" YOUR_DB ; done

Views:

for tbl in `psql -qAt -c "select table_name from information_schema.views where table_schema = 'public';" YOUR_DB` ; do  psql -c "alter view \"$tbl\" owner to NEW_OWNER" YOUR_DB ; done

You could probably DRY that up a bit since the alter statements are identical for all three.


How do I calculate the MD5 checksum of a file in Python?

In Python 3.8+ you can do

import hashlib

with open("your_filename.png", "rb") as f:
    file_hash = hashlib.md5()
    while chunk := f.read(8192):
        file_hash.update(chunk)

print(file_hash.digest())
print(file_hash.hexdigest())  # to get a printable str instead of bytes

On Python 3.7 and below:

with open("your_filename.png", "rb") as f:
    file_hash = hashlib.md5()
    chunk = f.read(8192)
    while chunk:
        file_hash.update(chunk)
        chunk = f.read(8192)

print(file_hash.hexdigest())

This reads the file 8192 (or 2¹³) bytes at a time instead of all at once with f.read() to use less memory.


Consider using hashlib.blake2b instead of md5 (just replace md5 with blake2b in the above snippets). It's cryptographically secure and faster than MD5.

Array formula on Excel for Mac

CTRL+SHIFT+ENTER, ARRAY FORMULA EXCEL 2016 MAC. So I arrive late into the game, but maybe someone else will. This almost drove me nuts. No matter what I searched for in Google I came up empty. Whatever I tried, no solution seemed to be in sight. Switched to Excel 2016 quite some time ago and today I needed to do some array formulas. Also sitting on a MacBook Pro 15 Touch Bar 2016. Not that it really matters, but still, since the solution was published on Youtube in 2013. The reason why, for me anyway, nothing worked, is in the Mac OS, the control key by default, for me anyway, is set to manage Mission control, which, at least for me, disabled the control button in Excel. In order to enable the key to actually control functions in Excel, you need to go to System preferences > Mission Control, and disable shortcuts for Mission control. So, let's see how long this solution will last. Probably be back to square one after the coffee break. Have a good one!

how to show progress bar(circle) in an activity having a listview before loading the listview with data

You can do this easier.
Source: http://www.tutorialspoint.com/android/android_loading_spinner.htm
It helped me.

Layout:

<ProgressBar
   android:id="@+id/progressBar1"
   style="?android:attr/progressBarStyleLarge"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerHorizontal="true" />

After defining it in xml, you have to get its reference in java file through ProgressBar class. Its syntax is given below:

private ProgressBar spinner;
spinner = (ProgressBar)findViewById(R.id.progressBar1);

After that you can make its disappear , and bring it back when needed through setVisibility Method. Its syntax is given below:

spinner.setVisibility(View.GONE);
spinner.setVisibility(View.VISIBLE);

Disable browser's back button

I also had the same problem, use this Java script function on head tag or in , its 100% working fine, would not let you go back.

 <script type = "text/javascript" >
      function preventBack(){window.history.forward();}
        setTimeout("preventBack()", 0);
        window.onunload=function(){null};
    </script>

How can I remove all objects but one from the workspace in R?

require(gdata)
keep(object_1,...,object_n,sure=TRUE)
ls()

setTimeout in for-loop does not print consecutive values

You can use the extra arguments to setTimeout to pass parameters to the callback function.

for (var i = 1; i <= 2; i++) {
    setTimeout(function(j) { alert(j) }, 100, i);
}

Note: This doesn't work on IE9 and below browsers.

How do I get information about an index and table owner in Oracle?

Below are two simple query using which you can check index created on a table in Oracle.

select index_name
  from dba_indexes
 where table_name='&TABLE_NAME'
   and owner='&TABLE_OWNER';
select index_name 
  from user_indexes 
 where table_name='&TABLE_NAME';

Please check for more details and index size below. Index on a table and its size in Oracle

memcpy() vs memmove()

The memory in memcpy cannot overlap or you risk undefined behaviour, while the memory in memmove can overlap.

char a[16];
char b[16];

memcpy(a,b,16);           // valid
memmove(a,b,16);          // Also valid, but slower than memcpy.
memcpy(&a[0], &a[1],10);  // Not valid since it overlaps.
memmove(&a[0], &a[1],10); // valid. 

Some implementations of memcpy might still work for overlapping inputs but you cannot count of that behaviour. While memmove must allow for overlapping.

Byte array to image conversion

Most of the time when this happens it is bad data in the SQL column. This is the proper way to insert into an image column:

INSERT INTO [TableX] (ImgColumn) VALUES (
(SELECT * FROM OPENROWSET(BULK N'C:\....\Picture 010.png', SINGLE_BLOB) as tempimg))

Most people do it incorrectly this way:

INSERT INTO [TableX] (ImgColumn) VALUES ('C:\....\Picture 010.png'))

How to obtain the location of cacerts of the default java installation?

If you need to access those certs programmatically it is best to not use the file at all, but access it via the trust manager. The following code is from a OpenJDK Test case (which makes sure the built cacerts collection is not empty):

TrustManagerFactory trustManagerFactory =
    TrustManagerFactory.getInstance("PKIX");
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers =
    trustManagerFactory.getTrustManagers();
X509TrustManager trustManager =
    (X509TrustManager) trustManagers[0];
X509Certificate[] acceptedIssuers =
    trustManager.getAcceptedIssuers();

So you don’t have to deal with file location or keystore password.

JFrame in full screen Java

Easiest fix ever:

for ( Window w : Window.getWindows() ) {
    GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow( w );
}

How do I set GIT_SSL_NO_VERIFY for specific repos only?

This works for me:

git init
git config --global http.sslVerify false
git clone https://myurl/myrepo.git

Gulp command not found after install

Not sure why the question was down-voted, but I had the same issue and following the blog post recommended solve the issue. One thing I should add is that in my case, once I ran:

npm config set prefix /usr/local

I confirmed the npm root -g was pointing to /usr/local/lib/node_modules/npm, but in order to install gulp in /usr/local/lib/node_modules, I had to use sudo:

sudo npm install gulp -g

COUNT DISTINCT with CONDITIONS

This may also work:

SELECT 
    COUNT(DISTINCT T.tag) as DistinctTag,
    COUNT(DISTINCT T2.tag) as DistinctPositiveTag
FROM Table T
    LEFT JOIN Table T2 ON T.tag = T2.tag AND T.entryID = T2.entryID AND T2.entryID > 0

You need the entryID condition in the left join rather than in a where clause in order to make sure that any items that only have a entryID of 0 get properly counted in the first DISTINCT.

What is the difference between document.location.href and document.location?

typeof document.location; // 'object'
typeof document.location.href; // 'string'

The href property is a string, while document.location itself is an object.

Symfony2 : How to get form validation errors after binding the request to the form

For Symfony 5 I got this working :

public function getErrorMessages(Form $form) {
  
    $errors = [];        

    foreach ($form->all() as $child) {
        foreach ($child->getErrors() as $error) {
                $name = $child->getName();
                $errors[$name] = $error->getMessage();
        }
    }

    return $errors;
}

I got this kind of JSON thing with it :

errors: {
    firstname: "The firstname must be between 2 and 30 characters long.",
    lastname: "The lastname must be between 2 and 40 characters long."
    subject: "Please choose a subject."
    text: "Empty messages are not allowed."
}

It's nice and sweet enough for me, but I guess it will not pick up errors at the global level, like timed out tokens or other stuff like that. Anyway, I've been quite a bit longtime looking for a solution suiting my case, and I'm happy contributing here hoping it'll help some developer somewhere sometime somehow.

How do I get values from a SQL database into textboxes using C#?

read = com.ExecuteReader()

SqlDataReader has a function Read() that reads the next row from your query's results and returns a bool whether it found a next row to read or not. So you need to check that before you actually get the columns from your reader (which always just gets the current row that Read() got). Or preferably make a loop while(read.Read()) if your query returns multiple rows.

How to use switch statement inside a React component?

This is another approach.

render() {
   return {this[`renderStep${this.state.step}`]()}

renderStep0() { return 'step 0' }
renderStep1() { return 'step 1' }

Generate random colors (RGB)

color = lambda : [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]

How to make a div 100% height of the browser window

Try to set height:100% in html & body

html, 
body {
    height: 100%;
}

And if you want to 2 div height same use or set the parent element display:flex property.

jQuery - Appending a div to body, the body is the object?

Instead use use appendTo. append or appendTo returns a jQuery object so you don't have to wrap it inside $().

var holdyDiv = $('<div />').appendTo('body');
holdyDiv.attr('id', 'holdy');

.appendTo() reference: http://api.jquery.com/appendTo/

Alernatively you can try this also.

$('<div />', { id: 'holdy' }).appendTo('body');
               ^
             (Here you can specify any attribute/value pair you want)

GSON - Date format

This won't really work at all. There is no date type in JSON. I would recommend to serialize to ISO8601 back and forth (for format agnostics and JS compat). Consider that you have to know which fields contain dates.

Make docker use IPv4 for port binding

Setting net.ipv6.conf.all.forwarding=1 will fix the issue.

This can be done on a live system using sudo sysctl -w net.ipv6.conf.all.forwarding=1

Node.js - use of module.exports as a constructor

At the end, Node is about Javascript. JS has several way to accomplished something, is the same thing to get an "constructor", the important thing is to return a function.

This way actually you are creating a new function, as we created using JS on Web Browser environment for example.

Personally i prefer the prototype approach, as Sukima suggested on this post: Node.js - use of module.exports as a constructor

Vertically center text in a 100% height div?

Setting the line height to the same as the height of the div will cause the text to center. Only works if there is one line. (such as a button).

How to catch SQLServer timeout exceptions

To check for a timeout, I believe you check the value of ex.Number. If it is -2, then you have a timeout situation.

-2 is the error code for timeout, returned from DBNETLIB, the MDAC driver for SQL Server. This can be seen by downloading Reflector, and looking under System.Data.SqlClient.TdsEnums for TIMEOUT_EXPIRED.

Your code would read:

if (ex.Number == -2)
{
     //handle timeout
}

Code to demonstrate failure:

try
{
    SqlConnection sql = new SqlConnection(@"Network Library=DBMSSOCN;Data Source=YourServer,1433;Initial Catalog=YourDB;Integrated Security=SSPI;");
    sql.Open();

    SqlCommand cmd = sql.CreateCommand();
    cmd.CommandText = "DECLARE @i int WHILE EXISTS (SELECT 1 from sysobjects) BEGIN SELECT @i = 1 END";
    cmd.ExecuteNonQuery(); // This line will timeout.

    cmd.Dispose();
    sql.Close();
}
catch (SqlException ex)
{
    if (ex.Number == -2) {
        Console.WriteLine ("Timeout occurred");
    }
}

IE8 support for CSS Media Query

Prior to Internet Explorer 8 there were no support for Media queries. But depending on your case you can try to use conditional comments to target only Internet Explorer 8 and lower. You just have to use a proper CSS files architecture.

Why do I always get the same sequence of random numbers with rand()?

If I remember the quote from Knuth's seminal work "The Art of Computer Programming" at the beginning of the chapter on Random Number Generation, it goes like this:

"Anyone who attempts to generate random numbers by mathematical means is, technically speaking, in a state of sin".

Simply put, the stock random number generators are algorithms, mathematical and 100% predictable. This is actually a good thing in a lot of situations, where a repeatable sequence of "random" numbers is desirable - for example for certain statistical exercises, where you don't want the "wobble" in results that truly random data introduces thanks to clustering effects.

Although grabbing bits of "random" data from the computer's hardware is a popular second alternative, it's not truly random either - although the more complex the operating environment, the more possibilities for randomness - or at least unpredictability.

Truly random data generators tend to look to outside sources. Radioactive decay is a favorite, as is the behavior of quasars. Anything whose roots are in quantum effects is effectively random - much to Einstein's annoyance.

How to read xml file contents in jQuery and display in html elements?

You can use $.each()

Suppose your xml is

<Cloudtags><id>1</id></Cloudtags><Cloudtags><id>2</id></Cloudtags><Cloudtags><id>3</id></Cloudtags>

In your Ajax success

success: function (xml) {
    $(xml).find('Cloudtags').each(function(){// your outer tag of xml
         var id = $(this).find("id").text(); // 
    });
}

For your case

success: function (xml) {
        $(xml).find('person').each(function(){// your outer tag of xml
             var name = $(this).find("name").text(); // 
             var age = $(this).find("age").text();
        });
    }

using OR and NOT in solr query

You can find the follow up to the solr-user group on: solr user mailling list

The prevailing thought is that the NOT operator may only be used to remove results from a query - not just exclude things out of the entire dataset. I happen to like the syntax you suggested mausch - thanks!

How to read file binary in C#?

Well, reading it isn't hard, just use FileStream to read a byte[]. Converting it to text isn't really generally possible or meaningful unless you convert the 1's and 0's to hex. That's easy to do with the BitConverter.ToString(byte[]) overload. You'd generally want to dump 16 or 32 bytes in each line. You could use Encoding.ASCII.GetString() to try to convert the bytes to characters. A sample program that does this:

using System;
using System.IO;
using System.Text;

class Program {
    static void Main(string[] args) {
        // Read the file into <bits>
        var fs = new FileStream(@"c:\temp\test.bin", FileMode.Open);
        var len = (int)fs.Length;
        var bits = new byte[len];
        fs.Read(bits, 0, len);
        // Dump 16 bytes per line
        for (int ix = 0; ix < len; ix += 16) {
            var cnt = Math.Min(16, len - ix);
            var line = new byte[cnt];
            Array.Copy(bits, ix, line, 0, cnt);
            // Write address + hex + ascii
            Console.Write("{0:X6}  ", ix);
            Console.Write(BitConverter.ToString(line));
            Console.Write("  ");
            // Convert non-ascii characters to .
            for (int jx = 0; jx < cnt; ++jx)
                if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
            Console.WriteLine(Encoding.ASCII.GetString(line));
        }
        Console.ReadLine();
    }
}