Programs & Examples On #Midi

MIDI (Musical Instrument Digital Interface) is a protocol used to allow music hardware, software and other equipment to communicate with each other.

Correctly Parsing JSON in Swift 3

let str = "{\"names\": [\"Bob\", \"Tim\", \"Tina\"]}"

let data = str.data(using: String.Encoding.utf8, allowLossyConversion: false)!

do {
    let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
    if let names = json["names"] as? [String] 
{
        print(names)
}
} catch let error as NSError {
    print("Failed to load: \(error.localizedDescription)")
}

AngularJS: How to set a variable inside of a template?

It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with "" and your variable will be hidden.

So, you could define the variable with:

{{f = forecast[day.iso]; ""}}

Accessing JSON elements

import json

# some JSON:
json_str =  '{ "name":"Sarah", "age":25, "city":"Chicago"}'

# parse json_str:
json = json.loads(json_str)

# get tags from json   
tags = []
for tag in json:
    tags.append(tag)
  

# print each tag name e your content
for i in range(len(tags)):
    print(tags[i] + ': ' + str(json[tags[i]]))

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

If you've tried modifying etc/hosts and adding java.rmi.server.hostname property as well but still registry is being bind to 127.0.0.1

the issue for me was resolved after explicitly setting System property through code though the same property wasn't picked from jvm args

Play sound file in a web-page in the background

<audio controls autoplay loop>
  <source src="path/your_song.mp3" type="audio/ogg">
  <embed src="path/your_song.mp3" autostart="true" loop="true" hidden="true"> 
</audio>

[ps. replace the "path/your_song.mp3" with the folder and the song title eg. "music/samplemusic.mp3" or "media/bgmusic.mp3" etc.

How to call getClass() from a static method in Java?

getClass() method is defined in Object class with the following signature:

public final Class getClass()

Since it is not defined as static, you can not call it within a static code block. See these answers for more information: Q1, Q2, Q3.

If you're in a static context, then you have to use the class literal expression to get the Class, so you basically have to do like:

Foo.class

This type of expression is called Class Literals and they are explained in Java Language Specification Book as follows:

A class literal is an expression consisting of the name of a class, interface, array, or primitive type followed by a `.' and the token class. The type of a class literal is Class. It evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.

You can also find information about this subject on API documentation for Class.

Leverage browser caching, how on apache or .htaccess?

First we need to check if we have enabled mod_headers.c and mod_expires.c.

sudo apache2 -l

If we don't have it, we need to enable them

sudo a2enmod headers

Then we need to restart apache

sudo apache2 restart

At last, add the rules on .htaccess (seen on other answers), for example

ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/png A2592000
ExpiresByType image/x-icon A2592000
ExpiresByType text/css A86400
ExpiresByType text/javascript A86400
ExpiresByType application/x-shockwave-flash A2592000
#
<FilesMatch "\.(gif|jpe?g|png|ico|css|js|swf)$">
Header set Cache-Control "public"
</FilesMatch>

Rmi connection refused with localhost

It seems to work when I replace the

Runtime.getRuntime().exec("rmiregistry 2020");

by

LocateRegistry.createRegistry(2020);

anyone an idea why? What's the difference?

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

Use try_files and named location block ('@apachesite'). This will remove unnecessary regex match and if block. More efficient.

location / {
    root /path/to/root/of/static/files;
    try_files $uri $uri/ @apachesite;

    expires max;
    access_log off;
}

location @apachesite {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

Update: The assumption of this config is that there doesn't exist any php script under /path/to/root/of/static/files. This is common in most modern php frameworks. In case your legacy php projects have both php scripts and static files mixed in the same folder, you may have to whitelist all of the file types you want nginx to serve.

#pragma pack effect

#pragma is used to send non-portable (as in this compiler only) messages to the compiler. Things like disabling certain warnings and packing structs are common reasons. Disabling specific warnings is particularly useful if you compile with the warnings as errors flag turned on.

#pragma pack specifically is used to indicate that the struct being packed should not have its members aligned. It's useful when you have a memory mapped interface to a piece of hardware and need to be able to control exactly where the different struct members point. It is notably not a good speed optimization, since most machines are much faster at dealing with aligned data.

ElasticSearch: Unassigned Shards, how to fix?

Might help, but I had this issue when trying to run ES in embedded mode. Fix was to make sure the Node had local(true) set.

Is it possible to GROUP BY multiple columns using MySQL?

To use a simple example, I had a counter that needed to summarise unique IP addresses per visited page on a site. Which is basically grouping by pagename and then by IP. I solved it with a combination of DISTINCT and GROUP BY.

SELECT pagename, COUNT(DISTINCT ipaddress) AS visit_count FROM log_visitors GROUP BY pagename ORDER BY visit_count DESC;

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

select CONVERT(NVARCHAR, SYSDATETIME(), 106) AS [DD-MON-YYYY]

or else

select REPLACE(CONVERT(NVARCHAR,GETDATE(), 106), ' ', '-')

both works fine

nginx error "conflicting server name" ignored

There should be only one localhost defined, check sites-enabled or nginx.conf.

Android Device Chooser -- device not showing up

I'm on a MAC and for some reason when I connected my device via USB there was a weird mount called USB-Drivers which when I UNmounted from Finder, the Androide Device Chooser instantly recognized my device.

How to get a random number in Ruby

Simplest answer to the question:

rand(0..n)

Multiple contexts with the same path error running web service in Eclipse using Tomcat

In my case I found duplicate paths in Servers/Tomcat5.5 at localhost-config/server.xml under tag. Removing the duplicates solved the problem.

Javascript Equivalent to C# LINQ Select

I know it is a late answer but it was useful to me! Just to complete, using the $.grep function you can emulate the linq where().

Linq:

var maleNames = people
.Where(p => p.Sex == "M")
.Select(p => p.Name)

Javascript:

// replace where  with $.grep
//         select with $.map
var maleNames = $.grep(people, function (p) { return p.Sex == 'M'; })
            .map(function (p) { return p.Name; });

How to solve "Fatal error: Class 'MySQLi' not found"?

install phpXX-extension by PHP. In my FreeBSD's case:

pkg install php74-extensions

What is the difference between char s[] and char *s?

char *str = "Hello";

The above sets str to point to the literal value "Hello" which is hard-coded in the program's binary image, which is flagged as read-only in memory, means any change in this String literal is illegal and that would throw segmentation faults.

char str[] = "Hello";

copies the string to newly allocated memory on the stack. Thus making any change in it is allowed and legal.

means str[0] = 'M';

will change the str to "Mello".

For more details, please go through the similar question:

Why do I get a segmentation fault when writing to a string initialized with "char *s" but not "char s[]"?

Limiting floats to two decimal points

You can modify the output format:

>>> a = 13.95
>>> a
13.949999999999999
>>> print "%.2f" % a
13.95

Android Studio 3.0 Flavor Dimension Issue

I have used flavorDimensions for my application in build.gradle (Module: app)

flavorDimensions "tier"

productFlavors {
    production {
        flavorDimensions "tier"
        //manifestPlaceholders = [appName: APP_NAME]
        //signingConfig signingConfigs.config
    }
    staging {
        flavorDimensions "tier"
        //manifestPlaceholders = [appName: APP_NAME_STAGING]
        //applicationIdSuffix ".staging"
        //versionNameSuffix "-staging"
        //signingConfig signingConfigs.config
    }
}

Check this link for more info

// Specifies two flavor dimensions.
flavorDimensions "tier", "minApi"

productFlavors {
     free {
            // Assigns this product flavor to the "tier" flavor dimension. Specifying
            // this property is optional if you are using only one dimension.
            dimension "tier"
            ...
     }

     paid {
            dimension "tier"
            ...
     }

     minApi23 {
            dimension "minApi"
            ...
     }

     minApi18 {
            dimension "minApi"
            ...
     }
}

Simple PHP form: Attachment to email (code golf)

I haven't tested the email part of this (my test box does not send email) but I think it will work.

<?php
if ($_POST) {
$s = md5(rand());
mail('[email protected]', 'attachment', "--$s

{$_POST['m']}
--$s
Content-Type: application/octet-stream; name=\"f\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

".chunk_split(base64_encode(join(file($_FILES['f']['tmp_name']))))."
--$s--", "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$s\"");
exit;
}
?>
<form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<textarea name="m"></textarea><br>
<input type="file" name="f"/><br>
<input type="submit">
</form>

How can I draw vertical text with CSS cross-browser?

If you use Bootstrap 3, you can use one of it's mixins:

.rotate(degrees);

Example:

.rotate(-90deg);

Using SSH keys inside docker container

One cross-platform solution is to use a bind mount to share the host's .ssh folder to the container:

docker run -v /home/<host user>/.ssh:/home/<docker user>/.ssh <image>

Similar to agent forwarding this approach will make the public keys accessible to the container. An additional upside is that it works with a non-root user too and will get you connected to GitHub. One caveat to consider, however, is that all contents (including private keys) from the .ssh folder will be shared so this approach is only desirable for development and only for trusted container images.

BackgroundWorker vs background Thread

Also you are tying up a threadpool thread for the lifetime of the background worker, which may be of concern as there are only a finite number of them. I would say that if you are only ever creating the thread once for your app (and not using any of the features of background worker) then use a thread, rather than a backgroundworker/threadpool thread.

getCurrentPosition() and watchPosition() are deprecated on insecure origins

Use FireFox or any other browser instead of Chrome if you want to test it on your development environment, for production there is no way except using https.

For development environment just open http://localhost:8100/ on FireFox and alas no such error.

Is there any JSON Web Token (JWT) example in C#?

Here is the list of classes and functions:

open System
open System.Collections.Generic
open System.Linq
open System.Threading.Tasks
open Microsoft.AspNetCore.Mvc
open Microsoft.Extensions.Logging
open Microsoft.AspNetCore.Authorization
open Microsoft.AspNetCore.Authentication
open Microsoft.AspNetCore.Authentication.JwtBearer
open Microsoft.IdentityModel.Tokens
open System.IdentityModel.Tokens
open System.IdentityModel.Tokens.Jwt
open Microsoft.IdentityModel.JsonWebTokens
open System.Text
open Newtonsoft.Json
open System.Security.Claims
    let theKey = "VerySecretKeyVerySecretKeyVerySecretKey"
    let securityKey = SymmetricSecurityKey(Encoding.UTF8.GetBytes(theKey))
    let credentials = SigningCredentials(securityKey, SecurityAlgorithms.RsaSsaPssSha256)
    let expires = DateTime.UtcNow.AddMinutes(123.0) |> Nullable
    let token = JwtSecurityToken(
                    "lahoda-pro-issuer", 
                    "lahoda-pro-audience",
                    claims = null,
                    expires =  expires,
                    signingCredentials = credentials
        )

    let tokenString = JwtSecurityTokenHandler().WriteToken(token)

Placeholder Mixin SCSS/CSS

To avoid 'Unclosed block: CssSyntaxError' errors being thrown from sass compilers add a ';' to the end of @content.

@mixin placeholder {
   ::-webkit-input-placeholder { @content;}
   :-moz-placeholder           { @content;}
   ::-moz-placeholder          { @content;}
   :-ms-input-placeholder      { @content;}
}

how to call a method in another Activity from Activity

The startActivityForResult pattern is much better suited for what you're trying to achieve : http://developer.android.com/reference/android/app/Activity.html#StartingActivities

Try below code

public class MainActivity extends Activity {  

    Button button1;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        textView1=(TextView)findViewById(R.id.textView1);  
        button1=(Button)findViewById(R.id.button1);  
        button1.setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View arg0) {  
                Intent intent=new Intent(MainActivity.this,SecondActivity.class);  
                startActivityForResult(intent, 2);// Activity is started with requestCode 2  
            }  
        });  
    }  
 // Call Back method  to get the Message form other Activity  
    @Override  
       protected void onActivityResult(int requestCode, int resultCode, Intent data)  
       {  
                 super.onActivityResult(requestCode, resultCode, data);  
                  // check if the request code is same as what is passed  here it is 2  
                   if(requestCode==2)  
                         {  
                          //do the things u wanted 
                         }  
     }  

} 

SecondActivity.class

public class SecondActivity extends Activity {  

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

            button1=(Button)findViewById(R.id.button1);  
            button1.setOnClickListener(new OnClickListener() {  
                @Override  
                public void onClick(View arg0) {  
                    String message="hello ";  
                    Intent intent=new Intent();  
                    intent.putExtra("MESSAGE",message);  
                    setResult(2,intent);  
                    finish();//finishing activity  
                }  
            });  
    }  

}  

Let me know if it helped...

How can I suppress the newline after a print statement?

The question asks: "How can it be done in Python 3?"

Use this construct with Python 3.x:

for item in [1,2,3,4]:
    print(item, " ", end="")

This will generate:

1  2  3  4

See this Python doc for more information:

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

--

Aside:

in addition, the print() function also offers the sep parameter that lets one specify how individual items to be printed should be separated. E.g.,

In [21]: print('this','is', 'a', 'test')  # default single space between items
this is a test

In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items
thisisatest

In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation
this--*--is--*--a--*--test

CSS: background-color only inside the margin

If your margin is set on the body, then setting the background color of the html tag should color the margin area

html { background-color: black; }
body { margin:50px; background-color: white; }

http://jsfiddle.net/m3zzb/

Or as dmackerman suggestions, set a margin of 0, but a border of the size you want the margin to be and set the border-color

Can I hide/show asp:Menu items based on role?

You can bind the menu items to a site map and use the roles attribute. You will need to enable Security Trimming in your Web.Config to do this. This is the simplest way.

Site Navigation Overview: http://msdn.microsoft.com/en-us/library/e468hxky.aspx

Security Trimming Info: http://msdn.microsoft.com/en-us/library/ms178428.aspx

SiteMap Binding Info: http://www.w3schools.com/aspnet/aspnet_navigation.asp

Good Tutorial/Overview here: http://weblogs.asp.net/jgalloway/archive/2008/01/26/asp-net-menu-and-sitemap-security-trimming-plus-a-trick-for-when-your-menu-and-security-don-t-match-up.aspx

Another option that works, but is less ideal is to use the loginview control which can display controls based on role. This might be the quickest (but least flexible/performant) option. You can find a guide here: http://weblogs.asp.net/sukumarraju/archive/2010/07/28/role-based-authorization-using-loginview-control.aspx

What possibilities can cause "Service Unavailable 503" error?

If the server doesn't have enough memory also will cause this problem. This is my personal experience with Godaddy VPS.

What is the (function() { } )() construct in JavaScript?

That construct is called an Immediately Invoked Function Expression (IIFE) which means it gets executed immediately. Think of it as a function getting called automatically when the interpreter reaches that function.

Most Common Use-case:

One of its most common use cases is to limit the scope of a variable made via var. Variables created via var have a scope limited to a function so this construct (which is a function wrapper around certain code) will make sure that your variable scope doesn't leak out of that function.

In following example, count will not be available outside the immediately invoked function i.e. the scope of count will not leak out of the function. You should get a ReferenceError, should you try to access it outside of the immediately invoked function anyway.

(function () { 
    var count = 10;
})();
console.log(count);  // Reference Error: count is not defined

ES6 Alternative (Recommended)

In ES6, we now can have variables created via let and const. Both of them are block-scoped (unlike var which is function-scoped).

Therefore, instead of using that complex construct of IIFE for the use case I mentioned above, you can now write much simpler code to make sure that a variable's scope does not leak out of your desired block.

{ 
    let count = 10;
}
console.log(count);  // ReferenceError: count is not defined

In this example, we used let to define count variable which makes count limited to the block of code, we created with the curly brackets {...}.

I call it a “Curly Jail”.

Preferred way to create a Scala list

And for simple cases:

val list = List(1,2,3) 

:)

What is a smart pointer and when should I use one?

Smart Pointers are those where you don't have to worry about Memory De-Allocation, Resource Sharing and Transfer.

You can very well use these pointer in the similar way as any allocation works in Java. In java Garbage Collector does the trick, while in Smart Pointers, the trick is done by Destructors.

What's a concise way to check that environment variables are set in a Unix shell script?

We can write a nice assertion to check a bunch of variables all at once:

#
# assert if variables are set (to a non-empty string)
# if any variable is not set, exit 1 (when -f option is set) or return 1 otherwise
#
# Usage: assert_var_not_null [-f] variable ...
#
function assert_var_not_null() {
  local fatal var num_null=0
  [[ "$1" = "-f" ]] && { shift; fatal=1; }
  for var in "$@"; do
    [[ -z "${!var}" ]] &&
      printf '%s\n' "Variable '$var' not set" >&2 &&
      ((num_null++))
  done

  if ((num_null > 0)); then
    [[ "$fatal" ]] && exit 1
    return 1
  fi
  return 0
}

Sample invocation:

one=1 two=2
assert_var_not_null one two
echo test 1: return_code=$?
assert_var_not_null one two three
echo test 2: return_code=$?
assert_var_not_null -f one two three
echo test 3: return_code=$? # this code shouldn't execute

Output:

test 1: return_code=0
Variable 'three' not set
test 2: return_code=1
Variable 'three' not set

More such assertions here: https://github.com/codeforester/base/blob/master/lib/assertions.sh

How to select the first element of a set with JSTL?

You can use the EL 3.0 Stream API.

<div>${attachments.stream().findFirst().get()}</div>

Be careful! The EL 3.0 Stream API was finalized before the Java 8 Stream API and it is different than that. They can't sunc both apis because it will break the backward compatibility.

Errors: Data path ".builders['app-shell']" should have required property 'class'

Following worked for me

npm uninstall @angular-devkit/build-angular
npm install @angular-devkit/[email protected]

How to automatically generate getters and setters in Android Studio

Use Ctrl+Enter on Mac to get list of options to generate setter, getter, constructor etc

enter image description here

Android Support Design TabLayout: Gravity Center and Mode Scrollable

keeps things simple just add app:tabMode="scrollable" and android:layout_gravity= "bottom"

just like this

<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="bottom"
app:tabMode="scrollable"
app:tabIndicatorColor="@color/colorAccent" />

enter image description here

How to install popper.js with Bootstrap 4?

Instead of remotely putting popper js from CDN you can directly install it in your angular project.

Try this.

npm install popper.js --save 

This query installs an updated version of popper.js Don't mention any version there, it will work for you.

sed command with -i option failing on Mac, but works on Linux

This works with both GNU and BSD versions of sed:

sed -i'' -e 's/old_link/new_link/g' *

or with backup:

sed -i'.bak' -e 's/old_link/new_link/g' *

Note missing space after -i option! (Necessary for GNU sed)

How to find the day, month and year with moment.js

I am getting day, month and year using dedicated functions moment().date(), moment().month() and moment().year() of momentjs.

_x000D_
_x000D_
let day = moment('2014-07-28', 'YYYY/MM/DD').date();_x000D_
let month = 1 + moment('2014-07-28', 'YYYY/MM/DD').month();_x000D_
let year = moment('2014-07-28', 'YYYY/MM/DD').year();_x000D_
_x000D_
console.log(day);_x000D_
console.log(month);_x000D_
console.log(year);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

I don't know why there are 48 upvotes for @Chris Schmitz answer which is not 100% correct.

Month is in form of array and starts from 0 so to get exact value we should use 1 + moment().month()

How do I exit a foreach loop in C#?

During testing I found that foreach loop after break go to the loop beging and not out of the loop. So I changed foreach into for and break in this case work correctly- after break program flow goes out of the loop.

Converting List<Integer> to List<String>

Not core Java, and not generic-ified, but the popular Jakarta commons collections library has some useful abstractions for this sort of task. Specifically, have a look at the collect methods on

CollectionUtils

Something to consider if you are already using commons collections in your project.

Copying files from one directory to another in Java

There is no file copy method in the Standard API (yet). Your options are:

  • Write it yourself, using a FileInputStream, a FileOutputStream and a buffer to copy bytes from one to the other - or better yet, use FileChannel.transferTo()
  • User Apache Commons' FileUtils
  • Wait for NIO2 in Java 7

Percentage width in a RelativeLayout

I have solved this creating a custom View:

public class FractionalSizeView extends View {
  public FractionalSizeView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

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

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = MeasureSpec.getSize(widthMeasureSpec);
    setMeasuredDimension(width * 70 / 100, 0);
  }
}

This is invisible strut I can use to align other views within RelativeLayout.

How to get year/month/day from a date object?

Use the Date get methods.

http://www.tizag.com/javascriptT/javascriptdate.php

http://www.htmlgoodies.com/beyond/javascript/article.php/3470841

var dateobj= new Date() ;
var month = dateobj.getMonth() + 1;
var day = dateobj.getDate() ;
var year = dateobj.getFullYear();

Using PUT method in HTML form

I wrote an npm package called 'html-form-enhancer'. By dropping it into your HTML source, it takes over submission of forms with methods aside from GET and POST, and also adds application/json serialization.

<script type=module" src="html-form-enhancer.js"></script>

<form method="PUT">
...
</form>

PHP - iterate on string characters

If your strings are in Unicode you should use preg_split with /u modifier

From comments in php documentation:

function mb_str_split( $string ) { 
    # Split at all position not after the start: ^ 
    # and not before the end: $ 
    return preg_split('/(?<!^)(?!$)/u', $string ); 
} 

Getting HTML elements by their attribute names

With prototypejs :

 $$('span[property=v.name]');

or

document.body.select('span[property=v.name]');

Both return an array

Why do I get "warning longer object length is not a multiple of shorter object length"?

I had a similar issue and using %in% operator instead of the == (equality) operator was the solution:

# %in%

Hope it helps.

Eclipse jump to closing brace

With Ctrl + Shift + L you can open the "key assist", where you can find all the shortcuts.

Terminating idle mysql connections

I don't see any problem, unless you are not managing them using a connection pool.

If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

Input mask for numeric and decimal

Now that I understand better what you need, here's what I propose. Add a keyup handler for your textbox that checks the textbox contents with this regex ^[0-9]{1,14}\.[0-9]{2}$ and if it doesn't match, make the background red or show a text or whatever you like. Here's the code to put in document.ready

$(document).ready(function() {
    $('selectorForTextbox').bind('keyup', function(e) {
        if (e.srcElement.value.match(/^[0-9]{1,14}\.[0-9]{2}$/) === null) {
            $(this).addClass('invalid');
        } else {
            $(this).removeClass('invalid');
        }
    });
});

Here's a JSFiddle of this in action. Also, do the same regex server side and if it doesn't match, the requirements have not been met. You can also do this check the onsubmit event and not let the user submit the page if the regex didn't match.

The reason for not enforcing the mask upon text inserting is that it complicates things a lot, e.g. as I mentioned in the comment, the user cannot begin entering the valid input since the beggining of it is not valid. It is possible though, but I suggest this instead.

AngularJS : The correct way of binding to a service properties

To bind any data,which sends service is not a good idea (architecture),but if you need it anymore I suggest you 2 ways to do that

1) you can get the data not inside you service.You can get data inside your controller/directive and you will not have a problem to bind it anywhere

2) you can use angularjs events.Whenever you want,you can send a signal(from $rootScope) and catch it wherever you want.You can even send a data on that eventName.

Maybe this can help you. If you need more with examples,here is the link

http://www.w3docs.com/snippets/angularjs/bind-value-between-service-and-controller-directive.html

JSON Invalid UTF-8 middle byte

I got this exception when in the Java Client Application I was serializing a JSON like this

String json = mapper.writeValueAsString(contentBean);

and on the Server Side I was using Spring Boot as REST Endpoint. Exception was:

nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 start byte 0xaa

My problem was, that I was not setting the correct encoding on the HTTP Client. This solved my problem:

updateRequest.setHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity entity= new StringEntity(json, "UTF-8");
updateRequest.setEntity(entity);

Android set content type HttpPost

Best way to check for null values in Java?

We can use Object.requireNonNull static method of Object class. Implementation is below

public void someMethod(SomeClass obj) {
    Objects.requireNonNull(obj, "Validation error, obj cannot be null");
}

Can I display the value of an enum with printf()?

As a string, no. As an integer, %d.

Unless you count:

static char* enumStrings[] = { /* filler 0's to get to the first value, */
                               "enum0", "enum1", 
                               /* filler for hole in the middle: ,0 */
                               "enum2", "enum3", .... };

...

printf("The value is %s\n", enumStrings[thevalue]);

This won't work for something like an enum of bit masks. At that point, you need a hash table or some other more elaborate data structure.

how to parse JSON file with GSON

just parse as an array:

Review[] reviews = new Gson().fromJson(jsonString, Review[].class);

then if you need you can also create a list in this way:

List<Review> asList = Arrays.asList(reviews);

P.S. your json string should be look like this:

[
    {
        "reviewerID": "A2SUAM1J3GNN3B1",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },
    {
        "reviewerID": "A2SUAM1J3GNN3B2",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },

    [...]
]

What is the difference between Scrum and Agile Development?

As mentioned above by others,

Scrum is an iterative and incremental agile software development method for managing software projects and product or application development. So Scrum is in fact a type of Agile approach which is used widely in software developments.

So, Scrum is a specific flavor of Agile, specifically it is referred to as an agile project management framework.

Also Scrum has mainly two roles inside it, which are: 1. Main/Core Role 2. Ancillary Role

Main/Core role: It consists of mainly three roles: a). Scrum Master, b). Product Owner, c). Development Team.

Ancillary Role: The ancillary roles in Scrum teams are those with no formal role and infrequent involvement in the Scrum procession but nonetheless, they must be taken into account. viz. Stakeholders, Managers.

Scrum Master:- There are 6 types of meetings in scrum:

  • Daily Scrum / Standup
  • Backlog grooming: storyline
  • Scrum of Scrums
  • Sprint Planning meeting
  • Sprint review meeting
  • Sprint retrospective

Let me know if any one need more inputs on this.

How to resolve /var/www copy/write permission denied?

are you in a develpment enviroment? why just not do

chown -R user.group /var/www

so you will be able to write with your user.

How do I monitor all incoming http requests?

I would install Microsoft Network Monitor, configure the tool so it would only see HTTP packets (filter the port) and start capturing packets.

You could download it here

How to find if div with specific id exists in jQuery?

You can handle it in different ways,

Objective is to check if the div exist then execute the code. Simple.

Condition:

$('#myDiv').length

Note:

#myDiv -> < div id='myDiv' > <br>
.myDiv -> < div class='myDiv' > 

This will return a number every time it is executed so if there is no div it will give a Zero [0], and as we no 0 can be represented as false in binary so you can use it in if statement. And you can you use it as a comparison with a none number. while any there are three statement given below

// Statement 0
// jQuery/Ajax has replace [ document.getElementById with $ sign ] and etc
// if you don't want to use jQuery/ajax 

   if (document.getElementById(name)) { 
      $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

// Statement 1
   if ($('#'+ name).length){ // if 0 then false ; if not 0 then true
       $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

// Statement 2
    if(!$('#'+ name).length){ // ! Means Not. So if it 0 not then [0 not is 1]
           $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>"); 
    }
// Statement 3
    if ($('#'+ name).length > 0 ) {
      $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

// Statement 4
    if ($('#'+ name).length !== 0 ) { // length not equal to 0 which mean exist.
       $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

In case it helps anyone I will post what worked for me.

I had to plug my S3 into a direct USB port of my PC for it to prompt me to accept the RSA signature. I had my S3 plugged into a hub before then.

Now the S3 is detected when using both the direct USB port of the PC and via the hub.

NOTE - You may need to also run adb devices from the command line to get your S3 to re-request permission.

D:\apps\android-sdk-windows\platform-tools>adb devices
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
9283759342847566        unauthorized

...accept signature on phone...

D:\apps\android-sdk-windows\platform-tools>adb devices
List of devices attached
9283759342847566        device

LINQ Orderby Descending Query

I think this first failed because you are ordering value which is null. If Delivery is a foreign key associated table then you should include this table first, example below:

var itemList = from t in ctn.Items.Include(x=>x.Delivery)
                    where !t.Items && t.DeliverySelection
                    orderby t.Delivery.SubmissionDate descending
                    select t;

Composer - the requested PHP extension mbstring is missing from your system

I set the PHPRC variable and uncommented zend_extension=php_opcache.dll in php.ini and all works well.

How to exit an application properly

Just Close() all active/existing forms and the application should exit.

How do I remove an array item in TypeScript?

Same way as you would in JavaScript.

delete myArray[key];

Note that this sets the element to undefined.

Better to use the Array.prototype.splice function:

const index = myArray.indexOf(key, 0);
if (index > -1) {
   myArray.splice(index, 1);
}

Distinct pair of values SQL

This will give you the result you're giving as an example:

SELECT DISTINCT a, b
FROM pairs

How to SUM two fields within an SQL query

Just a reminder on adding columns. If one of the values is NULL the total of those columns becomes NULL. Thus why some posters have recommended coalesce with the second parameter being 0

I know this was an older posting but wanted to add this for completeness.

python NameError: name 'file' is not defined

To solve this error, it is enough to add from google.colab import files in your code!

Remove blank attributes from an Object in Javascript

Shortest one liners for ES6+

Filter all falsy values ( "", 0, false, null, undefined )

Object.entries(obj).reduce((a,[k,v]) => (v ? (a[k]=v, a) : a), {})

Filter null and undefined values:

Object.entries(obj).reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {})

Filter ONLY null

Object.entries(obj).reduce((a,[k,v]) => (v === null ? a : (a[k]=v, a)), {})

Filter ONLY undefined

Object.entries(obj).reduce((a,[k,v]) => (v === undefined ? a : (a[k]=v, a)), {})

Recursive Solutions: Filters null and undefined

For Objects:

const cleanEmpty = obj => Object.entries(obj)
        .map(([k,v])=>[k,v && typeof v === "object" ? cleanEmpty(v) : v])
        .reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {});

For Objects and Arrays:

const cleanEmpty = obj => {
  if (Array.isArray(obj)) { 
    return obj
        .map(v => (v && typeof v === 'object') ? cleanEmpty(v) : v)
        .filter(v => !(v == null)); 
  } else { 
    return Object.entries(obj)
        .map(([k, v]) => [k, v && typeof v === 'object' ? cleanEmpty(v) : v])
        .reduce((a, [k, v]) => (v == null ? a : (a[k]=v, a)), {});
  } 
}

AngularJS - $http.post send data as json

Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one):

$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
        .then(function (response) {
            return response;
        });

How a thread should close itself in Java?

If you want to terminate the thread, then just returning is fine. You do NOT need to call Thread.currentThread().interrupt() (it will not do anything bad though. It's just that you don't need to.) This is because interrupt() is basically used to notify the owner of the thread (well, not 100% accurate, but sort of). Because you are the owner of the thread, and you decided to terminate the thread, there is no one to notify, so you don't need to call it.

By the way, why in the first case we need to use currentThread? Is Thread does not refer to the current thread?

Yes, it doesn't. I guess it can be confusing because e.g. Thread.sleep() affects the current thread, but Thread.sleep() is a static method.

If you are NOT the owner of the thread (e.g. if you have not extended Thread and coded a Runnable etc.) you should do

Thread.currentThread().interrupt();
return;

This way, whatever code that called your runnable will know the thread is interrupted = (normally) should stop whatever it is doing and terminate. As I said earlier, it is just a mechanism of communication though. The owner might simply ignore the interrupted status and do nothing.. but if you do set the interrupted status, somebody might thank you for that in the future.

For the same reason, you should never do

Catch(InterruptedException ie){
     //ignore
}

Because if you do, you are stopping the message there. Instead one should do

Catch(InterruptedException ie){
    Thread.currentThread().interrupt();//preserve the message
    return;//Stop doing whatever I am doing and terminate
}

Single vs Double quotes (' vs ")

If it's all the same, perhaps using single-quotes is better since it doesn't require holding down the shift key. Fewer keystrokes == less chance of RSI.

Different color for each bar in a bar chart; ChartJS

If you're not able to use NewChart.js you just need to change the way to set the color using array instead. Find the helper iteration inside Chart.js:

Replace this line:

fillColor : dataset.fillColor,

For this one:

fillColor : dataset.fillColor[index],

The resulting code:

//Iterate through each of the datasets, and build this into a property of the chart
  helpers.each(data.datasets,function(dataset,datasetIndex){

    var datasetObject = {
      label : dataset.label || null,
      fillColor : dataset.fillColor,
      strokeColor : dataset.strokeColor,
      bars : []
    };

    this.datasets.push(datasetObject);

    helpers.each(dataset.data,function(dataPoint,index){
      //Add a new point for each piece of data, passing any required data to draw.
      datasetObject.bars.push(new this.BarClass({
        value : dataPoint,
        label : data.labels[index],
        datasetLabel: dataset.label,
        strokeColor : dataset.strokeColor,
        //Replace this -> fillColor : dataset.fillColor,
        // Whith the following:
        fillColor : dataset.fillColor[index],
        highlightFill : dataset.highlightFill || dataset.fillColor,
        highlightStroke : dataset.highlightStroke || dataset.strokeColor
      }));
    },this);

  },this);

And in your js:

datasets: [
                {
                  label: "My First dataset",
                  fillColor: ["rgba(205,64,64,0.5)", "rgba(220,220,220,0.5)", "rgba(24,178,235,0.5)", "rgba(220,220,220,0.5)"],
                  strokeColor: "rgba(220,220,220,0.8)",
                  highlightFill: "rgba(220,220,220,0.75)",
                  highlightStroke: "rgba(220,220,220,1)",
                  data: [2000, 1500, 1750, 50]
                }
              ]

C# - insert values from file into two arrays

var Text = File.ReadAllLines("Path"); foreach (var i in Text) {    var SplitText = i.Split().Where(x=> x.Lenght>1).ToList();    //@Array1 add SplitText[0]    //@Array2 add SpliteText[1]   }  

Display a decimal in scientific notation

This worked best for me:

import decimal
'%.2E' % decimal.Decimal('40800000000.00000000000000')
# 4.08E+10

Get DOM content of cross-domain iframe

If you have an access to that domain/iframe that is loaded, then you can use window.postMessage to communicate between iframe and the main window.

Read the DOM with JavaScript in iframe and send it via postMessage to the top window.

More info here: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

load Js file in HTML

I had the same problem, and found the answer. If you use node.js with express, you need to give it its own function in order for the js file to be reached. For example:

const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))

Symbolicating iPhone App Crash Reports

I prefer a script that will symbolicate all my crash logs.

Preconditions

Create a folder and put there 4 things:

  1. symbolicatecrash perl script - there are many SO answers that tells it's location

  2. The archive of the build that match the crashes (from Xcode Organizer. simple as Show in Finder and copy) [I don't sure this is necessery]

  3. All the xccrashpoint packages - (from Xcode Organizer. Show in Finder, you may copy all the packages in the directory, or the single xccrashpoint you would like to symbolicate)

  4. Add that short script to the directory:

    #!/bin/sh
    
    echo "cleaning old crashes from directory"
    rm -P *.crash
    rm -P *.xccrashpoint
    rm -r allCrashes
    echo "removed!"
    echo ""
    echo "--- START ---"
    echo ""
    
    mkdir allCrashes
    mkdir symboledCrashes
    find `ls -d *.xccrashpoint` -name "*.crash" -print -exec cp {} allCrashes/ \;
    
    cd allCrashes
    for crash in *.crash; do
        ../symbolicatecrash $crash > ../symboledCrashes/V$crash
    done
    cd ..
    
    echo ""
    echo "--- DONE ---"
    echo ""
    

The Script

When you run the script, you'll get 2 directories.

  1. allCrashes - all the crashes from all the xccrashpoint will be there.

  2. symboledCrashes - the same crashes but now with all the symbols.

  3. you DON'T need to clean the directory from old crashes before running the script. it will clean automatically. good luck!

How to convert a std::string to const char* or char*?

Use the .c_str() method for const char *.

You can use &mystring[0] to get a char * pointer, but there are a couple of gotcha's: you won't necessarily get a zero terminated string, and you won't be able to change the string's size. You especially have to be careful not to add characters past the end of the string or you'll get a buffer overrun (and probable crash).

There was no guarantee that all of the characters would be part of the same contiguous buffer until C++11, but in practice all known implementations of std::string worked that way anyway; see Does “&s[0]” point to contiguous characters in a std::string?.

Note that many string member functions will reallocate the internal buffer and invalidate any pointers you might have saved. Best to use them immediately and then discard.

Keyword not supported: "data source" initializing Entity Framework Context

Make sure you have Data Source and not DataSource in your connection string. The space is important. Trust me. I'm an idiot.

How do you connect to a MySQL database using Oracle SQL Developer?

Under Tools > Preferences > Databases there is a third party JDBC driver path that must be setup. Once the driver path is setup a separate 'MySQL' tab should appear on the New Connections dialog.

Note: This is the same jdbc connector that is available as a JAR download from the MySQL website.

Get filename from input [type='file'] using jQuery

This was a very important issue for me in order for my site to be multilingual. So here is my conclusion tested in Firefox and Chrome.

jQuery trigger comes in handy.

So this hides the standard boring type=file labels. You can place any label you want and format anyway. I customized a script from http://demo.smarttutorials.net/ajax1/. The script allows multiple file uploads with thumbnail preview and uses PHP and MySQL.

<form enctype="multipart/form-data" name='imageform' role="form"    ="imageform" method="post" action="upload_ajax.php">
    <div class="form-group">
        <div id="select_file">Select a file</div>
        <input class='file' type="file" style="display: none " class="form-control" name="images_up" id="images_up" placeholder="Please choose your image">
        <div id="my_file"></div>
        <span class="help-block"></span>
    </div>
    <div id="loader" style="display: none;">
        Please wait image uploading to server....
    </div>
    <input type="submit" value="Upload" name="image_upload" id="image_upload" class="btn"/>
</form>

$('#select_file').click(function() {
    $('#images_up').trigger('click');
    $('#images_up').change(function() {
        var filename = $('#images_up').val();
        if (filename.substring(3,11) == 'fakepath') {
            filename = filename.substring(12);
        } // Remove c:\fake at beginning from localhost chrome
        $('#my_file').html(filename);
   });
});

How to list files in an android directory?

Well, the AssetManager lists files within the assets folder that is inside of your APK file. So what you're trying to list in your example above is [apk]/assets/sdcard/Pictures.

If you put some pictures within the assets folder inside of your application, and they were in the Pictures directory, you would do mgr.list("/Pictures/").

On the other hand, if you have files on the sdcard that are outside of your APK file, in the Pictures folder, then you would use File as so:

File file = new File(Environment.getExternalStorageDirectory(), "Pictures");
File[] pictures = file.listFiles();
...
for (...)
{
log.e("FILE:", pictures[i].getAbsolutePath());
}

And relevant links from the docs:
File
Asset Manager

How can I solve equations in Python?

Use a different tool. Something like Wolfram Alpha, Maple, R, Octave, Matlab or any other algebra software package.

As a beginner you should probably not attempt to solve such a non-trivial problem.

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Even better, use DEFAULT instead of NULL. You want to store the default value, not a NULL that might trigger a default value.

But you'd better name all columns, with a piece of SQL you can create all the INSERT, UPDATE and DELETE's you need. Just check the information_schema and construct the queries you need. There is no need to do it all by hand, SQL can help you out.

Ping a site in Python?

It's hard to say what your question is, but there are some alternatives.

If you mean to literally execute a request using the ICMP ping protocol, you can get an ICMP library and execute the ping request directly. Google "Python ICMP" to find things like this icmplib. You might want to look at scapy, also.

This will be much faster than using os.system("ping " + ip ).

If you mean to generically "ping" a box to see if it's up, you can use the echo protocol on port 7.

For echo, you use the socket library to open the IP address and port 7. You write something on that port, send a carriage return ("\r\n") and then read the reply.

If you mean to "ping" a web site to see if the site is running, you have to use the http protocol on port 80.

For or properly checking a web server, you use urllib2 to open a specific URL. (/index.html is always popular) and read the response.

There are still more potential meaning of "ping" including "traceroute" and "finger".

Does SVG support embedding of bitmap images?

It is also possible to include bitmaps. I think you also can use transformations on that.

How to Change color of Button in Android when Clicked?

To deal properly for how long you want to have your button stay in your other color I would advise this version:

button.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        button.setBackground(getResources().getDrawable(R.drawable.on_click_drawable));
                        break;
                    case MotionEvent.ACTION_UP:
                        new java.util.Timer().schedule(
                                new java.util.TimerTask() {
                                    @Override
                                    public void run() {
                                        ((Activity) (getContext())).runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                button.setBackground(getResources().getDrawable(R.drawable.not_clicked_drawable));
                                            }
                                        });
                                    }
                                }, BUTTON_CLICK_TIME_AFTER_RELEASE_ANIMATION);
                        break;
                    default:
                }
                return false;
            }
        });

BUTTON_CLICK_TIME_AFTER_RELEASE_ANIMATION indicates after how much time [ms] the button will reset to the previous state (however you might want to use some boolean to check that the button hadn't been used in between, depending on what you want to achieve...).

Foreach in a Foreach in MVC View

Try this:

It looks like you are looping for every product each time, now this is looping for each product that has the same category ID as the current category being looped

<div id="accordion1" style="text-align:justify">
@using (Html.BeginForm())
{
    foreach (var category in Model.Categories)
    {
        <h3><u>@category.Name</u></h3>

        <div>
            <ul>    
                @foreach (var product in Model.Product.Where(m=> m.CategoryID= category.CategoryID)
                {
                    <li>
                        @product.Title
                        @if (System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal("/admin", User, "GET"))
                        {
                            @Html.Raw(" - ")  
                            @Html.ActionLink("Edit", "Edit", new { id = product.ID })
                        }
                        <ul>
                            <li>
                                @product.Description
                            </li>
                        </ul>
                    </li>
                }
            </ul>
        </div>
    }
}  

How to get on scroll events?

Alternative to @HostListener and scroll output on the element I would suggest using fromEvent from RxJS since you can chain it with filter() and distinctUntilChanges() and can easily skip flood of potentially redundant events (and change detections).

Here is a simple example:

// {static: true} can be omitted if you don't need this element/listener in ngOnInit
@ViewChild('elementId', {static: true}) el: ElementRef;

// ...

fromEvent(this.el.nativeElement, 'scroll')
  .pipe(
    // Is elementId scrolled for more than 50 from top?
    map((e: Event) => (e.srcElement as Element).scrollTop > 50),
    // Dispatch change only if result from map above is different from previous result
    distinctUntilChanged());

Compare two objects with .equals() and == operator

Your equals2() method always will return the same as equals() !!

Your code with my comments:

public boolean equals2(Object object2) {  // equals2 method
    if(a.equals(object2)) { // if equals() method returns true
        return true; // return true
    }
    else return false; // if equals() method returns false, also return false
}

How to check if an option is selected?

UPDATE

A more direct jQuery method to the option selected would be:

var selected_option = $('#mySelectBox option:selected');

Answering the question .is(':selected') is what you are looking for:

$('#mySelectBox option').each(function() {
    if($(this).is(':selected')) ...

The non jQuery (arguably best practice) way to do it would be:

$('#mySelectBox option').each(function() {
    if(this.selected) ...

Although, if you are just looking for the selected value try:

$('#mySelectBox').val()

If you are looking for the selected value's text do:

$('#mySelectBox option').filter(':selected').text();

Check out: http://api.jquery.com/selected-selector/

Next time look for duplicate SO questions:

Get current selected option or Set selected option or How to get $(this) selected option in jQuery? or option[selected=true] doesn't work

How to get Last record from Sqlite?

The previous answers assume that there is an incrementing integer ID column, so MAX(ID) gives the last row. But sometimes the keys are of text type, not ordered in a predictable way. So in order to take the last 1 or N rows (#Nrows#) we can follow a different approach:

Select * From [#TableName#]  LIMIT #Nrows# offset cast((SELECT count(*)  FROM [#TableName#]) AS INT)- #Nrows#

Simple GUI Java calculator

What you need is something that calculates the result of the infix notated calculation, have a look at the Shunting-Yard Algorithm.

There's an example in C++ on Wikipedia's page, but it shouldn't be too hard to implement it in Java.
And since it's the primary function of your calculator, I would advise you to not grab some codez from the Web in this Case (except all you want to do is building calculator GUIs).

How to quickly test some javascript code?

If you want to edit some complex javascript I suggest you use JsFiddle. Alternatively, for smaller pieces of javascript you can just run it through your browser URL bar, here's an example:

javascript:alert("hello world");

And, as it was already suggested both Firebug and Chrome developer tools have Javascript console, in which you can type in your javascript to execute. So do Internet Explorer 8+, Opera, Safari and potentially other modern browsers.

Setting transparent images background in IrfanView

You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.

You just need to re-open the image with IrfanView after changing the view color to white.

To change the viewing color in Irfanview go to:

Options > Properties/Settings > Viewing > Main window color

Recursively add the entire folder to a repository

In my case, there was a .git folder in the subdirectory because I had previously initialized a git repo there. When I added the subdirectory it simply added it as a subproject without adding any of the contained files.

I solved the issue by removing the git repository from the subdirectory and then re-adding the folder.

How to change Apache Tomcat web server port number

You need to edit the Tomcat/conf/server.xml and change the connector port. The connector setting should look something like this:

<Connector port="8080" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="20000" disableUploadTimeout="true" />

Just change the connector port from default 8080 to another valid port number.

How to check if field is null or empty in MySQL?

Either use

SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1 
from tablename

or

SELECT case when field1 IS NULL or field1 = ''
            then 'empty'
            else field1
       end as field1 
from tablename

If you only want to check for null and not for empty strings then you can also use ifnull() or coalesce(field1, 'empty'). But that is not suitable for empty strings.

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

Pandas every nth row

A solution I came up with when using the index was not viable ( possibly the multi-Gig .csv was too large, or I missed some technique that would allow me to reindex without crashing ).
Walk through one row at a time and add the nth row to a new dataframe.

import pandas as pd
from csv import DictReader

def make_downsampled_df(filename, interval):    
    with open(filename, 'r') as read_obj:
        csv_dict_reader = DictReader(read_obj)
        column_names = csv_dict_reader.fieldnames
        df = pd.DataFrame(columns=column_names)
    
        for index, row in enumerate(csv_dict_reader):
            if index % interval == 0:
               print(str(row))
               df = df.append(row, ignore_index=True)

    return df

How to find out the MySQL root password

Follow these steps to reset password in Windows system

  1. Stop Mysql service from task manager

  2. Create a text file and paste the below statement

MySQL 5.7.5 and earlier:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('yournewpassword');


MySQL 5.7.6 and later:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'yournewpassword';

  1. Save as mysql-init.txt and place it in 'C' drive.

  2. Open command prompt and paste the following

C:\> mysqld --init-file=C:\\mysql-init.txt

how to specify new environment location for conda create

I ran into a similar situation. I did have access to a larger data drive. Depending on your situation, and the access you have to the server you can consider

ln -s /datavol/path/to/your/.conda /home/user/.conda

Then subsequent conda commands will put data to the symlinked dir in datavol

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

Take with a grain of salt, didn't test.

- (BOOL)isModal {
     if([self presentingViewController])
         return YES;
     if([[[self navigationController] presentingViewController] presentedViewController] == [self navigationController])
         return YES;
     if([[[self tabBarController] presentingViewController] isKindOfClass:[UITabBarController class]])
         return YES;

    return NO;
 }

What is a callback function?

Let's keep it simple. What is a call back function?

Example by Parable and Analogy

I have a secretary. Everyday I ask her to: (i) drop off the firm's outgoing mail at the post office, and after she's done that, to do: (ii) whatever task I wrote for her on one of those sticky notes.

Now, what is the task on the sticky-note? The task varies from day to day.

Suppose on this particular day, I require her to print off some documents. So I write that down on the sticky note, and I pin it on her desk along with the outgoing mail she needs to post.

In summary:

  1. first, she needs to drop off the mail and
  2. immediately after that is done, she needs to print off some documents.

The call back function is that second task: printing off those documents. Because it is done AFTER the mail is dropped off, and also because the sticky note telling her to print the document is given to her along with the mail she needs to post.

Let's now tie this in with programming vocabulary

  • The method name in this case is: DropOffMail.
  • And the call back function is: PrintOffDocuments. The PrintOffDocuments is the call back function because we want the secretary to do that, only after DropOffMail has run.
  • So I would "pass: PrintOffDocuments as an "argument" to the DropOffMail method. This is an important point.

That's all it is. Nothing more. I hope that cleared it up for you - and if not, post a comment and I'll do my best to clarify.

Display Animated GIF

Create a package named “Utils” under src folder and create a class named “GifImageView”

public class GifImageView extends View {
    private InputStream mInputStream;
    private Movie mMovie;
    private int mWidth, mHeight;
    private long mStart;
    private Context mContext;
    public GifImageView(Context context) {
        super(context);
        this.mContext = context;
    }
    public GifImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public GifImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        if (attrs.getAttributeName(1).equals("background")) {
            int id = Integer.parseInt(attrs.getAttributeValue(1).substring(1));
            setGifImageResource(id);
        }
    }
    private void init() {
        setFocusable(true);
        mMovie = Movie.decodeStream(mInputStream);
        mWidth = mMovie.width();
        mHeight = mMovie.height();
        requestLayout();
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(mWidth, mHeight);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        long now = SystemClock.uptimeMillis();
        if (mStart == 0) {
            mStart = now;
        }
        if (mMovie != null) {
            int duration = mMovie.duration();
            if (duration == 0) {
                duration = 1000;
            }
            int relTime = (int) ((now - mStart) % duration);
            mMovie.setTime(relTime);
            mMovie.draw(canvas, 0, 0);
            invalidate();
        }
    }
    public void setGifImageResource(int id) {
        mInputStream = mContext.getResources().openRawResource(id);
        init();
    }
    public void setGifImageUri(Uri uri) {
        try {
            mInputStream = mContext.getContentResolver().openInputStream(uri);
            init();
        } catch (FileNotFoundException e) {
            Log.e("GIfImageView", "File not found");
        }
    }
}

Now define GifImageView in MainActivity File: src/activity/MainActivity.class

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GifImageView gifImageView = (GifImageView) findViewById(R.id.GifImageView);
        gifImageView.setGifImageResource(R.drawable.smartphone_drib);
    }
}

Now UI Part File: res/layout/activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:gravity="center"
    android:background="#111E39"
    tools:context=".Activity.MainActivity">
    <com.android.animatedgif.Utils.GifImageView
        android:id="@+id/GifImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

</RelativeLayout>

Resourece code : Android example

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

In my case: spring boot 2 ,multiple datasource(default and custom). entityManager.createQuery go wrong: 'entity is not mapped'

while debug, i find out that the entityManager's unitName is wrong(should be custom,but the fact is default) the right way:

@PersistenceContext(unitName = "customer1") // !important, 
private EntityManager em;

the customer1 is from the second datasource config class:

@Bean(name = "customer1EntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
        @Qualifier("customer1DataSource") DataSource dataSource) {
    return builder.dataSource(dataSource).packages("com.xxx.customer1Datasource.model")
            .persistenceUnit("customer1")
            // PersistenceUnit injects an EntityManagerFactory, and PersistenceContext
            // injects an EntityManager.
            // It's generally better to use PersistenceContext unless you really need to
            // manage the EntityManager lifecycle manually.
            // ?4?
            .properties(jpaProperties.getHibernateProperties(new HibernateSettings())).build();
}

Then,the entityManager is right.

But, em.persist(entity) doesn't work,and the transaction doesn't work.

Another important point is:

@Transactional("customer1TransactionManager") // !important
public Trade findNewestByJdpModified() {
    //test persist,working right!
    Trade t = new Trade();
    em.persist(t);
    log.info("t.id" + t.getSysTradeId());

    //test transactional, working right!
    int a = 3/0;
}

customer1TransactionManager is from the second datasource config class:

@Bean(name = "customer1TransactionManager")
public PlatformTransactionManager transactionManager(
        @Qualifier("customer1EntityManagerFactory") EntityManagerFactory entityManagerFactory) {
    return new JpaTransactionManager(entityManagerFactory);
}

The whole second datasource config class is :

package com.lichendt.shops.sync;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "customer1EntityManagerFactory", transactionManagerRef = "customer1TransactionManager",
        // ?1??????DAO???? ,????DAO?? com.xx.DAO??,????? com.xx.DAO
        basePackages = { "com.lichendt.customer1Datasource.dao" })
public class Custom1DBConfig {

    @Autowired
    private JpaProperties jpaProperties;

    @Bean(name = "customer1DatasourceProperties")
    @Qualifier("customer1DatasourceProperties")
    @ConfigurationProperties(prefix = "customer1.datasource")
    public DataSourceProperties customer1DataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean(name = "customer1DataSource")
    @Qualifier("customer1DatasourceProperties")
    @ConfigurationProperties(prefix = "customer1.datasource") //
    // ?2?datasource?????,???? ?mysql?yaml???
    public DataSource dataSource() {
        // return DataSourceBuilder.create().build();
        return customer1DataSourceProperties().initializeDataSourceBuilder().build();
    }

    @Bean(name = "customer1EntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
            @Qualifier("customer1DataSource") DataSource dataSource) {
        return builder.dataSource(dataSource).packages("com.lichendt.customer1Datasource.model") // ?3???????????
                .persistenceUnit("customer1")
                // PersistenceUnit injects an EntityManagerFactory, and PersistenceContext
                // injects an EntityManager.
                // It's generally better to use PersistenceContext unless you really need to
                // manage the EntityManager lifecycle manually.
                // ?4?
                .properties(jpaProperties.getHibernateProperties(new HibernateSettings())).build();
    }

    @Bean(name = "customer1TransactionManager")
    public PlatformTransactionManager transactionManager(
            @Qualifier("customer1EntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

How do you add an action to a button programmatically in xcode

CGRect buttonFrame = CGRectMake( 10, 80, 100, 30 );
        UIButton *button = [[UIButton alloc] initWithFrame: buttonFrame];
        [button setTitle: @"My Button" forState: UIControlStateNormal];
        [button addTarget:self action:@selector(btnSelected:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor: [UIColor redColor] forState: UIControlStateNormal];
[view addSubview:button];

How to view .img files?

you could use either PowerISO or WinRAR

Compare 2 arrays which returns difference

I know this is an old question, but I thought I would share this little trick.

var diff = $(old_array).not(new_array).get();

diff now contains what was in old_array that is not in new_array

How to vertically align into the center of the content of a div with defined width/height?

I would say to add a paragraph with a period in it and style it like so:

<p class="center">.</p>

<style>
.center {font-size: 0px; margin-bottom: anyPercentage%;}
</style>

You may need to toy around with the percentages to get it right

How can I get System variable value in Java?

Have you tried rebooting since you set the environment variable?

It appears that Windows keeps it's environment variable in some sort of cache, and rebooting is one method to refresh it. I'm not sure but there may be a different method, but if you are not going to be changing your variable value too often this may be good enough.

How to detect the device orientation using CSS media queries?

I would go for aspect-ratio, it offers way more possibilities.

/* Exact aspect ratio */
@media (aspect-ratio: 2/1) {
    ...
}

/* Minimum aspect ratio */
@media (min-aspect-ratio: 16/9) {
    ...
}

/* Maximum aspect ratio */
@media (max-aspect-ratio: 8/5) {
    ...
}

Both, orientation and aspect-ratio depend on the actual size of the viewport and have nothing todo with the device orientation itself.

Read more: https://dev.to/ananyaneogi/useful-css-media-query-features-o7f

How can you have SharePoint Link Lists default to opening in a new window?

It is not possible with the default Link List web part, but there are resources describing how to extend Sharepoint server-side to add this functionality.

Share Point Links Open in New Window
Changing Link Lists in Sharepoint 2007

SimpleDateFormat and locale based format string

String text = new SimpleDateFormat("E, MMM d, yyyy").format(date);

Find length of 2D array Python

Assuming input[row][col],

    rows = len(input)
    cols = map(len, input)  #list of column lengths

Why am I getting a FileNotFoundError?

The mistake I did was my code :

x = open('python.txt')

print(x)

But the problem was in file directory ,I saved it as python.txt instead of just python .

So my file path was ->C:\Users\noob\Desktop\Python\Course 2\python.txt.txt

That is why it was giving a error.

Name your file without .txt it will run.

TypeError: $.browser is undefined

Somewhere the code--either your code or a jQuery plugin--is calling $.browser to get the current browser type.

However, early has year the $.browser function was deprecated. Since then some bugs have been filed against it but because it is deprecated, the jQuery team has decided not to fix them. I've decided not to rely on the function at all.

I don't see any references to $.browser in your code, so the problem probably lies in one of your plugins. To find it, look at the source code for each plugin that you've referenced with a <script> tag.

As for how to fix it: well, it depends on the context. E.g., maybe there's an updated version of the problematic plugin. Or perhaps you can use another plugin that does something similar but doesn't depend on $.browser.

Error in Eclipse: "The project cannot be built until build path errors are resolved"

  1. Go to Project > Properties > Java Compiler > Building
  2. Look under Build Path Problems
  3. Un-check "Abort build when build path error occurs"
    It won't solve all your errors but at least it will let you run your program :)

Postfix is installed but how do I test it?

To check whether postfix is running or not

sudo postfix status

If it is not running, start it.

sudo postfix start

Then telnet to localhost port 25 to test the email id

ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix

Hi,
Are you there?
regards,
Admin
.

Do not forget the . at the end, which indicates end of line

Set Encoding of File to UTF8 With BOM in Sublime Text 3

Into the Preferences > Setting - Default

You will have the next by default:

// Display file encoding in the status bar
    "show_encoding": false

You could change it or like cdesmetz said set your user settings.

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

For those that are not overflowing but hiding by negative margin:

$('#element').height() + -parseInt($('#element').css("margin-top"));

(ugly but only one that works so far)

What is the difference between buffer and cache memory in Linux?

Buffer is an area of memory used to temporarily store data while it's being moved from one place to another.

Cache is a temporary storage area used to store frequently accessed data for rapid access. Once the data is stored in the cache, future use can be done by accessing the cached copy rather than re-fetching the original data, so that the average access time is shorter.

Note: buffer and cache can be allocated on disk as well

Iterator invalidation rules

C++03 (Source: Iterator Invalidation Rules (C++03))


Insertion

Sequence containers

  • vector: all iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated) [23.2.4.3/1]
  • deque: all iterators and references are invalidated, unless the inserted member is at an end (front or back) of the deque (in which case all iterators are invalidated, but references to elements are unaffected) [23.2.1.3/1]
  • list: all iterators and references unaffected [23.2.2.3/1]

Associative containers

  • [multi]{set,map}: all iterators and references unaffected [23.1.2/8]

Container adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

Erasure

Sequence containers

  • vector: every iterator and reference after the point of erase is invalidated [23.2.4.3/3]
  • deque: all iterators and references are invalidated, unless the erased members are at an end (front or back) of the deque (in which case only iterators and references to the erased members are invalidated) [23.2.1.3/4]
  • list: only the iterators and references to the erased element is invalidated [23.2.2.3/3]

Associative containers

  • [multi]{set,map}: only iterators and references to the erased elements are invalidated [23.1.2/8]

Container adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

Resizing

  • vector: as per insert/erase [23.2.4.2/6]
  • deque: as per insert/erase [23.2.1.2/1]
  • list: as per insert/erase [23.2.2.2/1]

Note 1

Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [23.1/11]

Note 2

It's not clear in C++2003 whether "end" iterators are subject to the above rules; you should assume, anyway, that they are (as this is the case in practice).

Note 3

The rules for invalidation of pointers are the sames as the rules for invalidation of references.

Deleting array elements in JavaScript - delete vs splice

Because delete only removes the object from the element in the array, the length of the array won't change. Splice removes the object and shortens the array.

The following code will display "a", "b", "undefined", "d"

myArray = ['a', 'b', 'c', 'd']; delete myArray[2];

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

Whereas this will display "a", "b", "d"

myArray = ['a', 'b', 'c', 'd']; myArray.splice(2,1);

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

Controller 'ngModel', required by directive '...', can't be found

As described here: Angular NgModelController, you should provide the <input with the required controller ngModel

<input submit-required="true" ng-model="user.Name"></input>

VBA copy cells value and format

Found this on OzGrid courtesy of Mr. Aaron Blood - simple direct and works.

Code:
Cells(1, 3).Copy Cells(1, 1)
Cells(1, 1).Value = Cells(1, 3).Value

However, I kinda suspect you were just providing us with an oversimplified example to ask the question. If you just want to copy formats from one range to another it looks like this...

Code:
Cells(1, 3).Copy
    Cells(1, 1).PasteSpecial (xlPasteFormats)
    Application.CutCopyMode = False

How do you convert a byte array to a hexadecimal string, and vice versa?

Two mashups which folds the two nibble operations into one.

Probably pretty efficient version:

public static string ByteArrayToString2(byte[] ba)
{
    char[] c = new char[ba.Length * 2];
    for( int i = 0; i < ba.Length * 2; ++i)
    {
        byte b = (byte)((ba[i>>1] >> 4*((i&1)^1)) & 0xF);
        c[i] = (char)(55 + b + (((b-10)>>31)&-7));
    }
    return new string( c );
}

Decadent linq-with-bit-hacking version:

public static string ByteArrayToString(byte[] ba)
{
    return string.Concat( ba.SelectMany( b => new int[] { b >> 4, b & 0xF }).Select( b => (char)(55 + b + (((b-10)>>31)&-7))) );
}

And reverse:

public static byte[] HexStringToByteArray( string s )
{
    byte[] ab = new byte[s.Length>>1];
    for( int i = 0; i < s.Length; i++ )
    {
        int b = s[i];
        b = (b - '0') + ((('9' - b)>>31)&-7);
        ab[i>>1] |= (byte)(b << 4*((i&1)^1));
    }
    return ab;
}

How to set the "Content-Type ... charset" in the request header using a HTML link

This is not possible from HTML on. The closest what you can get is the accept-charset attribute of the <form>. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.

To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).


Update: Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.

alt text

How can I get a count of the total number of digits in a number?

Answers already here work for unsigned integers, but I have not found good solutions for getting number of digits from decimals and doubles.

public static int Length(double number)
{
    number = Math.Abs(number);
    int length = 1;
    while ((number /= 10) >= 1)
        length++;
    return length;
}
//number of digits in 0 = 1,
//number of digits in 22.1 = 2,
//number of digits in -23 = 2

You may change input type from double to decimal if precision matters, but decimal has a limit too.

How do I make a WPF TextBlock show my text on multiple lines?

Nesting a stackpanel will cause the textbox to wrap properly:

<Viewbox Margin="120,0,120,0">
    <StackPanel Orientation="Vertical" Width="400">
        <TextBlock x:Name="subHeaderText" 
                   FontSize="20" 
                   TextWrapping="Wrap" 
                   Foreground="Black"
                   Text="Lorem ipsum dolor, lorem isum dolor,Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet " />
    </StackPanel>
</Viewbox>

CakePHP 3.0 installation: intl extension missing from system

If you are using latest version Ubuntu 16.04 or later just do

sudo apt-get install php-intl

Then restart your apache

sudo service apache2 restart

ASP.NET Button to redirect to another page

You can either do a Response.Redirect("YourPage.aspx"); or a Server.Transfer("YourPage.aspx"); on your button click event. So it's gonna be like the following:

protected void btnConfirm_Click(object sender, EventArgs e)
{
    Response.Redirect("YourPage.aspx");
    //or
    Server.Transfer("YourPage.aspx");
}

Update a local branch with the changes from a tracked remote branch

You don't use the : syntax - pull always modifies the currently checked-out branch. Thus:

git pull origin my_remote_branch

while you have my_local_branch checked out will do what you want.

Since you already have the tracking branch set, you don't even need to specify - you could just do...

git pull

while you have my_local_branch checked out, and it will update from the tracked branch.

How to create a new text file using Python

Looks like you forgot the mode parameter when calling open, try w:

file = open("copy.txt", "w") 
file.write("Your text goes here") 
file.close() 

The default value is r and will fail if the file does not exist

'r' open for reading (default)
'w' open for writing, truncating the file first

Other interesting options are

'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists

See Doc for Python2.7 or Python3.6

-- EDIT --

As stated by chepner in the comment below, it is better practice to do it with a withstatement (it guarantees that the file will be closed)

with open("copy.txt", "w") as file:
    file.write("Your text goes here")

Changing CSS style from ASP.NET code

As a NOT TO DO - Another way would be to use:

divControl.Attributes.Add("style", "height: number");

But don't use this as its messy and the answer by AviewAnew is the correct way.

Wildcards in a Windows hosts file

To add to the great suggestions already here, XIP.IO is a fantastic wildcard DNS server that's publicly available.

      myproject.127.0.0.1.xip.io  -- resolves to -->   127.0.0.1
  other.project.127.0.0.1.xip.io  -- resolves to -->   127.0.0.1
   other.machine.10.0.0.1.xip.io  -- resolves to -->   10.0.0.1

(The ability to specify non-loopback addresses is fantastic for testing sites on iOS devices where you cannot access a hosts file.)

If you combine this with some of the Apache configuration mentioned in other answers, you can potentially add VirtualHosts with zero setup.

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

Here it goes an example:

$.post("test.php", { 'choices[]': ["Jon", "Susan"] });

Hope it helps.

Combine two data frames by rows (rbind) when they have different sets of columns

Most of the base R answers address the situation where only one data.frame has additional columns or that the resulting data.frame would have the intersection of the columns. Since the OP writes I am hoping to retain the columns that do not match after the bind, an answer using base R methods to address this issue is probably worth posting.

Below, I present two base R methods: One that alters the original data.frames, and one that doesn't. Additionally, I offer a method that generalizes the non-destructive method to more than two data.frames.

First, let's get some sample data.

# sample data, variable c is in df1, variable d is in df2
df1 = data.frame(a=1:5, b=6:10, d=month.name[1:5])
df2 = data.frame(a=6:10, b=16:20, c = letters[8:12])

Two data.frames, alter originals
In order to retain all columns from both data.frames in an rbind (and allow the function to work without resulting in an error), you add NA columns to each data.frame with the appropriate missing names filled in using setdiff.

# fill in non-overlapping columns with NAs
df1[setdiff(names(df2), names(df1))] <- NA
df2[setdiff(names(df1), names(df2))] <- NA

Now, rbind-em

rbind(df1, df2)
    a  b        d    c
1   1  6  January <NA>
2   2  7 February <NA>
3   3  8    March <NA>
4   4  9    April <NA>
5   5 10      May <NA>
6   6 16     <NA>    h
7   7 17     <NA>    i
8   8 18     <NA>    j
9   9 19     <NA>    k
10 10 20     <NA>    l

Note that the first two lines alter the original data.frames, df1 and df2, adding the full set of columns to both.


Two data.frames, do not alter originals
To leave the original data.frames intact, first loop through the names that differ, return a named vector of NAs that are concatenated into a list with the data.frame using c. Then, data.frame converts the result into an appropriate data.frame for the rbind.

rbind(
  data.frame(c(df1, sapply(setdiff(names(df2), names(df1)), function(x) NA))),
  data.frame(c(df2, sapply(setdiff(names(df1), names(df2)), function(x) NA)))
)

Many data.frames, do not alter originals
In the instance that you have more than two data.frames, you could do the following.

# put data.frames into list (dfs named df1, df2, df3, etc)
mydflist <- mget(ls(pattern="df\\d+"))
# get all variable names
allNms <- unique(unlist(lapply(mydflist, names)))

# put em all together
do.call(rbind,
        lapply(mydflist,
               function(x) data.frame(c(x, sapply(setdiff(allNms, names(x)),
                                                  function(y) NA)))))

Maybe a bit nicer to not see the row names of original data.frames? Then do this.

do.call(rbind,
        c(lapply(mydflist,
                 function(x) data.frame(c(x, sapply(setdiff(allNms, names(x)),
                                                    function(y) NA)))),
          make.row.names=FALSE))

Linux command to check if a shell script is running or not

I was quite inspired by the last answer by mklement0 - I have few scripts/small programs I run at every reboot via /etc/crontab. I built on his answer and built a login script, which shows if my programs are still running. I execute this scripts.sh via .profile -file on every login, to get instant notification on each login.

cat scripts.sh 
#!/bin/bash

getscript() {
  pgrep -lf ".[ /]$1( |\$)"
}

script1=keepalive.sh
script2=logger_v3.py

# test if script 1 is running
if getscript "$script1" >/dev/null; then
  echo "$script1" is RUNNING
  else
    echo "$script1" is NOT running
fi

# test if script 2 is running:
if getscript "$script2" >/dev/null; then
  echo "$script2" is RUNNING
  else
    echo "$script2" is NOT running
fi

Is there an embeddable Webkit component for Windows / C# development?

There is OpenWebKitSharp, a fork of WebKit.NET 0.5 and very advanced. Details: http://code.google.com/p/open-webkit-sharp/

How to delete duplicate lines in a file without sorting it in Unix?

This can be achieved using awk
Below Line will display unique Values

awk file_name | uniq

You can output these unique values to a new file

awk file_name | uniq > uniq_file_name

new file uniq_file_name will contain only Unique values, no duplicates

determine DB2 text string length

Mostly we write below statement select * from table where length(ltrim(rtrim(field)))=10;

How to use lodash to find and return an object from Array?

You don't need Lodash or Ramda or any other extra dependency.

Just use the ES6 find() function in a functional way:

savedViews.find(el => el.description === view)

Sometimes you need to use 3rd-party libraries to get all the goodies that come with them. However, generally speaking, try avoiding dependencies when you don't need them. Dependencies can:

  • bloat your bundled code size,
  • you will have to keep them up to date,
  • and they can introduce bugs or security risks

Javascript geocoding from address to latitude and longitude numbers not working

The script tag to the api has changed recently. Use something like this to query the Geocoding API and get the JSON object back

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/geocode/json?address=THE_ADDRESS_YOU_WANT_TO_GEOCODE&key=YOUR_API_KEY"></script>

The address could be something like

1600+Amphitheatre+Parkway,+Mountain+View,+CA (URI Encoded; you should Google it. Very useful)

or simply

1600 Amphitheatre Parkway, Mountain View, CA

By entering this address https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY inside the browser, along with my API Key, I get back a JSON object which contains the Latitude & Longitude for the city of Moutain view, CA.

{"results" : [
  {
     "address_components" : [
        {
           "long_name" : "1600",
           "short_name" : "1600",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Amphitheatre Parkway",
           "short_name" : "Amphitheatre Pkwy",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Mountain View",
           "short_name" : "Mountain View",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Santa Clara County",
           "short_name" : "Santa Clara County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "California",
           "short_name" : "CA",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "94043",
           "short_name" : "94043",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
     "geometry" : {
        "location" : {
           "lat" : 37.4222556,
           "lng" : -122.0838589
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 37.4236045802915,
              "lng" : -122.0825099197085
           },
           "southwest" : {
              "lat" : 37.4209066197085,
              "lng" : -122.0852078802915
           }
        }
     },
     "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
     "types" : [ "street_address" ]
  }],"status" : "OK"}

Web Frameworks such like AngularJS allow us to perform these queries with ease.

Verifying a specific parameter with Moq

A simpler way would be to do:

ObjectA.Verify(
    a => a.Execute(
        It.Is<Params>(p => p.Id == 7)
    )
);

What is difference between Implicit wait and Explicit wait in Selenium WebDriver?

Implicit waits are used to provide a default waiting time between each consecutive test step/command across the entire test script. Thus, subsequent test step would only execute when the specified amount of time have elapsed after executing the previous test step/command.

Explicit waits are used to halt the execution till the time a particular condition is met or the maximum time has elapsed. Unlike Implicit waits, Explicit waits are applied for a particular instance only.

How to remove leading and trailing white spaces from a given html string?

var str = "  my awesome string   "
str.trim();    

for old browsers, use regex

str = str.replace(/^[ ]+|[ ]+$/g,'')
//str = "my awesome string" 

How do I get bit-by-bit data from an integer value in C?

If you don't want any loops, you'll have to write it out:

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
    int num = 7;

    #if 0
        bool arr[4] = { (num&1) ?true: false, (num&2) ?true: false, (num&4) ?true: false, (num&8) ?true: false };
    #else
        #define BTB(v,i) ((v) & (1u << (i))) ? true : false
        bool arr[4] = { BTB(num,0), BTB(num,1), BTB(num,2), BTB(num,3)};
        #undef BTB
    #endif

    printf("%d %d %d %d\n", arr[3], arr[2], arr[1], arr[0]);

    return 0;
}

As demonstrated here, this also works in an initializer.

How to make audio autoplay on chrome

Solution without using iframe, or javascript:

<embed src="silence.mp3" type="audio/mp3" autostart="true" hidden="true">
        <audio id="player" autoplay controls><source src="source/audio.mp3" type="audio/mp3"></audio>

With this solution, the open/save dialog of Internet Explorer is also avoided.

_x000D_
_x000D_
   <embed src="http://deinesv.cf/silence.mp3" type="audio/mp3" autostart="true" hidden="true">
        <audio id="player" autoplay controls><source src="https://freemusicarchive.org/file/music/ccCommunity/Mild_Wild/a_Alright_Okay_b_See_Through/Mild_Wild_-_Alright_Okay.mp3" type="audio/mp3"></audio>
_x000D_
_x000D_
_x000D_

Attach event to dynamic elements in javascript

I have found the solution posted by jillykate works, but only if the target element is the most nested. If this is not the case, this can be rectified by iterating over the parents, i.e.

function on_window_click(event)
{
    let e = event.target;

    while (e !== null)
    {
        // --- Handle clicks here, e.g. ---
        if (e.getAttribute(`data-say_hello`))
        {
            console.log("Hello, world!");
        }

        e = e.parentElement;
    }
}

window.addEventListener("click", on_window_click);

Also note we can handle events by any attribute, or attach our listener at any level. The code above uses a custom attribute and window. I doubt there is any pragmatic difference between the various methods.

CSS Div stretch 100% page height

_x000D_
_x000D_
 _x000D_
           document.body.onload = function () {_x000D_
                var textcontrol = document.getElementById("page");_x000D_
                textcontrol.style.height = (window.innerHeight) + 'px';_x000D_
            }
_x000D_
<html>_x000D_
<head><title></title></head>_x000D_
<body>_x000D_
_x000D_
<div id="page" style="background:green;">_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Redirecting to a new page after successful login

Just add the following code after the final message you give using PHP code

Print'window.location.assign("index.php")

MySQL Cannot Add Foreign Key Constraint

Try to use the same type of your primary keys - int(11) - on the foreign keys - smallint(5) - as well.

Hope it helps!

Is it better practice to use String.format over string Concatenation in Java?

Here's a test with multiple sample sizes in milliseconds.

public class Time {

public static String sysFile = "/sys/class/camera/rear/rear_flash";
public static String cmdString = "echo %s > " + sysFile;

public static void main(String[] args) {

  int i = 1;
  for(int run=1; run <= 12; run++){
      for(int test =1; test <= 2 ; test++){
        System.out.println(
                String.format("\nTEST: %s, RUN: %s, Iterations: %s",run,test,i));
        test(run, i);
      }
      System.out.println("\n____________________________");
      i = i*3;
  }
}

public static void test(int run, int iterations){

      long start = System.nanoTime();
      for( int i=0;i<iterations; i++){
          String s = "echo " + i + " > "+ sysFile;
      }
      long t = System.nanoTime() - start;   
      String r = String.format("  %-13s =%10d %s", "Concatenation",t,"nanosecond");
      System.out.println(r) ;


     start = System.nanoTime();       
     for( int i=0;i<iterations; i++){
         String s =  String.format(cmdString, i);
     }
     t = System.nanoTime() - start; 
     r = String.format("  %-13s =%10d %s", "Format",t,"nanosecond");
     System.out.println(r);

      start = System.nanoTime();          
      for( int i=0;i<iterations; i++){
          StringBuilder b = new StringBuilder("echo ");
          b.append(i).append(" > ").append(sysFile);
          String s = b.toString();
      }
     t = System.nanoTime() - start; 
     r = String.format("  %-13s =%10d %s", "StringBuilder",t,"nanosecond");
     System.out.println(r);
}

}

TEST: 1, RUN: 1, Iterations: 1
  Concatenation =     14911 nanosecond
  Format        =     45026 nanosecond
  StringBuilder =      3509 nanosecond

TEST: 1, RUN: 2, Iterations: 1
  Concatenation =      3509 nanosecond
  Format        =     38594 nanosecond
  StringBuilder =      3509 nanosecond

____________________________

TEST: 2, RUN: 1, Iterations: 3
  Concatenation =      8479 nanosecond
  Format        =     94438 nanosecond
  StringBuilder =      5263 nanosecond

TEST: 2, RUN: 2, Iterations: 3
  Concatenation =      4970 nanosecond
  Format        =     92976 nanosecond
  StringBuilder =      5848 nanosecond

____________________________

TEST: 3, RUN: 1, Iterations: 9
  Concatenation =     11403 nanosecond
  Format        =    287115 nanosecond
  StringBuilder =     14326 nanosecond

TEST: 3, RUN: 2, Iterations: 9
  Concatenation =     12280 nanosecond
  Format        =    209051 nanosecond
  StringBuilder =     11818 nanosecond

____________________________

TEST: 5, RUN: 1, Iterations: 81
  Concatenation =     54383 nanosecond
  Format        =   1503113 nanosecond
  StringBuilder =     40056 nanosecond

TEST: 5, RUN: 2, Iterations: 81
  Concatenation =     44149 nanosecond
  Format        =   1264241 nanosecond
  StringBuilder =     34208 nanosecond

____________________________

TEST: 6, RUN: 1, Iterations: 243
  Concatenation =     76018 nanosecond
  Format        =   3210891 nanosecond
  StringBuilder =     76603 nanosecond

TEST: 6, RUN: 2, Iterations: 243
  Concatenation =     91222 nanosecond
  Format        =   2716773 nanosecond
  StringBuilder =     73972 nanosecond

____________________________

TEST: 8, RUN: 1, Iterations: 2187
  Concatenation =    527450 nanosecond
  Format        =  10291108 nanosecond
  StringBuilder =    885027 nanosecond

TEST: 8, RUN: 2, Iterations: 2187
  Concatenation =    526865 nanosecond
  Format        =   6294307 nanosecond
  StringBuilder =    591773 nanosecond

____________________________

TEST: 10, RUN: 1, Iterations: 19683
  Concatenation =   4592961 nanosecond
  Format        =  60114307 nanosecond
  StringBuilder =   2129387 nanosecond

TEST: 10, RUN: 2, Iterations: 19683
  Concatenation =   1850166 nanosecond
  Format        =  35940524 nanosecond
  StringBuilder =   1885544 nanosecond

  ____________________________

TEST: 12, RUN: 1, Iterations: 177147
  Concatenation =  26847286 nanosecond
  Format        = 126332877 nanosecond
  StringBuilder =  17578914 nanosecond

TEST: 12, RUN: 2, Iterations: 177147
  Concatenation =  24405056 nanosecond
  Format        = 129707207 nanosecond
  StringBuilder =  12253840 nanosecond

Java logical operator short-circuiting

Logical OR :- returns true if at least one of the operands evaluate to true. Both operands are evaluated before apply the OR operator.

Short Circuit OR :- if left hand side operand returns true, it returns true without evaluating the right hand side operand.

Can I access constants in settings.py from templates in Django?

I find the simplest approach being a single custom template tag:

from django import template
from django.conf import settings

register = template.Library()

# settings value
@register.simple_tag
def settings_value(name):
    return getattr(settings, name, "")

Usage:

{% settings_value "LANGUAGE_CODE" %}

Using bind variables with dynamic SELECT INTO clause in PL/SQL

In my opinion, a dynamic PL/SQL block is somewhat obscure. While is very flexible, is also hard to tune, hard to debug and hard to figure out what's up. My vote goes to your first option,

EXECUTE IMMEDIATE v_query_str INTO v_num_of_employees USING p_job;

Both uses bind variables, but first, for me, is more redeable and tuneable than @jonearles option.

What are the rules about using an underscore in a C++ identifier?

From MSDN:

Use of two sequential underscore characters ( __ ) at the beginning of an identifier, or a single leading underscore followed by a capital letter, is reserved for C++ implementations in all scopes. You should avoid using one leading underscore followed by a lowercase letter for names with file scope because of possible conflicts with current or future reserved identifiers.

This means that you can use a single underscore as a member variable prefix, as long as it's followed by a lower-case letter.

This is apparently taken from section 17.4.3.1.2 of the C++ standard, but I can't find an original source for the full standard online.

See also this question.

Scrolling a div with jQuery

There's a plug-in for this if you don't want to write a bare-bones implementation yourself. It's called "scrollTo" (link). It allows you to perform programmed scrolling to certain points, or use values like -= 10px for continuous scrolling.

ScrollTo jQuery Plug-in

Setting std=c99 flag in GCC

Instead of calling /usr/bin/gcc, use /usr/bin/c99. This is the Single-Unix-approved way of invoking a C99 compiler. On an Ubuntu system, this points to a script which invokes gcc after having added the -std=c99 flag, which is precisely what you want.

How to dynamically add elements to String array?

Arrays in Java have a defined size, you cannot change it later by adding or removing elements (you can read some basics here).

Instead, use a List:

ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.

Of course, if you know beforehand how many strings you are going to put in your array, you can create an array of that size and set the elements by using the correct position:

String[] myarray = new String[numberofstrings];
myarray[23] = string24; //this sets the 24'th (first index is 0) element to string24.

Border around specific rows in a table?

Based on your requirement that you want to put a border around an arbitrary block of MxN cells there really is no easier way of doing it without using Javascript. If your cells are fixed with you can use floats but this is problematic for other reasons. what you're doing may be tedious but it's fine.

Ok, if you're interested in a Javascript solution, using jQuery (my preferred approach), you end up with this fairly scary piece of code:

<html>
<head>

<style type="text/css">
td.top { border-top: thin solid black; }
td.bottom { border-bottom: thin solid black; }
td.left { border-left: thin solid black; }
td.right { border-right: thin solid black; }
</style>
<script type="text/javascript" src="jquery-1.3.1.js"></script>
<script type="text/javascript">
$(function() {
  box(2, 1, 2, 2);
});

function box(row, col, height, width) {
  if (typeof height == 'undefined') {
    height = 1;
  }
  if (typeof width == 'undefined') {
    width = 1;
  }
  $("table").each(function() {
    $("tr:nth-child(" + row + ")", this).children().slice(col - 1, col + width - 1).addClass("top");
    $("tr:nth-child(" + (row + height - 1) + ")", this).children().slice(col - 1, col + width - 1).addClass("bottom");
    $("tr", this).slice(row - 1, row + height - 1).each(function() {
      $(":nth-child(" + col + ")", this).addClass("left");
      $(":nth-child(" + (col + width - 1) + ")", this).addClass("right");
    });
  });
}
</script>
</head>
<body>

<table cellspacing="0">
  <tr>
    <td>no border</td>
    <td>no border here either</td>
  </tr>
  <tr>
    <td>one</td>
    <td>two</td>
  </tr>
  <tr>
    <td>three</td>
    <td>four</td>
  </tr>
  <tr>
    <td colspan="2">once again no borders</td>
  </tr>
</tfoot>
</table>
</html>

I'll happily take suggestions on easier ways to do this...

setTimeout or setInterval?

The difference is obvious in console:

enter image description here

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

Rank each of the squares with numeric scores. If a square is taken, move on to the next choice (sorted in descending order by rank). You're going to need to choose a strategy (there are two main ones for going first and three (I think) for second). Technically, you could just program all of the strategies and then choose one at random. That would make for a less predictable opponent.

Run bash script from Windows PowerShell

If you add the extension .SH to the environment variable PATHEXT, you will be able to run shell scripts from PowerShell by only using the script name with arguments:

PS> .\script.sh args

If you store your scripts in a directory that is included in your PATH environment variable, you can run it from anywhere, and omit the extension and path:

PS> script args

Note: sh.exe or another *nix shell must be associated with the .sh extension.

Exception 'open failed: EACCES (Permission denied)' on Android

For API 23+ you need to request the read/write permissions even if they are already in your manifest.

// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

/**
 * Checks if the app has permission to write to device storage
 *
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

For official documentation about requesting permissions for API 23+, check https://developer.android.com/training/permissions/requesting.html

The connection to adb is down, and a severe error has occurred

Sounds a bit familiar with my problem: aapt not found under the right path

I needed to clean all open projects to get it working again...

How to push changes to github after jenkins build completes?

I followed the below Steps. It worked for me.

In Jenkins execute shell under Build, creating a file and trying to push that file from Jenkins workspace to GitHub.

enter image description here

Download Git Publisher Plugin and Configure as shown below snapshot.

enter image description here

Click on Save and Build. Now you can check your git repository whether the file was pushed successfully or not.

Download File Using jQuery

I might suggest this, as a more gracefully degrading solution, using preventDefault:

$('a').click(function(e) {
    e.preventDefault();  //stop the browser from following
    window.location.href = 'uploads/file.doc';
});

<a href="no-script.html">Download now!</a>

Even if there's no Javascript, at least this way the user will get some feedback.

rsync - mkstemp failed: Permission denied (13)

I had the same issue, so I first SSH into the server to confirm that I able to log in to the server by using the command:

ssh -i /Users/Desktop/mypemfile.pem [email protected]

Then in New Terminal

I copied a small file to the server by using SCP, to make sure I am able to make a connection:

scp -i /Users/Desktop/mypemfile.pem /Users/Desktop/test.file [email protected]:/home/user/test/

Then In the same new terminal, I tried running rsync:

rsync -avz -e "ssh -i /Users/Desktop/mypemfile.pem" /Users/Desktop/backup/image.img.gz [email protected]:

Convert PEM traditional private key to PKCS8 private key

To convert the private key from PKCS#1 to PKCS#8 with openssl:

# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key

That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.

How to set a:link height/width with css?

Your problem is probably that a elements are display: inline by nature. You can't set the width and height of inline elements.

You would have to set display: block on the a, but that will bring other problems because the links start behaving like block elements. The most common cure to that is giving them float: left so they line up side by side anyway.

Where does VBA Debug.Print log to?

Where do you want to see the output?

Messages being output via Debug.Print will be displayed in the immediate window which you can open by pressing Ctrl+G.

You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar

enter image description here

How to print color in console using System.out.println?

You could do this using ANSI escape sequences. I've actually put together this class in Java for anyone that would like a simple workaround for this. It allows for more than just color codes.

https://gist.github.com/nathan-fiscaletti/9dc252d30b51df7d710a

(Ported from: https://github.com/nathan-fiscaletti/ansi-util)

Example Use:

StringBuilder sb = new StringBuilder();

System.out.println(
    sb.raw("Hello, ")
      .underline("John Doe")
      .resetUnderline()
      .raw(". ")
      .raw("This is ")
      .color16(StringBuilder.Color16.FG_RED, "red")
      .raw(".")
);

Just what is an IntPtr exactly?

An IntPtr is a value type that is primarily used to hold memory addresses or handles. A pointer is a memory address. A pointer can be typed (e.g. int*) or untyped (e.g. void*). A Windows handle is a value that is usually the same size (or smaller) than a memory address and represents a system resource (like a file or window).

How do I find out where login scripts live?

The default location for logon scripts is the netlogon share of a domain controller. On the server this is located:

%SystemRoot%'SYSVOL'sysvol''scripts

It can presumably be changes from this default but I've never met anyone that had a reason to.

To get list of domain controllers programatically see this article: http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1216.mspx

#include errors detected in vscode

For Windows:

  1. Please add this directory to your environment variable(Path):

C:\mingw-w64\x86_64-8.1.0-win32-seh-rt_v6-rev0\mingw64\bin\

  1. For Include errors detected, mention the path of your include folder into

"includePath": [ "C:/mingw-w64/x86_64-8.1.0-win32-seh-rt_v6-rev0/mingw64/include/" ]

, as this is the path from where the compiler fetches the library to be included in your program.

"Large data" workflows using pandas

I routinely use tens of gigabytes of data in just this fashion e.g. I have tables on disk that I read via queries, create data and append back.

It's worth reading the docs and late in this thread for several suggestions for how to store your data.

Details which will affect how you store your data, like:
Give as much detail as you can; and I can help you develop a structure.

  1. Size of data, # of rows, columns, types of columns; are you appending rows, or just columns?
  2. What will typical operations look like. E.g. do a query on columns to select a bunch of rows and specific columns, then do an operation (in-memory), create new columns, save these.
    (Giving a toy example could enable us to offer more specific recommendations.)
  3. After that processing, then what do you do? Is step 2 ad hoc, or repeatable?
  4. Input flat files: how many, rough total size in Gb. How are these organized e.g. by records? Does each one contains different fields, or do they have some records per file with all of the fields in each file?
  5. Do you ever select subsets of rows (records) based on criteria (e.g. select the rows with field A > 5)? and then do something, or do you just select fields A, B, C with all of the records (and then do something)?
  6. Do you 'work on' all of your columns (in groups), or are there a good proportion that you may only use for reports (e.g. you want to keep the data around, but don't need to pull in that column explicity until final results time)?

Solution

Ensure you have pandas at least 0.10.1 installed.

Read iterating files chunk-by-chunk and multiple table queries.

Since pytables is optimized to operate on row-wise (which is what you query on), we will create a table for each group of fields. This way it's easy to select a small group of fields (which will work with a big table, but it's more efficient to do it this way... I think I may be able to fix this limitation in the future... this is more intuitive anyhow):
(The following is pseudocode.)

import numpy as np
import pandas as pd

# create a store
store = pd.HDFStore('mystore.h5')

# this is the key to your storage:
#    this maps your fields to a specific group, and defines 
#    what you want to have as data_columns.
#    you might want to create a nice class wrapping this
#    (as you will want to have this map and its inversion)  
group_map = dict(
    A = dict(fields = ['field_1','field_2',.....], dc = ['field_1',....,'field_5']),
    B = dict(fields = ['field_10',......        ], dc = ['field_10']),
    .....
    REPORTING_ONLY = dict(fields = ['field_1000','field_1001',...], dc = []),

)

group_map_inverted = dict()
for g, v in group_map.items():
    group_map_inverted.update(dict([ (f,g) for f in v['fields'] ]))

Reading in the files and creating the storage (essentially doing what append_to_multiple does):

for f in files:
   # read in the file, additional options may be necessary here
   # the chunksize is not strictly necessary, you may be able to slurp each 
   # file into memory in which case just eliminate this part of the loop 
   # (you can also change chunksize if necessary)
   for chunk in pd.read_table(f, chunksize=50000):
       # we are going to append to each table by group
       # we are not going to create indexes at this time
       # but we *ARE* going to create (some) data_columns

       # figure out the field groupings
       for g, v in group_map.items():
             # create the frame for this group
             frame = chunk.reindex(columns = v['fields'], copy = False)    

             # append it
             store.append(g, frame, index=False, data_columns = v['dc'])

Now you have all of the tables in the file (actually you could store them in separate files if you wish, you would prob have to add the filename to the group_map, but probably this isn't necessary).

This is how you get columns and create new ones:

frame = store.select(group_that_I_want)
# you can optionally specify:
# columns = a list of the columns IN THAT GROUP (if you wanted to
#     select only say 3 out of the 20 columns in this sub-table)
# and a where clause if you want a subset of the rows

# do calculations on this frame
new_frame = cool_function_on_frame(frame)

# to 'add columns', create a new group (you probably want to
# limit the columns in this new_group to be only NEW ones
# (e.g. so you don't overlap from the other tables)
# add this info to the group_map
store.append(new_group, new_frame.reindex(columns = new_columns_created, copy = False), data_columns = new_columns_created)

When you are ready for post_processing:

# This may be a bit tricky; and depends what you are actually doing.
# I may need to modify this function to be a bit more general:
report_data = store.select_as_multiple([groups_1,groups_2,.....], where =['field_1>0', 'field_1000=foo'], selector = group_1)

About data_columns, you don't actually need to define ANY data_columns; they allow you to sub-select rows based on the column. E.g. something like:

store.select(group, where = ['field_1000=foo', 'field_1001>0'])

They may be most interesting to you in the final report generation stage (essentially a data column is segregated from other columns, which might impact efficiency somewhat if you define a lot).

You also might want to:

  • create a function which takes a list of fields, looks up the groups in the groups_map, then selects these and concatenates the results so you get the resulting frame (this is essentially what select_as_multiple does). This way the structure would be pretty transparent to you.
  • indexes on certain data columns (makes row-subsetting much faster).
  • enable compression.

Let me know when you have questions!

What does `set -x` do?

set -x

Prints a trace of simple commands, for commands, case commands, select commands, and arithmetic for commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4 variable is expanded and the resultant value is printed before the command and its expanded arguments.

[source]

Example

set -x
echo `expr 10 + 20 `
+ expr 10 + 20
+ echo 30
30

set +x
echo `expr 10 + 20 `
30

Above example illustrates the usage of set -x. When it is used, above arithmetic expression has been expanded. We could see how a singe line has been evaluated step by step.

  • First step expr has been evaluated.
  • Second step echo has been evaluated.

To know more about set ? visit this link

when it comes to your shell script,

[ "$DEBUG" == 'true' ] && set -x

Your script might have been printing some additional lines of information when the execution mode selected as DEBUG. Traditionally people used to enable debug mode when a script called with optional argument such as -d

Tomcat Server not starting with in 45 seconds

URL pattern of <servlet-mapping>:

Check project explorer → Deployment descriptor → Servlet Mapping → check that all mapping present in controller package. ref. image as below:

shop project ref

if there is any mapping not available, Then remove that <servlet> and <servlet-mapping> tag in web.xml.

css3 text-shadow in IE9

Try CSS Generator.

You can choose values and see the results online. Then you get the code in the clipboard.
This is one example of generated code:

text-shadow: 1px 1px 2px #a8aaad;
filter: dropshadow(color=#a8aaad, offx=1, offy=1);

How to call a parent method from child class in javascript?

In case of multiple inheritance level, this function can be used as a super() method in other languages. Here is a demo fiddle, with some tests, you can use it like this, inside your method use : call_base(this, 'method_name', arguments);

It make use of quite recent ES functions, an compatibility with older browsers is not guarantee. Tested in IE11, FF29, CH35.

/**
 * Call super method of the given object and method.
 * This function create a temporary variable called "_call_base_reference",
 * to inspect whole inheritance linage. It will be deleted at the end of inspection.
 *
 * Usage : Inside your method use call_base(this, 'method_name', arguments);
 *
 * @param {object} object The owner object of the method and inheritance linage
 * @param {string} method The name of the super method to find.
 * @param {array} args The calls arguments, basically use the "arguments" special variable.
 * @returns {*} The data returned from the super method.
 */
function call_base(object, method, args) {
    // We get base object, first time it will be passed object,
    // but in case of multiple inheritance, it will be instance of parent objects.
    var base = object.hasOwnProperty('_call_base_reference') ? object._call_base_reference : object,
    // We get matching method, from current object,
    // this is a reference to define super method.
            object_current_method = base[method],
    // Temp object wo receive method definition.
            descriptor = null,
    // We define super function after founding current position.
            is_super = false,
    // Contain output data.
            output = null;
    while (base !== undefined) {
        // Get method info
        descriptor = Object.getOwnPropertyDescriptor(base, method);
        if (descriptor !== undefined) {
            // We search for current object method to define inherited part of chain.
            if (descriptor.value === object_current_method) {
                // Further loops will be considered as inherited function.
                is_super = true;
            }
            // We already have found current object method.
            else if (is_super === true) {
                // We need to pass original object to apply() as first argument,
                // this allow to keep original instance definition along all method
                // inheritance. But we also need to save reference to "base" who
                // contain parent class, it will be used into this function startup
                // to begin at the right chain position.
                object._call_base_reference = base;
                // Apply super method.
                output = descriptor.value.apply(object, args);
                // Property have been used into super function if another
                // call_base() is launched. Reference is not useful anymore.
                delete object._call_base_reference;
                // Job is done.
                return output;
            }
        }
        // Iterate to the next parent inherited.
        base = Object.getPrototypeOf(base);
    }
}

Why doesn't git recognize that my file has been changed, therefore git add not working

I had a similar issue when I created a patch file in server with vi editor. It seems the issue was with spacing. When I pushed the patch from local, deployment was proper.

How to compile and run a C/C++ program on the Android system

You can compile your C programs with an ARM cross-compiler:

arm-linux-gnueabi-gcc -static -march=armv7-a test.c -o test

Then you can push your compiled binary file to somewhere (don't push it in to the SD card):

adb push test /data/local/tmp/test

Disable Required validation attribute under certain circumstances

If you just want to disable validation for a single field in client side then you can override the validation attributes as follows:

@Html.TextBoxFor(model => model.SomeValue, 
                new Dictionary<string, object> { { "data-val", false }})

DOS: find a string, if found then run another script

As the answer is marked correct then it's a Windows Dos prompt script and this will work too:

find "string" status.txt >nul && call "my batch file.bat"

How do I prevent an Android device from going to sleep programmatically?

If you are a Xamarin user, this is the solution:

   protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle); //always call superclass first

        this.Window.AddFlags(WindowManagerFlags.KeepScreenOn);

        LoadApplication(new App());
    }

What is the .idea folder?

When you use the IntelliJ IDE, all the project-specific settings for the project are stored under the .idea folder.

Project settings are stored with each specific project as a set of xml files under the .idea folder. If you specify the default project settings, these settings will be automatically used for each newly created project.

Check this documentation for the IDE settings and here is their recommendation on Source Control and an example .gitignore file.

Note: If you are using git or some version control system, you might want to set this folder "ignore". Example - for git, add this directory to .gitignore. This way, the application is not IDE-specific.

In Python, how do I split a string and keep the separators?

Here is a simple .split solution that works without regex.

This is an answer for Python split() without removing the delimiter, so not exactly what the original post asks but the other question was closed as a duplicate for this one.

def splitkeep(s, delimiter):
    split = s.split(delimiter)
    return [substr + delimiter for substr in split[:-1]] + [split[-1]]

Random tests:

import random

CHARS = [".", "a", "b", "c"]
assert splitkeep("", "X") == [""]  # 0 length test
for delimiter in ('.', '..'):
    for _ in range(100000):
        length = random.randint(1, 50)
        s = "".join(random.choice(CHARS) for _ in range(length))
        assert "".join(splitkeep(s, delimiter)) == s

How to append to the end of an empty list?

Like Mikola said, append() returns a void, so every iteration you're setting list1 to a nonetype because append is returning a nonetype. On the next iteration, list1 is null so you're trying to call the append method of a null. Nulls don't have methods, hence your error.

unable to start mongodb local server

Use:

sudo killall mongod

It will stop the server.

Then restart mongod by:

sudo service mongod restart

it should work.

"Sources directory is already netbeans project" error when opening a project from existing sources

  1. Go to the folder containing your project
  2. Delete the folder named nbproject
  3. Restart Netbeans
  4. Try creating your project again from the original folder

How to run stored procedures in Entity Framework Core?

The support for stored procedure in EF Core is similar to the earlier versions of EF Code first.

You need to create your DbContext class by inherting the DbContext class from EF. The stored procedures are executing using the DbContext.

First step is to write a method that create a DbCommand from the DbContext.

public static DbCommand LoadStoredProc(
  this DbContext context, string storedProcName)
{
  var cmd = context.Database.GetDbConnection().CreateCommand();
  cmd.CommandText = storedProcName;
  cmd.CommandType = System.Data.CommandType.StoredProcedure;
  return cmd;
}

To pass parameters to the stored procedure use the following method.

public static DbCommand WithSqlParam(
  this DbCommand cmd, string paramName, object paramValue)
{
  if (string.IsNullOrEmpty(cmd.CommandText))
    throw new InvalidOperationException(
      "Call LoadStoredProc before using this method");
  var param = cmd.CreateParameter();
  param.ParameterName = paramName;
  param.Value = paramValue;
  cmd.Parameters.Add(param);
  return cmd;
}

Finally for mapping the result into a list of custom objects use the MapToList method.

private static List<T> MapToList<T>(this DbDataReader dr)
{
  var objList = new List<T>();
  var props = typeof(T).GetRuntimeProperties();

  var colMapping = dr.GetColumnSchema()
    .Where(x => props.Any(y => y.Name.ToLower() == x.ColumnName.ToLower()))
    .ToDictionary(key => key.ColumnName.ToLower());

  if (dr.HasRows)
  {
    while (dr.Read())
    {
      T obj = Activator.CreateInstance<T>();
      foreach (var prop in props)
      {
        var val = 
          dr.GetValue(colMapping[prop.Name.ToLower()].ColumnOrdinal.Value);
          prop.SetValue(obj, val == DBNull.Value ? null : val);
      }
      objList.Add(obj);
    }
  }
  return objList;
}

Now we’re ready for execute the stored procedute with the ExecuteStoredProc method and maps it to the a List whose type that’s passed in as T.

public static async Task<List<T>> ExecuteStoredProc<T>(this DbCommand command)
{
  using (command)
  {
    if (command.Connection.State == System.Data.ConnectionState.Closed)
    command.Connection.Open();
    try
    {
      using (var reader = await command.ExecuteReaderAsync())
      {
        return reader.MapToList<T>();
      }
    }
    catch(Exception e)
    {
      throw (e);
    }
    finally
    {
      command.Connection.Close();
    }
  }
}

For example, to execute a stored procedure called “StoredProcedureName” with two parameters called “firstparamname” and “secondparamname” this is the implementation.

List<MyType> myTypeList = new List<MyType>();
using(var context = new MyDbContext())
{
  myTypeList = context.LoadStoredProc("StoredProcedureName")
  .WithSqlParam("firstparamname", firstParamValue)
  .WithSqlParam("secondparamname", secondParamValue).
  .ExecureStoredProc<MyType>();
}

C# getting the path of %AppData%

AppData ? Local aka (C:\Users\<user>\AppData\Local):

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)

AppData ? Roaming aka (C:\Users\<user>\AppData\Roaming):

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

Additionally, it could be handy to know:

  • Environment.SpecialFolder.ProgramFiles - for Program files X64 folder
  • Environment.SpecialFolder.ProgramFilesX86 - for Program files X86 folder

For the full list check here.

Set variable with multiple values and use IN

Ideally you shouldn't be splitting strings in T-SQL at all.

Barring that change, on older versions before SQL Server 2016, create a split function:

CREATE FUNCTION dbo.SplitStrings
(
    @List      nvarchar(max), 
    @Delimiter nvarchar(2)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
  RETURN ( WITH x(x) AS
    (
      SELECT CONVERT(xml, N'<root><i>' 
        + REPLACE(@List, @Delimiter, N'</i><i>') 
        + N'</i></root>')
    )
    SELECT Item = LTRIM(RTRIM(i.i.value(N'.',N'nvarchar(max)')))
      FROM x CROSS APPLY x.nodes(N'//root/i') AS i(i)
  );
GO

Now you can say:

DECLARE @Values varchar(1000);

SET @Values = 'A, B, C';

SELECT blah
  FROM dbo.foo
  INNER JOIN dbo.SplitStrings(@Values, ',') AS s
    ON s.Item = foo.myField;

On SQL Server 2016 or above (or Azure SQL Database), it is much simpler and more efficient, however you do have to manually apply LTRIM() to take away any leading spaces:

DECLARE @Values varchar(1000) = 'A, B, C';

SELECT blah
  FROM dbo.foo
  INNER JOIN STRING_SPLIT(@Values, ',') AS s
    ON LTRIM(s.value) = foo.myField;

how to set radio option checked onload with jQuery

JQuery has actually two ways to set checked status for radio and checkboxes and it depends on whether you are using value attribute in HTML markup or not:

If they have value attribute:

$("[name=myRadio]").val(["myValue"]);

If they don't have value attribute:

$("#myRadio1").prop("checked", true);

More Details

In first case, we specify the entire radio group using name and tell JQuery to find radio to select using val function. The val function takes 1-element array and finds the radio with matching value, set its checked=true. Others with the same name would be deselected. If no radio with matching value found then all will be deselected. If there are multiple radios with same name and value then the last one would be selected and others would be deselected.

If you are not using value attribute for radio then you need to use unique ID to select particular radio in the group. In this case, you need to use prop function to set "checked" property. Many people don't use value attribute with checkboxes so #2 is more applicable for checkboxes then radios. Also note that as checkboxes don't form group when they have same name, you can do $("[name=myCheckBox").prop("checked", true); for checkboxes.

You can play with this code here: http://jsbin.com/OSULAtu/1/edit?html,output

PHP How to fix Notice: Undefined variable:

Xampp I guess you're using MySQL.

mysql_fetch_array($result);  

And make sure $result is not empty.