Programs & Examples On #Gldrawpixels

Git commit with no commit message

I have the following config in my private project:

git config alias.auto 'commit -a -m "changes made from [device name]"'

That way, when I'm in a hurry I do

git auto
git push

And at least I know what device the commit was made from.

How to read GET data from a URL using JavaScript?

Here's one solution. Of course, this function doesn't need to load into a "window.params" option -- that can be customized.

window.params = function(){
    var params = {};
    var param_array = window.location.href.split('?')[1].split('&');
    for(var i in param_array){
        x = param_array[i].split('=');
        params[x[0]] = x[1];
    }
    return params;
}();

Example API call on http://www.mints.com/myurl.html?name=something&goal=true:

if(window.params.name == 'something') doStuff();
else if( window.params.goal == 'true') shoutGOOOOOAAALLL();

why windows 7 task scheduler task fails with error 2147942667

I had the same problem, on Windows7.

I was getting error 2147942667 and a report of being unable to run c:\windows\system32\CMD.EXE. I tried with and without double quotes in the Script and Start-in and it made no difference. Then I tried replacing all path references to mapped network drives and with UNC references (\Server1\Sharexx\my_scripts\run_this.cmd) and that fixed it for me. Pat.

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

In my case I forgot it was packaging conflict jar vs pom. I forgot to write

<packaging>pom</packaging>

In every child pom.xml file

How do I modify the URL without reloading the page?

The HTML5 replaceState is the answer, as already mentioned by Vivart and geo1701. However it is not supported in all browsers/versions. History.js wraps HTML5 state features and provides additional support for HTML4 browsers.

How do I URL encode a string

ios 7 update

NSString *encode = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

NSString *decode = [encode stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

How to change Oracle default data pump directory to import dumpfile?

I want change default directory dumpfile.

You could create a new directory and give it required privileges, for example:

SQL> CREATE DIRECTORY dmpdir AS '/opt/oracle';
Directory created.

SQL> GRANT read, write ON DIRECTORY dmpdir TO scott;
Grant succeeded.

To use the newly created directory, you could just add it as a parameter:

DIRECTORY=dmpdir

Oracle introduced a default directory from 10g R2, called DATA_PUMP_DIR, that can be used. To check the location, you could look into dba_directories:

SQL> select DIRECTORY_NAME, DIRECTORY_PATH from dba_directories where DIRECTORY_NAME = 'DATA_PUMP_DIR';

DIRECTORY_NAME       DIRECTORY_PATH
-------------------- --------------------------------------------------
DATA_PUMP_DIR        C:\app\Lalit/admin/orcl/dpdump/

SQL>

Oracle REPLACE() function isn't handling carriage-returns & line-feeds

If the data in your database is POSTED from HTML form TextArea controls, different browsers use different New Line characters:

Firefox separates lines with CHR(10) only

Internet Explorer separates lines with CHR(13) + CHR(10)

Apple (pre-OSX) separates lines with CHR(13) only

So you may need something like:

set col_name = replace(replace(col_name, CHR(13), ''), CHR(10), '')

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

You can use it like this:

In Mvc:

@Html.TextBoxFor(x=>x.Id,new{@data_val_number="10"});

In Html:

<input type="text" name="Id" data_val_number="10"/>

Vim autocomplete for Python

As pointed out by in the comments, this answers is outdated. youcompleteme now supports python3 and jedi-vim no longer breaks the undo history.

Original answer below.


AFAIK there are three options, each with its disadvantages:

  1. youcompleteme: unfriendly to install, but works nice if you manage to get it working. However python3 is not supported.
  2. jedi-vim: coolest name, but breaks your undo history.
  3. python-mode does a lot more the autocomplete: folding, syntax checking, highlighting. Personally I prefer scripts that do 1 thing well, as they are easier to manage (and replace). Differently from the two other options, it uses rope instead of jedi for autocompletion.

Python 3 and undo history (gundo!) are a must for me, so options 1 and 2 are out.

What is the maximum size of a web browser's cookie's key?

The 4K limit you read about is for the entire cookie, including name, value, expiry date etc. If you want to support most browsers, I suggest keeping the name under 4000 bytes, and the overall cookie size under 4093 bytes.

One thing to be careful of: if the name is too big you cannot delete the cookie (at least in JavaScript). A cookie is deleted by updating it and setting it to expire. If the name is too big, say 4090 bytes, I found that I could not set an expiry date. I only looked into this out of interest, not that I plan to have a name that big.

To read more about it, here are the "Browser Cookie Limits" for common browsers.


While on the subject, if you want to support most browsers, then do not exceed 50 cookies per domain, and 4093 bytes per domain. That is, the size of all cookies should not exceed 4093 bytes.

This means you can have 1 cookie of 4093 bytes, or 2 cookies of 2045 bytes, etc.


I used to say 4095 bytes due to IE7, however now Mobile Safari comes in with 4096 bytes with a 3 byte overhead per cookie, so 4093 bytes max.

How can I clear the content of a file?

Try using something like

File.Create

Creates or overwrites a file in the specified path.

how to check and set max_allowed_packet mysql variable

max_allowed_packet is set in mysql config, not on php side

[mysqld]
max_allowed_packet=16M 

You can see it's curent value in mysql like this:

SHOW VARIABLES LIKE 'max_allowed_packet';

You can try to change it like this, but it's unlikely this will work on shared hosting:

SET GLOBAL max_allowed_packet=16777216;

You can read about it here http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html

EDIT

The [mysqld] is necessary to make the max_allowed_packet working since at least mysql version 5.5.

Recently setup an instance on AWS EC2 with Drupal and Solr Search Engine, which required 32M max_allowed_packet. It you set the value under [mysqld_safe] (which is default settings came with the mysql installation) mode in /etc/my.cnf, it did no work. I did not dig into the problem. But after I change it to [mysqld] and restarted the mysqld, it worked.

How to properly seed random number generator

I don't understand why people are seeding with a time value. This has in my experience never been a good idea. For example, while the system clock is maybe represented in nanoseconds, the system's clock precision isn't nanoseconds.

This program should not be run on the Go playground but if you run it on your machine you get a rough estimate on what type of precision you can expect. I see increments of about 1000000 ns, so 1 ms increments. That's 20 bits of entropy that are not used. All the while the high bits are mostly constant!? Roughly ~24 bits of entropy over a day which is very brute forceable (which can create vulnerabilities).

The degree that this matters to you will vary but you can avoid pitfalls of clock based seed values by simply using the crypto/rand.Read as source for your seed. It will give you that non-deterministic quality that you are probably looking for in your random numbers (even if the actual implementation itself is limited to a set of distinct and deterministic random sequences).

import (
    crypto_rand "crypto/rand"
    "encoding/binary"
    math_rand "math/rand"
)

func init() {
    var b [8]byte
    _, err := crypto_rand.Read(b[:])
    if err != nil {
        panic("cannot seed math/rand package with cryptographically secure random number generator")
    }
    math_rand.Seed(int64(binary.LittleEndian.Uint64(b[:])))
}

As a side note but in relation to your question. You can create your own rand.Source using this method to avoid the cost of having locks protecting the source. The rand package utility functions are convenient but they also use locks under the hood to prevent the source from being used concurrently. If you don't need that you can avoid it by creating your own Source and use that in a non-concurrent way. Regardless, you should NOT be reseeding your random number generator between iterations, it was never designed to be used that way.

How do change the color of the text of an <option> within a <select>?

Here is my demo with jQuery

<!doctype html>
<html>
<head>
<style>
    select{
        color:#aaa;
    }
    option:not(first-child) {
        color: #000;
    }
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        $("select").change(function(){
            if ($(this).val()=="") $(this).css({color: "#aaa"});
            else $(this).css({color: "#000"});
        });
    }); 
</script>
<meta charset="utf-8">
</head>
<body>
<select>
    <option disable hidden value="">CHOOSE</option>
    <option>#1</option>
    <option>#2</option>
    <option>#3</option>
    <option>#4</option>
</select>
</body>
</html> 

https://jsfiddle.net/monster75/cnt73375/1/

Node.js global proxy setting

Unfortunately, it seems that proxy information must be set on each call to http.request. Node does not include a mechanism for global proxy settings.

The global-tunnel-ng module on NPM appears to handle this, however:

var globalTunnel = require('global-tunnel-ng');

globalTunnel.initialize({
  host: '10.0.0.10',
  port: 8080,
  proxyAuth: 'userId:password', // optional authentication
  sockets: 50 // optional pool size for each http and https
});

After the global settings are establish with a call to initialize, both http.request and the request library will use the proxy information.

The module can also use the http_proxy environment variable:

process.env.http_proxy = 'http://proxy.example.com:3129';
globalTunnel.initialize();

How to add column if not exists on PostgreSQL?

For those who use Postgre 9.5+(I believe most of you do), there is a quite simple and clean solution

ALTER TABLE if exists <tablename> add if not exists <columnname> <columntype>

Angular2 dynamic change CSS property

Angular 6 + Alyle UI

With Alyle UI you can change the styles dynamically

Here a demo stackblitz

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    CommonModule,
    FormsModule,
    HttpClientModule,
    BrowserAnimationsModule,
    AlyleUIModule.forRoot(
      {
        name: 'myTheme',
        primary: {
          default: '#00bcd4'
        },
        accent: {
          default: '#ff4081'
        },
        scheme: 'myCustomScheme', // myCustomScheme from colorSchemes
        lightGreen: '#8bc34a',
        colorSchemes: {
          light: {
            myColor: 'teal',
          },
          dark: {
            myColor: '#FF923D'
          },
          myCustomScheme: {
            background: {
              primary: '#dde4e6',
            },
            text: {
              default: '#fff'
            },
            myColor: '#C362FF'
          }
        }
      }
    ),
    LyCommonModule, // for bg, color, raised and others
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Html

<div [className]="classes.card">dynamic style</div>
<p color="myColor">myColor</p>
<p bg="myColor">myColor</p>

For change Style

import { Component } from '@angular/core';
import { LyTheme } from '@alyle/ui';

@Component({ ... })
export class AppComponent  {
  classes = {
    card: this.theme.setStyle(
      'card', // key
      () => (
        // style
        `background-color: ${this.theme.palette.myColor};` +
        `position: relative;` +
        `margin: 1em;` +
        `text-align: center;`
         ...
      )
    )
  }
  constructor(
    public theme: LyTheme
  ) { }

  changeScheme() {
    const scheme = this.theme.palette.scheme === 'light' ?
    'dark' : this.theme.palette.scheme === 'dark' ?
    'myCustomScheme' : 'light';
    this.theme.setScheme(scheme);
  }
}

Github Repository

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

Look at SignalR Tests for the feature.

Test "SendToUser" takes automatically the user identity passed by using a regular owin authentication library.

The scenario is you have a user who has connected from multiple devices/browsers and you want to push a message to all his active connections.

What's the purpose of SQL keyword "AS"?

The AS in this case is an optional keyword defined in ANSI SQL 92 to define a <<correlation name> ,commonly known as alias for a table.

<table reference> ::=
            <table name> [ [ AS ] <correlation name>
                [ <left paren> <derived column list> <right paren> ] ]
          | <derived table> [ AS ] <correlation name>
                [ <left paren> <derived column list> <right paren> ]
          | <joined table>

     <derived table> ::= <table subquery>

     <derived column list> ::= <column name list>

     <column name list> ::=
          <column name> [ { <comma> <column name> }... ]


     Syntax Rules

     1) A <correlation name> immediately contained in a <table refer-
        ence> TR is exposed by TR. A <table name> immediately contained
        in a <table reference> TR is exposed by TR if and only if TR
        does not specify a <correlation name>.

It seems a best practice NOT to use the AS keyword for table aliases as it is not supported by a number of commonly used databases.

Can you have a <span> within a <span>?

HTML4 specification states that:

Inline elements may contain only data and other inline elements

Span is an inline element, therefore having span inside span is valid. There's a related question: Can <span> tags have any type of tags inside them? which makes it completely clear.

HTML5 specification (including the most current draft of HTML 5.3 dated November 16, 2017) changes terminology, but it's still perfectly valid to place span inside another span.

Set session variable in laravel

The correct syntax for this is...

Session::set('variableName', $value);

For Laravel 5.4 and later, the correct method to use is put.

Session::put('variableName', $value);

To get the variable, you'd use...

Session::get('variableName');

If you need to set it once, I'd figure out when exactly you want it set and use Events to do it. For example, if you want to set it when someone logs in, you'd use...

Event::listen('auth.login', function()
{
    Session::set('variableName', $value);
});

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

If you really sure that you installed cv2 but it gives no module error. There is a solution for this. Probably you have cv2.so file in your directory

/usr/local/lib/python2.7/site-packages/cv2.so

move this cv2.so file to

/usr/lib/python2.7/site-packages

copy the file into site-packages directory

Node.js Web Application examples/tutorials

DailyJS has a good tutorial (long series of 24 posts) that walks you through all the aspects of building a notepad app (including all the possible extras).

Heres an overview of the tutorial: http://dailyjs.com/2010/11/01/node-tutorial/

And heres a link to all the posts: http://dailyjs.com/tags.html#nodepad

JUnit Testing private variables?

Despite the danger of stating the obvious: With a unit test you want to test the correct behaviour of the object - and this is defined in terms of its public interface. You are not interested in how the object accomplishes this task - this is an implementation detail and not visible to the outside. This is one of the things why OO was invented: That implementation details are hidden. So there is no point in testing private members. You said you need 100% coverage. If there is a piece of code that cannot be tested by using the public interface of the object, then this piece of code is actually never called and hence not testable. Remove it.

Using an integer as a key in an associative array in JavaScript

If the use case is storing data in a collection then ECMAScript 6 provides the Map type.

It's only heavier to initialize.

Here is an example:

const map = new Map();
map.set(1, "One");
map.set(2, "Two");
map.set(3, "Three");

console.log("=== With Map ===");

for (const [key, value] of map) {
    console.log(`${key}: ${value} (${typeof(key)})`);
}

console.log("=== With Object ===");

const fakeMap = {
    1: "One",
    2: "Two",
    3: "Three"
};

for (const key in fakeMap) {
    console.log(`${key}: ${fakeMap[key]} (${typeof(key)})`);
}

Result:

=== With Map ===
1: One (number)
2: Two (number)
3: Three (number)
=== With Object ===
1: One (string)
2: Two (string)
3: Three (string)

Java check if boolean is null

boolean can only be true or false because it's a primitive datatype (+ a boolean variables default value is false). You can use the class Boolean instead if you want to use null values. Boolean is a reference type, that's the reason you can assign null to a Boolean "variable". Example:

Boolean testvar = null;
if (testvar == null) { ...}

Setting session variable using javascript

A session is stored server side, you can't modify it with JavaScript. Sessions may contain sensitive data.

You can modify cookies using document.cookie.

You can easily find many examples how to modify cookies.

Passing parameters to click() & bind() event in jquery?

see event.data

commentbtn.bind('click', { id: '12', name: 'Chuck Norris' }, function(event) {
    var data = event.data;
    alert(data.id);
    alert(data.name);
});

If your data is initialized before binding the event, then simply capture those variables in a closure.

// assuming id and name are defined in this scope
commentBtn.click(function() {
    alert(id), alert(name);
});

Displaying the build date

If this is a windows app, you can just use the application executable path: new System.IO.FileInfo(Application.ExecutablePath).LastWriteTime.ToString("yyyy.MM.dd")

How to run Maven from another directory (without cd to project dir)?

You can use the parameter -f (or --file) and specify the path to your pom file, e.g. mvn -f /path/to/pom.xml

This runs maven "as if" it were in /path/to for the working directory.

Javascript string/integer comparisons

You can use Number() function also since it converts the object argument to a number that represents the object's value.

Eg: javascript:alert( Number("2") > Number("10"))

How to change sender name (not email address) when using the linux mail command for autosending mail?

If no From: header is specified in the e-mail headers, the MTA uses the full name of the current user, in this case "Apache". You can edit full user names in /etc/passwd

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

for some reason, the ODBC user is the default username under windows even if you didn't create that user at setup time. simply typing

mysql

without specifying a username will attempt to connect with the non-existent ODBC username, and give:

Error 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO)

Instead, try specifying a username that you know, for example:

mysql -u root -p

where -u root specified the username root and -p will make the command prompt for a password.

VBA Date as integer

Date is not an Integer in VB(A), it is a Double.

You can get a Date's value by passing it to CDbl().

CDbl(Now())      ' 40877.8052662037 

From the documentation:

The 1900 Date System

In the 1900 date system, the first day that is supported is January 1, 1900. When you enter a date, the date is converted into a serial number that represents the number of elapsed days starting with 1 for January 1, 1900. For example, if you enter July 5, 1998, Excel converts the date to the serial number 35981.

So in the 1900 system, 40877.805... represents 40,876 days after January 1, 1900 (29 November 2011), and ~80.5% of one day (~19:19h). There is a setting for 1904-based system in Excel, numbers will be off when this is in use (that's a per-workbook setting).

To get the integer part, use

Int(CDbl(Now())) ' 40877

which would return a LongDouble with no decimal places (i.e. what Floor() would do in other languages).

Using CLng() or Round() would result in rounding, which will return a "day in the future" when called after 12:00 noon, so don't do that.

Can lambda functions be templated?

I am aware that this question is about C++11. However, for those who googled and landed on this page, templated lambdas are now supported in C++14 and go by the name Generic Lambdas.

[info] Most of the popular compilers support this feature now. Microsoft Visual Studio 2015 supports. Clang supports. GCC supports.

Angular 6: saving data to local storage

First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript

Change Volley timeout duration

Just to contribute with my approach. As already answered, RetryPolicy is the way to go. But if you need a policy different the than default for all your requests, you can set it in a base Request class, so you don't need to set the policy for all the instances of your requests.

Something like this:

public class BaseRequest<T> extends Request<T> {

    public BaseRequest(int method, String url, Response.ErrorListener listener) {
        super(method, url, listener);
        setRetryPolicy(getMyOwnDefaultRetryPolicy());
    }
}

In my case I have a GsonRequest which extends from this BaseRequest, so I don't run the risk of forgetting to set the policy for an specific request and you can still override it if some specific request requires to.

Print current call stack from a method in Python code

Here's a variation of @RichieHindle's excellent answer which implements a decorator that can be selectively applied to functions as desired. Works with Python 2.7.14 and 3.6.4.

from __future__ import print_function
import functools
import traceback
import sys

INDENT = 4*' '

def stacktrace(func):
    @functools.wraps(func)
    def wrapped(*args, **kwds):
        # Get all but last line returned by traceback.format_stack()
        # which is the line below.
        callstack = '\n'.join([INDENT+line.strip() for line in traceback.format_stack()][:-1])
        print('{}() called:'.format(func.__name__))
        print(callstack)
        return func(*args, **kwds)

    return wrapped

@stacktrace
def test_func():
    return 42

print(test_func())

Output from sample:

test_func() called:
    File "stacktrace_decorator.py", line 28, in <module>
    print(test_func())
42

Sublime text 3. How to edit multiple lines?

Use CTRL+D at each line and it will find the matching words and select them then you can use multiple cursors.

You can also use find to find all the occurrences and then it would be multiple cursors too.

pull out p-values and r-squared from a linear regression

This is the easiest way to pull the p-values:

coef(summary(modelname))[, "Pr(>|t|)"]

Unable to open project... cannot be opened because the project file cannot be parsed

Goto PhoneGapTest>>platform Then delete the folder ios after that go to terminal then type: sudo phonegap build ios after that you can run the project

How does the bitwise complement operator (~ tilde) work?

This operation is a complement, not a negation.

Consider that ~0 = -1, and work from there.

The algorithm for negation is, "complement, increment".

Did you know? There is also "one's complement" where the inverse numbers are symmetrical, and it has both a 0 and a -0.

Take screenshots in the iOS simulator

You can google for IOS Simulator Cropper software useful for capturing screen shots and also easy to use with various options of taking snapshots like with simulator/without simulator.

Update Just pressing CMD + S will give you screenshot saved on desktop. Pretty easy huh..

Kubernetes pod gets recreated when deleted

Look out for stateful sets as well

kubectl get sts --all-namespaces

to delete all the stateful sets in a namespace

kubectl --namespace <yournamespace> delete sts --all

to delete them one by one

kubectl --namespace ag1 delete sts mssql1 
kubectl --namespace ag1 delete sts mssql2
kubectl --namespace ag1 delete sts mssql3

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

you can also skip creating dictionary altogether. i used below approach to same problem .

 mappedItems: {};
 items.forEach(item => {     
        if (mappedItems[item.key]) {
           mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount});
        } else {
          mappedItems[item.key] = [];
          mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount}));
        }
    });

error C4996: 'scanf': This function or variable may be unsafe in c programming

It sounds like it's just a compiler warning.

Usage of scanf_s prevents possible buffer overflow.
See: http://code.wikia.com/wiki/Scanf_s

Good explanation as to why scanf can be dangerous: Disadvantages of scanf

So as suggested, you can try replacing scanf with scanf_s or disable the compiler warning.

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

How to get a unix script to run every 15 seconds?

Won't running this in the background do it?

#!/bin/sh
while [ 1 ]; do
    echo "Hell yeah!" &
    sleep 15
done

This is about as efficient as it gets. The important part only gets executed every 15 seconds and the script sleeps the rest of the time (thus not wasting cycles).

Tar error: Unexpected EOF in archive

I had a similar problem with truncated tar files being produced by a cron job and redirecting standard out to a file fixed the issue.

From talking to a colleague, cron creates a pipe and limits the amount of output that can be sent to standard out. I fixed mine by removing -v from my tar command, making it much less verbose and keeping the error output in the same spot as the rest of my cron jobs. If you need the verbose tar output, you'll need to redirect to a file, though.

How do I change the default schema in sql developer?

Just create a new connection (hit the green plus sign) and enter the schema name and password of the new default schema your DBA suggested. You can switch between your old schema and the new schema with the pull down menu at the top right end of your window.

Android saving file to external storage

This code is Working great & Worked on KitKat as well. Appreciate @RajaReddy PolamReddy
Added few more steps here and also Visible on Gallery as well.

public void SaveOnClick(View v){
File mainfile;
String fpath;


    try {
//i.e  v2:My view to save on own folder     
        v2.setDrawingCacheEnabled(true);
//Your final bitmap according to my code.
        bitmap_tmp = v2.getDrawingCache();

File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)+File.separator+"/MyFolder");

          Random random=new Random();
          int ii=100000;
          ii=random.nextInt(ii);
          String fname="MyPic_"+ ii + ".jpg";
            File direct = new File(Environment.getExternalStorageDirectory() + "/MyFolder");

            if (!direct.exists()) {
                File wallpaperDirectory = new File("/sdcard/MyFolder/");
                wallpaperDirectory.mkdirs();
            }

            mainfile = new File(new File("/sdcard/MyFolder/"), fname);
            if (mainfile.exists()) {
                mainfile.delete();
            }

              FileOutputStream fileOutputStream;
        fileOutputStream = new FileOutputStream(mainfile);

        bitmap_tmp.compress(CompressFormat.JPEG, 100, fileOutputStream);
        Toast.makeText(MyActivity.this.getApplicationContext(), "Saved in Gallery..", Toast.LENGTH_LONG).show();
        fileOutputStream.flush();
        fileOutputStream.close();
        fpath=mainfile.toString();
        galleryAddPic(fpath);
    } catch(FileNotFoundException e){
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

This is Media scanner to Visible in Gallery.

private void galleryAddPic(String fpath) {
    Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
    File f = new File(fpath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
}

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

Sorry, brief moment of synapse failure. Here's the real answer.

require 'date'

Time.at(seconds_since_epoch_integer).to_datetime

Brief example (this takes into account the current system timezone):

$ date +%s
1318996912

$ irb

ruby-1.9.2-p180 :001 > require 'date'
 => true 

ruby-1.9.2-p180 :002 > Time.at(1318996912).to_datetime
 => #<DateTime: 2011-10-18T23:01:52-05:00 (13261609807/5400,-5/24,2299161)> 

Further update (for UTC):

ruby-1.9.2-p180 :003 > Time.at(1318996912).utc.to_datetime
 => #<DateTime: 2011-10-19T04:01:52+00:00 (13261609807/5400,0/1,2299161)>

Recent Update: I benchmarked the top solutions in this thread while working on a HA service a week or two ago, and was surprised to find that Time.at(..) outperforms DateTime.strptime(..) (update: added more benchmarks).

# ~ % ruby -v
#  => ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin13.0]

irb(main):038:0> Benchmark.measure do
irb(main):039:1*   ["1318996912", "1318496912"].each do |s|
irb(main):040:2*     DateTime.strptime(s, '%s')
irb(main):041:2>   end
irb(main):042:1> end

=> #<Benchmark ... @real=2.9e-05 ... @total=0.0>

irb(main):044:0> Benchmark.measure do
irb(main):045:1>   [1318996912, 1318496912].each do |i|
irb(main):046:2>     DateTime.strptime(i.to_s, '%s')
irb(main):047:2>   end
irb(main):048:1> end

=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>

irb(main):050:0* Benchmark.measure do
irb(main):051:1*   ["1318996912", "1318496912"].each do |s|
irb(main):052:2*     Time.at(s.to_i).to_datetime
irb(main):053:2>   end
irb(main):054:1> end

=> #<Benchmark ... @real=1.5e-05 ... @total=0.0>

irb(main):056:0* Benchmark.measure do
irb(main):057:1*   [1318996912, 1318496912].each do |i|
irb(main):058:2*     Time.at(i).to_datetime
irb(main):059:2>   end
irb(main):060:1> end

=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>

How can I determine whether a 2D Point is within a Polygon?

The trivial solution would be to divide the polygon to triangles and hit test the triangles as explained here

If your polygon is CONVEX there might be a better approach though. Look at the polygon as a collection of infinite lines. Each line dividing space into two. for every point it's easy to say if its on the one side or the other side of the line. If a point is on the same side of all lines then it is inside the polygon.

CSS scale down image to fit in containing div, without specifing original size

In a webpage where I wanted a in image to scale with browser size change and remain at the top, next to a fixed div, all I had to do was use a single CSS line: overflow:hidden; and it did the trick. The image scales perfectly.

What is especially nice is that this is pure css and will work even if Javascript is turned off.

CSS:

#ImageContainerDiv {
  overflow: hidden;
}

HTML:

<div id="ImageContainerDiv">
  <a href="URL goes here" target="_blank">
    <img src="MapName.png" alt="Click to load map" />
  </a>
</div>

syntax error, unexpected T_VARIABLE

There is no semicolon at the end of that instruction causing the error.

EDIT

Like RiverC pointed out, there is no semicolon at the end of the previous line!

require ("scripts/connect.php") 

EDIT

It seems you have no-semicolons whatsoever.

http://php.net/manual/en/language.basic-syntax.instruction-separation.php

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement.

How to encode a string in JavaScript for displaying in HTML?

You need to escape < and &. Escaping > too doesn't hurt:

function magic(input) {
    input = input.replace(/&/g, '&amp;');
    input = input.replace(/</g, '&lt;');
    input = input.replace(/>/g, '&gt;');
    return input;
}

Or you let the DOM engine do the dirty work for you (using jQuery because I'm lazy):

function magic(input) {
    return $('<span>').text(input).html();
}

What this does is creating a dummy element, assigning your string as its textContent (i.e. no HTML-specific characters have side effects since it's just text) and then you retrieve the HTML content of that element - which is the text but with special characters converted to HTML entities in cases where it's necessary.

Could not find server 'server name' in sys.servers. SQL Server 2014

At first check out that your linked server is in the list by this query

select name from sys.servers

If it not exists then try to add to the linked server

EXEC sp_addlinkedserver @server = 'SERVER_NAME' --or may be server ip address

After that login to that linked server by

EXEC sp_addlinkedsrvlogin 'SERVER_NAME'
                         ,'false'
                         ,NULL
                         ,'USER_NAME'
                         ,'PASSWORD'

Then you can do whatever you want ,treat it like your local server

exec [SERVER_NAME].[DATABASE_NAME].dbo.SP_NAME @sample_parameter

Finally you can drop that server from linked server list by

sp_dropserver 'SERVER_NAME', 'droplogins'

If it will help you then please upvote.

How can I convert a DOM element to a jQuery element?

var elm = document.createElement("div");
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element

compareTo() vs. equals()

Here one thing is important while using compareTo() over equals() that compareTo works for the classes that implements 'Comparable' interface otherwise it will throw a NullPointerException. String classes implements Comparable interface while StringBuffer does not hence you can use "foo".compareTo("doo") in String object but not in StringBuffer Object.

Renaming part of a filename

There are a couple of variants of a rename command, in your case, it may be as simple as

rename ABC XYZ *.dat

You may have a version which takes a Perl regex;

rename 's/ABC/XYZ/' *.dat

Difference between git pull and git pull --rebase

git pull = git fetch + git merge against tracking upstream branch

git pull --rebase = git fetch + git rebase against tracking upstream branch

If you want to know how git merge and git rebase differ, read this.

How to convert text column to datetime in SQL

In SQL Server , cast text as datetime

select cast('5/21/2013 9:45:48' as datetime)

Most efficient way to concatenate strings?

Try this 2 pieces of code and you will find the solution.

 static void Main(string[] args)
    {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < 10000000; i++)
        {
            s.Append( i.ToString());
        }
        Console.Write("End");
        Console.Read();
    }

Vs

static void Main(string[] args)
    {
        string s = "";
        for (int i = 0; i < 10000000; i++)
        {
            s += i.ToString();
        }
        Console.Write("End");
        Console.Read();
    }

You will find that 1st code will end really quick and the memory will be in a good amount.

The second code maybe the memory will be ok, but it will take longer... much longer. So if you have an application for a lot of users and you need speed, use the 1st. If you have an app for a short term one user app, maybe you can use both or the 2nd will be more "natural" for developers.

Cheers.

Bootstrap modal z-index

I fell into this this with using the JQLayout plugin, especially when using nested layouts and modals with Bootstrap 4.

An overriding css needs to be added to correct the behaviour,

.pane-center{
    z-index:inherit !important;
}

Spring Boot - Cannot determine embedded database driver class for database type NONE

If you really need "spring-boot-starter-data-jpa" as your project dependency and at the same time you don't want to allow your app to access any database, you can simply exclude auto-configuration classes

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

SQL Server Management Studio missing

Did you include "Management Tools" as a chosen option during setup?

enter image description here

Ensure this option is selected, and SQL Server Management Studio will be installed on the machine.

How to use setInterval and clearInterval?

setInterval sets up a recurring timer. It returns a handle that you can pass into clearInterval to stop it from firing:

var handle = setInterval(drawAll, 20);

// When you want to cancel it:
clearInterval(handle);
handle = 0; // I just do this so I know I've cleared the interval

On browsers, the handle is guaranteed to be a number that isn't equal to 0; therefore, 0 makes a handy flag value for "no timer set". (Other platforms may return other values; NodeJS's timer functions return an object, for instance.)

To schedule a function to only fire once, use setTimeout instead. It won't keep firing. (It also returns a handle you can use to cancel it via clearTimeout before it fires that one time if appropriate.)

setTimeout(drawAll, 20);

How to get a password from a shell script without echoing

You can also prompt for a password without setting a variable in the current shell by doing something like this:

$(read -s;echo $REPLY)

For instance:

my-command --set password=$(read -sp "Password: ";echo $REPLY)

You can add several of these prompted values with line break, doing this:

my-command --set user=$(read -sp "`echo $'\n '`User: ";echo $REPLY) --set password=$(read -sp "`echo $'\n '`Password: ";echo $REPLY)

What does character set and collation mean exactly?

From MySQL docs:

A character set is a set of symbols and encodings. A collation is a set of rules for comparing characters in a character set. Let's make the distinction clear with an example of an imaginary character set.

Suppose that we have an alphabet with four letters: 'A', 'B', 'a', 'b'. We give each letter a number: 'A' = 0, 'B' = 1, 'a' = 2, 'b' = 3. The letter 'A' is a symbol, the number 0 is the encoding for 'A', and the combination of all four letters and their encodings is a character set.

Now, suppose that we want to compare two string values, 'A' and 'B'. The simplest way to do this is to look at the encodings: 0 for 'A' and 1 for 'B'. Because 0 is less than 1, we say 'A' is less than 'B'. Now, what we've just done is apply a collation to our character set. The collation is a set of rules (only one rule in this case): "compare the encodings." We call this simplest of all possible collations a binary collation.

But what if we want to say that the lowercase and uppercase letters are equivalent? Then we would have at least two rules: (1) treat the lowercase letters 'a' and 'b' as equivalent to 'A' and 'B'; (2) then compare the encodings. We call this a case-insensitive collation. It's a little more complex than a binary collation.

In real life, most character sets have many characters: not just 'A' and 'B' but whole alphabets, sometimes multiple alphabets or eastern writing systems with thousands of characters, along with many special symbols and punctuation marks. Also in real life, most collations have many rules: not just case insensitivity but also accent insensitivity (an "accent" is a mark attached to a character as in German 'ö') and multiple-character mappings (such as the rule that 'ö' = 'OE' in one of the two German collations).

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Ignore parent padding

The problem could come down to which box model you're using. Are you using IE?

When IE is in quirks mode, width is the outer width of your box, which means the padding will be inside. So the total area left inside the box is 100px - 2 * 10px = 80px in which case your 100px wide <hr> will not look right.

If you're in standards mode, width is the inner width of your box, and padding is added outside. So the total width of the box is 100px + 2 * 10px = 120px leaving exactly 100px inside the box for your <hr>.

To solve it, either adjust your CSS values for IE. (Check in Firefox to see if it looks okay there). Or even better, set a document type to kick the browser into strict mode - where also IE follows the standard box model.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html>
 ...

http://www.quirksmode.org/css/quirksmode.html

Read from database and fill DataTable

Private Function LoaderData(ByVal strSql As String) As DataTable
    Dim cnn As SqlConnection
    Dim dad As SqlDataAdapter

    Dim dtb As New DataTable
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        dad = New SqlDataAdapter(strSql, cnn)
        dad.Fill(dtb)
        cnn.Close()
        dad.Dispose()
    Catch ex As Exception
        cnn.Close()
        MsgBox(ex.Message)
    End Try
    Return dtb
End Function

Is calling destructor manually always a sign of bad design?

I have never come across a situation where one needs to call a destructor manually. I seem to remember even Stroustrup claims it is bad practice.

How to round a number to n decimal places in Java

Here is a summary of what you can use if you want the result as String:

  1. DecimalFormat#setRoundingMode():

    DecimalFormat df = new DecimalFormat("#.#####");
    df.setRoundingMode(RoundingMode.HALF_UP);
    String str1 = df.format(0.912385)); // 0.91239
    
  2. BigDecimal#setScale()

    String str2 = new BigDecimal(0.912385)
        .setScale(5, BigDecimal.ROUND_HALF_UP)
        .toString();
    

Here is a suggestion of what libraries you can use if you want double as a result. I wouldn't recommend it for string conversion, though, as double may not be able to represent what you want exactly (see e.g. here):

  1. Precision from Apache Commons Math

    double rounded = Precision.round(0.912385, 5, BigDecimal.ROUND_HALF_UP);
    
  2. Functions from Colt

    double rounded = Functions.round(0.00001).apply(0.912385)
    
  3. Utils from Weka

    double rounded = Utils.roundDouble(0.912385, 5)
    

Run ssh and immediately execute command

You can use the LocalCommand command-line option if the PermitLocalCommand option is enabled:

ssh username@hostname -o LocalCommand="tmux list-sessions"

For more details about the available options, see the ssh_config man page.

Using Excel VBA to export data to MS Access table

@Ahmed

Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".

Sub test()
    dbWb = Application.ActiveWorkbook.FullName
    dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2"  'Data2 is a named range


sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close


End Sub

npm ERR! Error: EPERM: operation not permitted, rename

I was getting the same thing. I didn't find this anywhere but it hit me that our VMs tend to change files to a read-only state. So I opened package.json's file properties and deselected Read-only in the "General" tab.

Steps

  1. Go to the package.json file.
  2. Right-click and select Properties.
  3. In the General tab, Attributes section, deselect Read-only.
  4. Click Apply to apply the change.

How to commit changes to a new branch

If I understand right, you've made a commit to changed_branch and you want to copy that commit to other_branch? Easy:

git checkout other_branch
git cherry-pick changed_branch

React native ERROR Packager can't listen on port 8081

This might be because of McAfee using that port. Doing simple lsof -i 8081 may not show the application and you may have to sudo it.

Do sudo lsof -i 8081 and if this command gives an output you can kill it by using sudo launchctl remove com.mcafee.agent.macmn. After this start packager again.

How to suppress binary file matching results in grep

This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:

bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk  ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$

SQL INSERT INTO from multiple tables

Here is an example if multiple tables don't have common Id, you can create yourself, I use 1 as commonId to create common id so that I can inner join them:

Insert Into #TempResult
select CountA, CountB, CountC  from

(
select Count(A_Id) as CountA, 1 as commonId from tableA
  where ....
  and  ...
  and   ...
) as tempA

inner join
(
select Count(B_Id) as CountB, 1 as commonId from tableB
  where ...
  and ...
  and  ...
 ) as tempB

on tempA.commonId = tempB.commonId

inner join
(
select Count(C_ID) as CountC, 1 as commonId from tableC
where ...
and   ...
) as tempC

on tmepB.commonId = tempC.commonId

--view insert result
select * from #TempResult

Access-control-allow-origin with multiple domains

In Web.API this attribute can be added using Microsoft.AspNet.WebApi.Cors as detailed at http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

In MVC you could create a filter attribute to do this work for you:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,
                AllowMultiple = true, Inherited = true)]
public class EnableCorsAttribute : FilterAttribute, IActionFilter {
    private const string IncomingOriginHeader = "Origin";
    private const string OutgoingOriginHeader = "Access-Control-Allow-Origin";
    private const string OutgoingMethodsHeader = "Access-Control-Allow-Methods";
    private const string OutgoingAgeHeader = "Access-Control-Max-Age";

    public void OnActionExecuted(ActionExecutedContext filterContext) {
        // Do nothing
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var isLocal = filterContext.HttpContext.Request.IsLocal;
        var originHeader = 
             filterContext.HttpContext.Request.Headers.Get(IncomingOriginHeader);
        var response = filterContext.HttpContext.Response;

        if (!String.IsNullOrWhiteSpace(originHeader) &&
            (isLocal || IsAllowedOrigin(originHeader))) {
            response.AddHeader(OutgoingOriginHeader, originHeader);
            response.AddHeader(OutgoingMethodsHeader, "GET,POST,OPTIONS");
            response.AddHeader(OutgoingAgeHeader, "3600");
        }
    }

    protected bool IsAllowedOrigin(string origin) {
        // ** replace with your own logic to check the origin header
        return true;
    }
}

Then either enable it for specific actions / controllers:

[EnableCors]
public class SecurityController : Controller {
    // *snip*
    [EnableCors]
    public ActionResult SignIn(Guid key, string email, string password) {

Or add it for all controllers in Global.asax.cs

protected void Application_Start() {
    // *Snip* any existing code

    // Register global filter
    GlobalFilters.Filters.Add(new EnableCorsAttribute());
    RegisterGlobalFilters(GlobalFilters.Filters);

    // *snip* existing code
}

Max tcp/ip connections on Windows Server 2008

How many thousands of users?

I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.

Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.

If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.

Edited to add details from the comment below...

If you're already thinking of multiple servers I'd take the following approach.

  1. Use the free tools that I link to and prove to yourself that you can create a reasonable number of connections onto your target OS (beware of the Windows limits on dynamic ports which may cause your client connections to fail, search for MAX_USER_PORT).

  2. during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html

Spring MVC Controller redirect using URL parameters instead of in response

Hey you can just do one simple thing instead of using model to send parameter use HttpServletRequest object and do this

HttpServletRequest request;
request.setAttribute("param", "value")

now your parametrs will not be shown in your url header hope it works :)

Installing Android Studio, does not point to a valid JVM installation error

Point your JAVA_HOME variable to C:\Program Files\Java\jdk1.8.0_xx\ where "xx" is the update number (make sure this matches your actual directory name). Do not include bin\javaw.exe in the pathname.

NOTE: You can access the Environment Variables GUI from the CLI by entering rundll32 sysdm.cpl,EditEnvironmentVariables. Be sure to put the 'JAVA_HOME' path variable in the System variables rather than the user variables. If the path variable is in User the Android Studio will not find the path.

Ruby objects and JSON serialization (without Rails)

Since I searched a lot myself to serialize a Ruby Object to json:

require 'json'

class User
  attr_accessor :name, :age

  def initialize(name, age)
    @name = name
    @age = age
  end

  def as_json(options={})
    {
      name: @name,
      age: @age
    }
  end

  def to_json(*options)
    as_json(*options).to_json(*options)
  end
end

user = User.new("Foo Bar", 42)
puts user.to_json #=> {"name":"Foo Bar","age":42}

How to set tint for an image view programmatically in android?

Simple and one line

imageView.setColorFilter(activity.getResources().getColor(R.color.your_color));

Making Maven run all tests, even when some fail

Can you test with surefire 2.6 and either configure Surefire with <testFailureIgnore>true</testFailureIgnore>.

Or on the command line:

mvn install -Dmaven.test.failure.ignore=true

What reference do I need to use Microsoft.Office.Interop.Excel in .NET?

Here is super solid solution, you just need have excell.dll in your Debug/Release folder Mine is 77,824 bytes, I downloaded it as a file, this also explain why some people have Debug compiled but Release not or vice versa.

Trento

How to edit/save a file through Ubuntu Terminal

If you are not root user then, use following commands:

There are two ways to do it -

1.

sudo vi path_to_file/file_name

Press Esc and then type below respectively

:wq //save and exit
:q! //exit without saving
  1. sudo nano path_to_file/file_name

When using nano: after you finish editing press ctrl+x then it will ask save Y/N.
If you want to save press Y, if not press N. And press enter to exit the editor.

#pragma pack effect

Data elements (e.g. members of classes and structs) are typically aligned on WORD or DWORD boundaries for current generation processors in order to improve access times. Retrieving a DWORD at an address which isn't divisible by 4 requires at least one extra CPU cycle on a 32 bit processor. So, if you have e.g. three char members char a, b, c;, they actually tend to take 6 or 12 bytes of storage.

#pragma allows you to override this to achieve more efficient space usage, at the expense of access speed, or for consistency of stored data between different compiler targets. I had a lot of fun with this transitioning from 16 bit to 32 bit code; I expect porting to 64 bit code will cause the same kinds of headaches for some code.

How to convert seconds to HH:mm:ss in moment.js

You can use moment-duration-format plugin:

_x000D_
_x000D_
var seconds = 3820;
var duration = moment.duration(seconds, 'seconds');
var formatted = duration.format("hh:mm:ss");
console.log(formatted); // 01:03:40
_x000D_
<!-- Moment.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

<!-- moment-duration-format plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
_x000D_
_x000D_
_x000D_

See also this Fiddle

Upd: To avoid trimming for values less than 60-sec use { trim: false }:

var formatted = duration.format("hh:mm:ss", { trim: false }); // "00:00:05"

How to convert an entire MySQL database characterset and collation to UTF-8?

The only solution that worked for me: http://docs.moodle.org/23/en/Converting_your_MySQL_database_to_UTF8

Converting a database containing tables

mysqldump -uusername -ppassword -c -e --default-character-set=utf8 --single-transaction --skip-set-charset --add-drop-database -B dbname > dump.sql

cp dump.sql dump-fixed.sql
vim dump-fixed.sql

:%s/DEFAULT CHARACTER SET latin1/DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci/
:%s/DEFAULT CHARSET=latin1/DEFAULT CHARSET=utf8/
:wq

mysql -uusername -ppassword < dump-fixed.sql

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.

Remove the string on the beginning of an URL

If the string has always the same format, a simple substr() should suffice.

var newString = originalStrint.substr(4)

VBA using ubound on a multidimensional array

Looping D3 ways;

Sub SearchArray()
    Dim arr(3, 2) As Variant
    arr(0, 0) = "A"
    arr(0, 1) = "1"
    arr(0, 2) = "w"

    arr(1, 0) = "B"
    arr(1, 1) = "2"
    arr(1, 2) = "x"

    arr(2, 0) = "C"
    arr(2, 1) = "3"
    arr(2, 2) = "y"

    arr(3, 0) = "D"
    arr(3, 1) = "4"
    arr(3, 2) = "z"

    Debug.Print "Loop Dimension 1"
    For i = 0 To UBound(arr, 1)
        Debug.Print "arr(" & i & ", 0) is " & arr(i, 0)
    Next i
    Debug.Print ""

    Debug.Print "Loop Dimension 2"
    For j = 0 To UBound(arr, 2)
        Debug.Print "arr(0, " & j & ") is " & arr(0, j)
    Next j
    Debug.Print ""

    Debug.Print "Loop Dimension 1 and 2"
    For i = 0 To UBound(arr, 1)
        For j = 0 To UBound(arr, 2)
            Debug.Print "arr(" & i & ", " & j & ") is " & arr(i, j)
        Next j
    Next i
    Debug.Print ""

End Sub

Entity Framework and Connection Pooling

Accoriding to EF6 (4,5 also) documentation: https://msdn.microsoft.com/en-us/data/hh949853#9

9.3 Context per request

Entity Framework’s contexts are meant to be used as short-lived instances in order to provide the most optimal performance experience. Contexts are expected to be short lived and discarded, and as such have been implemented to be very lightweight and reutilize metadata whenever possible. In web scenarios it’s important to keep this in mind and not have a context for more than the duration of a single request. Similarly, in non-web scenarios, context should be discarded based on your understanding of the different levels of caching in the Entity Framework. Generally speaking, one should avoid having a context instance throughout the life of the application, as well as contexts per thread and static contexts.

How can I monitor the thread count of a process on linux?

jvmtop can show the current jvm thread count beside other metrics.

How do I redirect to the previous action in ASP.NET MVC?

You could return to the previous page by using ViewBag.ReturnUrl property.

How to see tomcat is running or not

open your browser,check whether Tomcat homepage is visible by below command.

http://ipaddress:portnumber

also check this

How to pip or easy_install tkinter on Windows

In python, Tkinter was a default package, you can repair the installation and select Tcl/Tk. repair When you run this, DDL should be installed like so: enter image description here

Gridview row editing - dynamic binding to a DropDownList

You can use SelectedValue:

<EditItemTemplate>
    <asp:DropDownList ID="ddlPBXTypeNS"
                      runat="server"
                      Width="200px"
                      DataSourceID="YDS"
                      DataTextField="CaptionValue"
                      DataValueField="OID"
                      SelectedValue='<%# Bind("YourForeignKey") %>' />
    <asp:YourDataSource ID="YDS" ...../>
</EditItemTemplate>

Android Studio: /dev/kvm device permission denied

Step 1: (Install qemu-kvm)

sudo apt install qemu-kvm

Step 2: (Add your user to kvm group using)

sudo adduser username kvm

Step 3: (If still showing permission denied)

sudo chown username /dev/kvm

Final step:

ls -al /dev/kvm

Parsing xml using powershell

If you want to start with a file you can do this

[xml]$cn = Get-Content config.xml
$cn.xml.Section.BEName

Use PowerShell to Parse an XML File

ReactJS map through Object

I use the below Object.entries to easily output the key and the value:

{Object.entries(someObject).map(([key, val], i) => (
    <p key={i}>
        {key}: {val}
    </p>
))}

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

I know that you can modify a javascript file when using Google Chrome.

  1. Open up Chrome Inspector, go to the "Scripts" tab.
  2. Press the drop-down menu and select the javascript file that you want to edit.
  3. Double click in the text field, type in what ever you want and delete whatever you want.
  4. Then all you have to do is press Ctrl + S to save the file.

Warning: If you refresh the page, all changes will go back to original file. I recommend to copy/paste the code somewhere else if you want to use it again.

Hope this helps!

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

I am using Docker. I am trying to create a docker image that has all of my node dependencies installed, but can use my local app directory at container run time (without polluting it with a node_modules directory or link). This causes problems in this scenario. My workaround is to require from the exact path where the module, e.g. require('/usr/local/lib/node_modules/socket.io')

How to set Android camera orientation properly?

I faced the issue when i was using ZBar for scanning in tabs. Camera orientation issue. Using below code i was able to resolve issue. This is not the whole code snippet, Please take only help from this.

 public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
     if (isPreviewRunning) {
            mCamera.stopPreview();
        }

 setCameraDisplayOrientation(mCamera);

        previewCamera();

    }



 public void previewCamera() {

        try {
            // Hard code camera surface rotation 90 degs to match Activity view
            // in portrait
            mCamera.setPreviewDisplay(mHolder);
            mCamera.setPreviewCallback(previewCallback);
            mCamera.startPreview();
            mCamera.autoFocus(autoFocusCallback);
            isPreviewRunning = true;
        } catch (Exception e) {
            Log.d("DBG", "Error starting camera preview: " + e.getMessage());
        }


    }


public void setCameraDisplayOrientation(android.hardware.Camera camera) {
        Camera.Parameters parameters = camera.getParameters();

        android.hardware.Camera.CameraInfo camInfo =
                new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(getBackFacingCameraId(), camInfo);


        Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int rotation = display.getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        int result;
        if (camInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (camInfo.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (camInfo.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }




    private int getBackFacingCameraId() {
        int cameraId = -1;
        // Search for the front facing camera
        int numberOfCameras = Camera.getNumberOfCameras();
        for (int i = 0; i < numberOfCameras; i++) {
            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {

                cameraId = i;
                break;
            }
        }
        return cameraId;
    }

How to disable GCC warnings for a few lines of code

I know the question is about GCC, but for people looking for how to do this in other and/or multiple compilers…

TL;DR

You might want to take a look at Hedley, which is a public-domain single C/C++ header I wrote which does a lot of this stuff for you. I'll put a quick section about how to use Hedley for all this at the end of this post.

Disabling the warning

#pragma warning (disable: …) has equivalents in most compilers:

  • MSVC: #pragma warning(disable:4996)
  • GCC: #pragma GCC diagnostic ignored "-W…" where the ellipsis is the name of the warning; e.g., #pragma GCC diagnostic ignored "-Wdeprecated-declarations.
  • clang: #pragma clang diagnostic ignored "-W…". The syntax is basically the same as GCC's, and many of the warning names are the same (though many aren't).
  • Intel C Compiler: Use the MSVC syntax, but keep in mind that warning numbers are totally different. Example: #pragma warning(disable:1478 1786).
  • PGI/NVidia: There is a diag_suppress pragma: #pragma diag_suppress 1215,1444. Note that all warning numbers increased by one in 20.7 (the first NV HPC release).
  • TI: There is a diag_suppress pragma with the same syntax (but different warning numbers!) as PGI: pragma diag_suppress 1291,1718
  • Oracle Developer Studio (suncc): there is an error_messages pragma. Annoyingly, the warnings are different for the C and C++ compilers. Both of these disable basically the same warnings:
    • C: #pragma error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)
    • C++: #pragma error_messages(off,symdeprecated,symdeprecated2)
  • IAR: also uses diag_suppress like PGI and TI, but the syntax is different. Some of the warning numbers are the same, but I others have diverged: #pragma diag_suppress=Pe1444,Pe1215
  • Pelles C: similar to MSVC, though again the numbers are different #pragma warn(disable:2241)

For most compilers it is often a good idea to check the compiler version before trying to disable it, otherwise you'll just end up triggering another warning. For example, GCC 7 added support for the -Wimplicit-fallthrough warning, so if you care about GCC before 7 you should do something like

#if defined(__GNUC__) && (__GNUC__ >= 7)
#  pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#endif

For clang and compilers based on clang such as newer versions of XL C/C++ and armclang, you can check to see if the compiler knows about a particular warning using the __has_warning() macro.

#if __has_warning("-Wimplicit-fallthrough")
#  pragma clang diagnostic ignored "-Wimplicit-fallthrough"
#endif

Of course you also have to check to see if the __has_warning() macro exists:

#if defined(__has_warning)
#  if __has_warning("-Wimplicit-fallthrough")
#    pragma clang diagnostic ignored "-Wimplicit-fallthrough"
#  endif
#endif

You may be tempted to do something like

#if !defined(__has_warning)
#  define __has_warning(warning)
#endif

So you can use __has_warning a bit more easily. Clang even suggests something similar for the __has_builtin() macro in their manual. Do not do this. Other code may check for __has_warning and fall back on checking compiler versions if it doesn't exist, and if you define __has_warning you'll break their code. The right way to do this is to create a macro in your namespace. For example:

#if defined(__has_warning)
#  define MY_HAS_WARNING(warning) __has_warning(warning)
#else
#  define MY_HAS_WARNING(warning) (0)
#endif

Then you can do stuff like

#if MY_HAS_WARNING(warning)
#  pragma clang diagnostic ignored "-Wimplicit-fallthrough"
#elif defined(__GNUC__) && (__GNUC__ >= 7)
#  pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#endif

Pushing and popping

Many compilers also support a way to push and pop warnings onto a stack. For example, this will disable a warning on GCC for one line of code, then return it to its previous state:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated"
call_deprecated_function();
#pragma GCC diagnostic pop

Of course there isn't a lot of agreement across compilers about the syntax:

  • GCC 4.6+: #pragma GCC diagnostic push / #pragma GCC diagnostic pop
  • clang: #pragma clang diagnostic push / #pragma diagnostic pop
  • Intel 13+ (and probably earlier): #pragma warning(push) / #pragma warning(pop)
  • MSVC 15+ (VS 9.0 / 2008): #pragma warning(push) / #pragma warning(pop)
  • ARM 5.6+: #pragma push / #pragma pop
  • TI 8.1+: #pragma diag_push / #pragma diag_pop
  • Pelles C 2.90+ (and probably earlier): #pragma warning(push) / #pragma warning(pop)

If memory serves, for some very old versions of GCC (like 3.x, IIRC) the push/pop pragmas had to be outside of the function.

Hiding the gory details

For most compilers it's possible to hide the logic behind macros using _Pragma, which was introduced in C99. Even in non-C99 mode, most compilers support _Pragma; the big exception is MSVC, which has its own __pragma keyword with a different syntax. The standard _Pragma takes a string, Microsoft's version doesn't:

#if defined(_MSC_VER)
#  define PRAGMA_FOO __pragma(foo)
#else
#  define PRAGMA_FOO _Pragma("foo")
#endif
PRAGMA_FOO

Is roughly equivalent, once preprocessed, to

#pragma foo

This lets us create macros so we can write code like

MY_DIAGNOSTIC_PUSH
MY_DIAGNOSTIC_DISABLE_DEPRECATED
call_deprecated_function();
MY_DIAGNOSTIC_POP

And hide away all the ugly version checks in the macro definitions.

The easy way: Hedley

Now that you understand the mechanics of how to do stuff like this portably while keeping your code clean, you understand what one of my projects, Hedley does. Instead of digging through tons of documentation and/or installing as many versions of as many compilers as you can to test with, you can just include Hedley (it is a single public domain C/C++ header) and be done with it. For example:

#include "hedley.h"

HEDLEY_DIAGNOSTIC_PUSH
HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
call_deprecated();
HEDLEY_DIAGNOSTIC_POP

Will disable the warning about calling a deprecated function on GCC, clang, ICC, PGI, MSVC, TI, IAR, ODS, Pelles, and possibly others (I probably won't bother updating this answer as I update Hedley). And, on compilers which aren't known to work, the macros will be preprocessed away to nothing, so your code will continue to work with any compiler. Of course HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED isn't the only warning Hedley knows about, nor is disabling warnings all Hedley can do, but hopefully you get the idea.

Sorting a vector in descending order

What about this?

std::sort(numbers.begin(), numbers.end());
std::reverse(numbers.begin(), numbers.end());

Numpy: Creating a complex array from 2 real ones?

import numpy as np

n = 51 #number of data points
# Suppose the real and imaginary parts are created independently
real_part = np.random.normal(size=n)
imag_part = np.random.normal(size=n)

# Create a complex array - the imaginary part will be equal to zero
z = np.array(real_part, dtype=complex)
# Now define the imaginary part:
z.imag = imag_part
print(z)

How to get terminal's Character Encoding

The terminal uses environment variables to determine which character set to use, therefore you can determine it by looking at those variables:

echo $LC_CTYPE

or

echo $LANG

Convert string to JSON Object

Enclose the string in single quote it should work. Try this.

var jsonObj = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
var obj = $.parseJSON(jsonObj);

Demo

How can I make git show a list of the files that are being tracked?

The files managed by git are shown by git ls-files. Check out its manual page.

Redirect using AngularJS

Don't forget to inject $location into controller.

How to style a div to have a background color for the entire width of the content, and not just for the width of the display?

black magic:

<style>
body { float:left;}
.success { background-color: #ccffcc;}
</style>

If anyone has a clear explanation of why this works, please comment. I think it has something to do with a side effect of the float that removes the constraint that the body must fit into the page width.

How do I create an Excel chart that pulls data from multiple sheets?

Use the Chart Wizard.

On Step 2 of 4, there is a tab labeled "Series". There are 3 fields and a list box on this tab. The list box shows the different series you are already including on the chart. Each series has both a "Name" field and a "Values" field that is specific to that series. The final field is the "Category (X) axis labels" field, which is common to all series.

Click on the "Add" button below the list box. This will add a blank series to your list box. Notice that the values for "Name" and for "Values" change when you highlight a series in the list box.

Select your new series.

There is an icon in each field on the right side. This icon allows you to select cells in the workbook to pull the data from. When you click it, the Wizard temporarily hides itself (except for the field you are working in) allowing you to interact with the workbook.

Select the appropriate sheet in the workbook and then select the fields with the data you want to show in the chart. The button on the right of the field can be clicked to unhide the wizard.

Hope that helps.

EDIT: The above applies to 2003 and before. For 2007, when the chart is selected, you should be able to do a similar action using the "Select Data" option on the "Design" tab of the ribbon. This opens up a dialog box listing the Series for the chart. You can select the series just as you could in Excel 2003, but you must use the "Add" and "Edit" buttons to define custom series.

How to commit a change with both "message" and "description" from the command line?

There is also another straight and more clear way

git commit -m "Title" -m "Description ..........";

Can I set state inside a useEffect hook

For future purposes, this may help too:

It's ok to use setState in useEffect you just need to have attention as described already to not create a loop.

But it's not the only problem that may occur. See below:

Imagine that you have a component Comp that receives props from parent and according to a props change you want to set Comp's state. For some reason, you need to change for each prop in a different useEffect:

DO NOT DO THIS

useEffect(() => {
  setState({ ...state, a: props.a });
}, [props.a]);

useEffect(() => {
  setState({ ...state, b: props.b });
}, [props.b]);

It may never change the state of a as you can see in this example: https://codesandbox.io/s/confident-lederberg-dtx7w

The reason why this happen in this example it's because both useEffects run in the same react cycle when you change both prop.a and prop.b so the value of {...state} when you do setState are exactly the same in both useEffect because they are in the same context. When you run the second setState it will replace the first setState.

DO THIS INSTEAD

The solution for this problem is basically call setState like this:

useEffect(() => {
  setState(state => ({ ...state, a: props.a }));
}, [props.a]);

useEffect(() => {
  setState(state => ({ ...state, b: props.b }));
}, [props.b]);

Check the solution here: https://codesandbox.io/s/mutable-surf-nynlx

Now, you always receive the most updated and correct value of the state when you proceed with the setState.

I hope this helps someone!

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

Have you tried, after calling DataBind on your DropDownList, to do something like ddl.SelectedIndex = 0 ?

How can I convert bigint (UNIX timestamp) to datetime in SQL Server?

Better? This function converts unixtime in milliseconds to datetime. It's lost milliseconds, but still very useful for filtering.

CREATE FUNCTION [dbo].[UnixTimestampToGMTDatetime] 
(@UnixTimestamp bigint)
RETURNS datetime
AS
BEGIN
       DECLARE @GMTDatetime datetime
       select @GMTDatetime = 
       CASE
       WHEN dateadd(ss, @UnixTimestamp/1000, '1970-01-01') 
       BETWEEN 
           Convert(DATETIME, Convert(VARCHAR(4), Year(dateadd(ss, @UnixTimestamp/1000, '1970-01-01') )) + '-03-' + Convert(VARCHAR(2), (31 - (5 * Year(dateadd(ss, @UnixTimestamp/1000, '1970-01-01') )/4 + 4) % 7)) + ' 01:00:00', 20)
       AND
           Convert(DATETIME, Convert(VARCHAR(4), Year(dateadd(ss, @UnixTimestamp/1000, '1970-01-01') )) + '-10-' + Convert(VARCHAR(2), (31 - (5 * Year(dateadd(ss, @UnixTimestamp/1000, '1970-01-01') )/4 + 1) % 7)) + ' 02:00:00', 20)
       THEN Dateadd(hh, 1, dateadd(ss, @UnixTimestamp/1000, '1970-01-01'))
       ELSE Dateadd(hh, 0, dateadd(ss, @UnixTimestamp/1000, '1970-01-01'))
       END
RETURN @GMTDatetime    
END

Replacing values from a column using a condition in R

I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful

library(dplyr)
iris %>% 
  mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))

How do you comment out code in PowerShell?

You can make:

 (Some basic code) # Use "#" after a line and use:

 <#
    for more lines
    ...
    ...
    ...
    ..
    .
 #>

cout is not a member of std

I had a similar issue and it turned out that i had to add an extra entry in cmake to include the files.

Since i was also using the zmq library I had to add this to the included libraries as well.

JQuery find first parent element with specific class prefix

Use .closest() with a selector:

var $div = $('#divid').closest('div[class^="div-a"]');

How to get an IFrame to be responsive in iOS Safari?

I am working with ionic2 and system config is as below-


******************************************************

Your system information:

Cordova CLI: 6.4.0 
Ionic Framework Version: 2.0.0-beta.10
Ionic CLI Version: 2.1.8
Ionic App Lib Version: 2.1.4
ios-deploy version: Not installed
ios-sim version: 5.0.8 
OS: OS X Yosemite
Node Version: v6.2.2
Xcode version: Xcode 7.2 Build version 7C68



******************************************************

For me this issue got resolved with this code-
for html iframe tag-

<div class="iframe_container">
      <iframe class= "animated fadeInUp" id="iframe1" [src]='page' frameborder="0" >
        <!--  <img src="img/video-icon.png"> -->
      </iframe><br>
   </div>

See css of the same as-


.iframe_container {
  overflow: auto; 
  position: relative; 
  -webkit-overflow-scrolling: touch;
  height: 75%;
}

iframe {
  position:relative;
  top: 2%;
  left: 5%;
  border: 0 !important;
  width: 90%;
}

Position property play a vital role here in my case.
position:relative;

It may help you too!!!

Set variable in jinja

Nice shorthand for Multiple variable assignments

{% set label_cls, field_cls = "col-md-7", "col-md-3" %}

A method to count occurrences in a list

var wordCount =
    from word in words
    group word by word into g
    select new { g.Key, Count = g.Count() };    

This is taken from one of the examples in the linqpad

UIView Hide/Show with animation

Swift 5.0, with generics:

func hideViewWithAnimation<T: UIView>(shouldHidden: Bool, objView: T) {
    if shouldHidden == true {
        UIView.animate(withDuration: 0.3, animations: {
            objView.alpha = 0
        }) { (finished) in
            objView.isHidden = shouldHidden
        }
    } else {
        objView.alpha = 0
        objView.isHidden = shouldHidden
        UIView.animate(withDuration: 0.3) {
            objView.alpha = 1
        }
    }
}   

Use:

hideViewWithAnimation(shouldHidden: shouldHidden, objView: itemCountLabelBGView)
hideViewWithAnimation(shouldHidden: shouldHidden, objView: itemCountLabel)
hideViewWithAnimation(shouldHidden: shouldHidden, objView: itemCountButton)

Here itemCountLabelBGView is a UIView, itemCountLabel is a UILabel & itemCountButton is a UIButton, So it will work for every view object whose parent class is UIView.

Use superscripts in R axis labels

The other option in this particular case would be to type the degree symbol: °

R seems to handle it fine. Type Option-k on a Mac to get it. Not sure about other platforms.

The Android emulator is not starting, showing "invalid command-line parameter"

Remember to run "android update avd -n avd_name" after change in Android SDK path.

Powershell script to check if service is started, if not then start it

Trying to do things as smooth as possible - I here suggest modifying GuyWhoLikesPowershell's suggestion slightly.

I replaced the if and until with one while - and I check for "Stopped", since I don't want to start if status is "starting" or " Stopping".

$Service = 'ServiceName'
while ((Get-Service $Service).Status -eq 'Stopped') 
{
    Start-Service $Service -ErrorAction SilentlyContinue
    Start-Sleep 10
} 
Return "$($Service) has STARTED"

Postgres "psql not recognized as an internal or external command"

Make sure that the path actually leads to the executables. I'm using version 11 and it did not work until this was set as the path:

C:\Program Files\PostgreSQL\11\bin\bin

Maybe this is how version 11 is structured or I somehow botched the installation but I haven't had a problem since.

How to convert string to integer in C#

If you are sure that you have "real" number in your string, or you are comfortable of any exception that might arise, use this.

string s="4";
int a=int.Parse(s);

For some more control over the process, use

string s="maybe 4";
int a;
if (int.TryParse(s, out a)) {
    // it's int;
}
else {
    // it's no int, and there's no exception;
}

How to serialize Joda DateTime with Jackson JSON processor?

As @Kimble has said, with Jackson 2, using the default formatting is very easy; simply register JodaModule on your ObjectMapper.

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());

For custom serialization/de-serialization of DateTime, you need to implement your own StdScalarSerializer and StdScalarDeserializer; it's pretty convoluted, but anyway.

For example, here's a DateTime serializer that uses the ISODateFormat with the UTC time zone:

public class DateTimeSerializer extends StdScalarSerializer<DateTime> {

    public DateTimeSerializer() {
        super(DateTime.class);
    }

    @Override
    public void serialize(DateTime dateTime,
                          JsonGenerator jsonGenerator,
                          SerializerProvider provider) throws IOException, JsonGenerationException {
        String dateTimeAsString = ISODateTimeFormat.withZoneUTC().print(dateTime);
        jsonGenerator.writeString(dateTimeAsString);
    }
}

And the corresponding de-serializer:

public class DateTimeDesrializer extends StdScalarDeserializer<DateTime> {

    public DateTimeDesrializer() {
        super(DateTime.class);
    }

    @Override
    public DateTime deserialize(JsonParser jsonParser,
                                DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        try {
            JsonToken currentToken = jsonParser.getCurrentToken();
            if (currentToken == JsonToken.VALUE_STRING) {
                String dateTimeAsString = jsonParser.getText().trim();
                return ISODateTimeFormat.withZoneUTC().parseDateTime(dateTimeAsString);
            }
        } finally {
            throw deserializationContext.mappingException(getValueClass());
        }
    }

Then tie these together with a module:

public class DateTimeModule extends SimpleModule {

    public DateTimeModule() {
        super();
        addSerializer(DateTime.class, new DateTimeSerializer());
        addDeserializer(DateTime.class, new DateTimeDeserializer());
    }
}

Then register the module on your ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new DateTimeModule());

Finalize vs Dispose

The finalizer method is called when your object is garbage collected and you have no guarantee when this will happen (you can force it, but it will hurt performance).

The Dispose method on the other hand is meant to be called by the code that created your class so that you can clean up and release any resources you have acquired (unmanaged data, database connections, file handles, etc) the moment the code is done with your object.

The standard practice is to implement IDisposable and Dispose so that you can use your object in a using statment. Such as using(var foo = new MyObject()) { }. And in your finalizer, you call Dispose, just in case the calling code forgot to dispose of you.

Python: 'break' outside loop

This is an old question, but if you wanted to break out of an if statement, you could do:

while 1:
    if blah:
        break

How do you import a large MS SQL .sql file?

From the command prompt, start up sqlcmd:

sqlcmd -S <server> -i C:\<your file here>.sql 

Just replace <server> with the location of your SQL box and <your file here> with the name of your script. Don't forget, if you're using a SQL instance the syntax is:

sqlcmd -S <server>\instance.

Here is the list of all arguments you can pass sqlcmd:

Sqlcmd            [-U login id]          [-P password]
  [-S server]            [-H hostname]          [-E trusted connection]
  [-d use database name] [-l login timeout]     [-t query timeout] 
  [-h headers]           [-s colseparator]      [-w screen width]
  [-a packetsize]        [-e echo input]        [-I Enable Quoted Identifiers]
  [-c cmdend]            [-L[c] list servers[clean output]]
  [-q "cmdline query"]   [-Q "cmdline query" and exit] 
  [-m errorlevel]        [-V severitylevel]     [-W remove trailing spaces]
  [-u unicode output]    [-r[0|1] msgs to stderr]
  [-i inputfile]         [-o outputfile]        [-z new password]
  [-f  | i:[,o:]] [-Z new password and exit] 
  [-k[1|2] remove[replace] control characters]
  [-y variable length type display width]
  [-Y fixed length type display width]
  [-p[1] print statistics[colon format]]
  [-R use client regional setting]
  [-b On error batch abort]
  [-v var = "value"...]  [-A dedicated admin connection]
  [-X[1] disable commands, startup script, environment variables [and exit]]
  [-x disable variable substitution]
  [-? show syntax summary] 

How do I rename a file using VBScript?

Below code absolutely worked for me to update File extension.

Ex: abc.pdf to abc.txt

Filepath = "Pls mention your Filepath"

Set objFso = CreateObject("Scripting.FileSystemObject")

'' Below line of code is to get the object for Folder where list of files are located 
Set objFolder = objFso.GetFolder(Filepath)

'' Below line of code used to get the collection object to hold list of files located in the Filepath.
Set FileCollection = objFolder.Files

For Each file In FileCollection

    WScript.Echo "File name ->" + file.Name
    ''Instr used to Return the position of the first occurrence of "." within the File name
    s = InStr(1, file.Name, ".",1)
    WScript.Echo s
    WScript.Echo "Extn --> " + Mid(file.Name, s, Len(file.Name))

    'Left(file.Name,s-1) = Used to fetch the file name without extension
    ' Move method is used to move the file in the Desitnation folder you mentioned
    file.Move(Filepath & Left(file.Name,s-1)&".txt") 

Next

How to create a JavaScript callback for knowing when an image is loaded?

Image.onload() will often work.

To use it, you'll need to be sure to bind the event handler before you set the src attribute.

Related Links:

Example Usage:

_x000D_
_x000D_
    window.onload = function () {_x000D_
_x000D_
        var logo = document.getElementById('sologo');_x000D_
_x000D_
        logo.onload = function () {_x000D_
            alert ("The image has loaded!");  _x000D_
        };_x000D_
_x000D_
        setTimeout(function(){_x000D_
            logo.src = 'https://edmullen.net/test/rc.jpg';         _x000D_
        }, 5000);_x000D_
    };
_x000D_
 <html>_x000D_
    <head>_x000D_
    <title>Image onload()</title>_x000D_
    </head>_x000D_
    <body>_x000D_
_x000D_
    <img src="#" alt="This image is going to load" id="sologo"/>_x000D_
_x000D_
    <script type="text/javascript">_x000D_
_x000D_
    </script>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

ExecJS and could not find a JavaScript runtime

In your Gem file, write

gem 'execjs'
gem 'therubyracer'

and then run

bundle install

Everything works fine for me :)

Set HTML dropdown selected option using JSTL

In Servlet do:

String selectedRole = "rat"; // Or "cat" or whatever you'd like.
request.setAttribute("selectedRole", selectedRole);

Then in JSP do:

<select name="roleName">
    <c:forEach items="${roleNames}" var="role">
        <option value="${role}" ${role == selectedRole ? 'selected' : ''}>${role}</option>
    </c:forEach>
</select>

It will print the selected attribute of the HTML <option> element so that you end up like:

<select name="roleName">
    <option value="cat">cat</option>
    <option value="rat" selected>rat</option>
    <option value="unicorn">unicorn</option>
</select>

Apart from the problem: this is not a combo box. This is a dropdown. A combo box is an editable dropdown.

Can an Option in a Select tag carry multiple values?

you can use multiple attribute

<SELECT NAME="Testing" multiple>  
 <OPTION VALUE="1"> One  
 <OPTION VALUE="2"> Two  
 <OPTION VALUE="3"> Three

Maximum value of maxRequestLength?

These two settings worked for me to upload 1GB mp4 videos.

<system.web>
    <httpRuntime maxRequestLength="2097152" requestLengthDiskThreshold="2097152" executionTimeout="240"/>
</system.web>
<system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="2147483648" />
        </requestFiltering>
    </security>
</system.webServer>

Best way to store time (hh:mm) in a database

DATETIME start DATETIME end

I implore you to use two DATETIME values instead, labelled something like event_start and event_end.

Time is a complex business

Most of the world has now adopted the denery based metric system for most measurements, rightly or wrongly. This is good overall, because at least we can all agree that a g, is a ml, is a cubic cm. At least approximately so. The metric system has many flaws, but at least it's internationally consistently flawed.

With time however, we have; 1000 milliseconds in a second, 60 seconds to a minute, 60 minutes to an hour, 12 hours for each half a day, approximately 30 days per month which vary by the month and even year in question, each country has its time offset from others, the way time is formatted in each country vary.

It's a lot to digest, but the long and short of it is impossible for such a complex scenario to have a simple solution.

Some corners can be cut, but there are those where it is wiser not to

Although the top answer here suggests that you store an integer of minutes past midnight might seem perfectly reasonable, I have learned to avoid doing so the hard way.

The reasons to implement two DATETIME values are for an increase in accuracy, resolution and feedback.

These are all very handy for when the design produces undesirable results.

Am I storing more data than required?

It might initially appear like more information is being stored than I require, but there is a good reason to take this hit.

Storing this extra information almost always ends up saving me time and effort in the long-run, because I inevitably find that when somebody is told how long something took, they'll additionally want to know when and where the event took place too.

It's a huge planet

In the past, I have been guilty of ignoring that there are other countries on this planet aside from my own. It seemed like a good idea at the time, but this has ALWAYS resulted in problems, headaches and wasted time later on down the line. ALWAYS consider all time zones.

C#

A DateTime renders nicely to a string in C#. The ToString(string Format) method is compact and easy to read.

E.g.

new TimeSpan(EventStart.Ticks - EventEnd.Ticks).ToString("h'h 'm'm 's's'")

SQL server

Also if you're reading your database seperate to your application interface, then dateTimes are pleasnat to read at a glance and performing calculations on them are straightforward.

E.g.

SELECT DATEDIFF(MINUTE, event_start, event_end)

ISO8601 date standard

If using SQLite then you don't have this, so instead use a Text field and store it in ISO8601 format eg.

"2013-01-27T12:30:00+0000"

Notes:

  • This uses 24 hour clock*

  • The time offset (or +0000) part of the ISO8601 maps directly to longitude value of a GPS coordiate (not taking into account daylight saving or countrywide).

E.g.

TimeOffset=(±Longitude.24)/360 

...where ± refers to east or west direction.

It is therefore worth considering if it would be worth storing longitude, latitude and altitude along with the data. This will vary in application.

  • ISO8601 is an international format.

  • The wiki is very good for further details at http://en.wikipedia.org/wiki/ISO_8601.

  • The date and time is stored in international time and the offset is recorded depending on where in the world the time was stored.

In my experience there is always a need to store the full date and time, regardless of whether I think there is when I begin the project. ISO8601 is a very good, futureproof way of doing it.

Additional advice for free

It is also worth grouping events together like a chain. E.g. if recording a race, the whole event could be grouped by racer, race_circuit, circuit_checkpoints and circuit_laps.

In my experience, it is also wise to identify who stored the record. Either as a seperate table populated via trigger or as an additional column within the original table.

The more you put in, the more you get out

I completely understand the desire to be as economical with space as possible, but I would rarely do so at the expense of losing information.

A rule of thumb with databases is as the title says, a database can only tell you as much as it has data for, and it can be very costly to go back through historical data, filling in gaps.

The solution is to get it correct first time. This is certainly easier said than done, but you should now have a deeper insight of effective database design and subsequently stand a much improved chance of getting it right the first time.

The better your initial design, the less costly the repairs will be later on.

I only say all this, because if I could go back in time then it is what I'd tell myself when I got there.

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

I solved this error with clearing cache and restarting chrome. Hope they will fix it in ver 40.

Shrink a YouTube video to responsive width

See full gist here and live example here.

#hero { width:100%;height:100%;background:url('{$img_ps_dir}cms/how-it-works/hero.jpg') no-repeat top center; }
.videoWrapper { position:relative;padding-bottom:56.25%;padding-top:25px;max-width:100%; }

<div id="hero">
    <div class="container">
        <div class="row-fluid">
            <script src="https://www.youtube.com/iframe_api"></script>
            <center>
            <div class="videoWrapper">
                 <div id="player"></div>
            </div>
            </center>
            <script>
            function onYouTubeIframeAPIReady() { 
                player = new YT.Player('player', {
                   videoId:'xxxxxxxxxxx',playerVars: {  controls:0,autoplay:0,disablekb:1,enablejsapi:1,iv_load_policy:3,modestbranding:1,showinfo:0,rel:0,theme:'light' }
                } );
                resizeHeroVideo();
             }
             </script>
        </div>
    </div>
</div>

var player = null;
$( document ).ready(function() {
    resizeHeroVideo();
} );

$(window).resize(function() {
    resizeHeroVideo();
});

function resizeHeroVideo() {
    var content = $('#hero');
    var contentH = viewportSize.getHeight();
    contentH -= 158;
    content.css('height',contentH);

    if(player != null) {
        var iframe = $('.videoWrapper iframe');
        var iframeH = contentH - 150;
        if (isMobile) {
            iframeH = 163; 
        }
        iframe.css('height',iframeH);
        var iframeW = iframeH/9 * 16;
        iframe.css('width',iframeW);
    }
}

resizeHeroVideo is called only after the Youtube player has fully loaded (on page load does not work), and whenever the browser window is resized. When it runs, it calculates the height and width of the iframe and assigns the appropriate values maintaining the correct aspect ratio. This works whether the window is resized horizontally or vertically.

Concatenate two NumPy arrays vertically

A not well known feature of numpy is to use r_. This is a simple way to build up arrays quickly:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.r_[a[None,:],b[None,:]]
print(c)
#[[1 2 3]
# [4 5 6]]

The purpose of a[None,:] is to add an axis to array a.

How to make the window full screen with Javascript (stretching all over the screen)

This will works to show your window in full screen

Note: For this to work, you need Query from http://code.jquery.com/jquery-2.1.1.min.js

Or make have javascript link like this.

<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>

   <div id="demo-element">
        <span>Full Screen Mode Disabled</span>
        <button id="go-button">Enable Full Screen</button>
    </div>
    <script>
    function GoInFullscreen(element) {
        if(element.requestFullscreen)
            element.requestFullscreen();
        else if(element.mozRequestFullScreen)
            element.mozRequestFullScreen();
        else if(element.webkitRequestFullscreen)
            element.webkitRequestFullscreen();
        else if(element.msRequestFullscreen)
            element.msRequestFullscreen();
    }

    function GoOutFullscreen() {
        if(document.exitFullscreen)
            document.exitFullscreen();
        else if(document.mozCancelFullScreen)
            document.mozCancelFullScreen();
        else if(document.webkitExitFullscreen)
            document.webkitExitFullscreen();
        else if(document.msExitFullscreen)
            document.msExitFullscreen();
    }

    function IsFullScreenCurrently() {
        var full_screen_element = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement || null;

        if(full_screen_element === null)
            return false;
        else
            return true;
    }

    $("#go-button").on('click', function() {
        if(IsFullScreenCurrently())
            GoOutFullscreen();
        else
            GoInFullscreen($("#demo-element").get(0));
    });

    $(document).on('fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange', function() {
        if(IsFullScreenCurrently()) {
            $("#demo-element span").text('Full Screen Mode Enabled');
            $("#go-button").text('Disable Full Screen');
        }
        else {
            $("#demo-element span").text('Full Screen Mode Disabled');
            $("#go-button").text('Enable Full Screen');
        }
    });</script>

AngularJS - Attribute directive input value change

Since this must have an input element as a parent, you could just use

<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">

Alternatively, you could use the ngModelController and add a function to $formatters, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController

.directive("myDirective", function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attr, ngModel) {
      ngModel.$formatters.push(function(value) {
        // Do stuff here, and return the formatted value.
      });
  };
};

I lose my data when the container exits

You might want to look at docker volumes if you you want to persist the data in your container. Visit https://docs.docker.com/engine/tutorials/dockervolumes/. The docker documentation is a very good place to start

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

JavaScript hard refresh of current page

Try to use:

location.reload(true);

When this method receives a true value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

More info:

Case insensitive 'Contains(string)'

Simple way for newbie:

title.ToLower().Contains("string");//of course "string" is lowercase.

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

I have found that python-dotenv helps solve this issue pretty effectively. Your project structure ends up changing slightly, but the code in your notebook is a bit simpler and consistent across notebooks.

For your project, do a little install.

pipenv install python-dotenv

Then, project changes to:

+-- .env (this can be empty)
+-- ipynb
¦   +-- 20170609-Examine_Database_Requirements.ipynb
¦   +-- 20170609-Initial_Database_Connection.ipynb
+-- lib
    +-- __init__.py
    +-- postgres.py

And finally, your import changes to:

import os
import sys

from dotenv import find_dotenv


sys.path.append(os.path.dirname(find_dotenv()))

A +1 for this package is that your notebooks can be several directories deep. python-dotenv will find the closest one in a parent directory and use it. A +2 for this approach is that jupyter will load environment variables from the .env file on startup. Double whammy.

Read the package name of an Android APK

You can use Analyze APK... from the Build menu in Android Studio, it will display the package name at the top of new window.

Show Image View from file path?

How To Show Images From Folder path in Android

Very First: Make Sure You Have Add Permissions into Mainfest file:

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

:Make a Class MyGallery

public class MyGallery extends Activity {


    private GridView gridView;
    private String _location;

    private String newFolder = "/IslamicGif/";
    private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
    private AdView mAdView;
    private ArrayList<Bitmap> photo = new ArrayList<Bitmap>();
    public static String[] imageFileList;
    TextView gallerytxt;

    public static ImageAdapter imageAdapter;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.mygallery);
        /*if (MenuClass.mInterstitialAd.isLoaded()) {
            MenuClass.mInterstitialAd.show();
        }*/

        gallerytxt = (TextView) findViewById(R.id.gallerytxt);
        /*gallerytxt.setTextSize(20);
        int[] color = {Color.YELLOW,Color.WHITE};
        float[] position = {0, 1};
        Shader.TileMode tile_mode0= Shader.TileMode.REPEAT; // or TileMode.REPEAT;
        LinearGradient lin_grad0 = new LinearGradient(0, 0, 0, 200,color,position, tile_mode0);
        Shader shader_gradient0 = lin_grad0;
        gallerytxt.getPaint().setShader(shader_gradient0);*/
        ImageButton btn_back = (ImageButton) findViewById(R.id.btn_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyGallery.this.finish();
            }
        });


        mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder()
                .build();
        mAdView.loadAd(adRequest);
        gridView = (GridView) findViewById(R.id.gridView);

        new MyGalleryAsy().execute();

        gridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(MyGallery.this, ImageDetail.class);
                intent.putExtra("ImgUrl", imageFileList[pos]);

                //Toast.makeText(MyGallery.this,"image detail"+pos,Toast.LENGTH_LONG).show();
                startActivity(intent);
            }
        });


    }

    protected void onStart() {
        super.onStart();
        if (ImageDetail.deleted) {
            photo = new ArrayList<Bitmap>();
            new MyGalleryAsy().execute();
            ImageDetail.deleted = false;
        }

    }

    public class MyGalleryAsy extends AsyncTask<Void, Void, Void> {
        private ProgressDialog dialog;
        Bitmap mBitmap;

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(MyGallery.this, "", "Loading ...", true);
            dialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            readImage();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            dialog.dismiss();
            DisplayMetrics displayMatrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMatrics);
            int screenWidth = displayMatrics.widthPixels / 3;

            if (photo.size() > 0) {
                imageAdapter = new ImageAdapter(MyGallery.this, screenWidth);
                gridView.setAdapter(imageAdapter);
            }

        }

    }


    private void readImage() {
        // TODO Auto-generated method stub


        try {
            if (isSdPresent()) {
                _location = extStorageDirectory + newFolder;
            } else
                _location = getFilesDir() + newFolder;
            File file1 = new File(_location);

            if (file1.isDirectory()) { // sdCard == true
                imageFileList = file1.list();
                if (imageFileList != null) {
                    for (int i = 0; i < imageFileList.length; i++) {
                        try {
                            photo.add(BitmapFactory.decodeFile(_location + imageFileList[i].trim()));
                        } catch (Exception e) {
                            // TODO: handle exception
                            //Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show();
                        }
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    public static boolean isSdPresent() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public class ImageAdapter extends BaseAdapter {

        private Context context;
        private LayoutInflater layoutInflater;
        private int width;
        private int mGalleryItemBackground;

        public ImageAdapter(Context c) {
            context = c;

        }

        public ImageAdapter(Context c, int width) {
            context = c;
            this.width = width;
        }

        public int getCount() {
            return photo.size();
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = layoutInflater.inflate(R.layout.galleryadapter, null);

            RelativeLayout layout = (RelativeLayout) v.findViewById(R.id.galleryLayout);

            ImageView imageView = new ImageView(context);
            layout.addView(imageView, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            layout.setLayoutParams(new GridView.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
            imageView.setImageBitmap(photo.get(position));

            return v;

        }

        public void updateItemList(ArrayList<Bitmap> newItemList) {
            photo = newItemList;
            notifyDataSetChanged();
        }
    }


}

Now create its Xml Class

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
android:orientation="vertical">

<RelativeLayout
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="@color/colorPrimary"
    android:minHeight="?attr/actionBarSize">

    <TextView
        android:id="@+id/gallerytxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_gravity="center"
        android:fontFamily="@string/font_fontFamily_medium"
        android:text="My Gallery"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@android:color/black"
        android:textStyle="bold" />

    <ImageButton
        android:id="@+id/btn_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="12dp"
        android:background="@drawable/ic_arrow_back_black_24dp" />
</RelativeLayout>


<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_gravity="center|bottom"
    android:visibility="gone"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_id" />

<GridView
    android:id="@+id/gridView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/adView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/relativeLayout"
    android:horizontalSpacing="5dp"
    android:numColumns="2"
    android:smoothScrollbar="true"
    android:verticalSpacing="5dp"></GridView>
## Also Make Adapter galleryadapter.xml ##
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:id="@+id/galleryLayout"
android:padding="2dp">
[![enter image description here][1]][1]

To see the Image in Detail create a new Class ImageDetail:##

 public class ImageDetail extends Activity implements OnClickListener {
    public static InterstitialAd mInterstitialAd;
    private ImageView mainImageView;
    private LinearLayout menuTop;
    private TableLayout menuBottom;
    private Boolean onOff = true;
    private ImageView delButton, mailButton, shareButton;

    private String imgUrl = null;
    private AdView mAdView;
    TextView titletxt;
    private String newFolder = "/IslamicGif/";
    private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
    public static boolean deleted = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.image_detail);

        mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder()
                .build();
        mAdView.loadAd(adRequest);
        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                mAdView.setVisibility(View.VISIBLE);
            }
        });
        mainImageView = (ImageView) findViewById(R.id.mainImageView);
        menuTop = (LinearLayout) findViewById(R.id.menuTop);
        menuBottom = (TableLayout) findViewById(R.id.menuBottom);
        titletxt = (TextView) findViewById(R.id.titletxt);
        titletxt.setTextSize(22);
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId(getString(R.string.interstial_id));

        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                requestNewInterstitial();

            }
        });
        requestNewInterstitial();
        delButton = (ImageView) findViewById(R.id.delButton);
        mailButton = (ImageView) findViewById(R.id.mailButton);
        shareButton = (ImageView) findViewById(R.id.shareButton);

        Bundle exBundle = getIntent().getExtras();
        if (exBundle != null) {
            imgUrl = exBundle.getString("ImgUrl");
        }
        if (isSdPresent()) {
            imgUrl = extStorageDirectory + newFolder + imgUrl;
        } else
            imgUrl = getFilesDir() + newFolder + imgUrl;

        if (imgUrl != null) {
            GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(mainImageView);
            Glide.with(this).load(imgUrl).into(imageViewTarget);

        }


        delButton.setOnClickListener(this);
        mailButton.setOnClickListener(this);
        shareButton.setOnClickListener(this);


    }

    public static boolean isSdPresent() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }


    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
            case R.id.shareButton:
                Image_Link();
                break;
            case R.id.delButton:
                deleted();
                break;
            case R.id.mailButton:
                sendemail();
                break;
            default:
                break;
        }
    }

    private void sendemail() {

        try {

            File photo = new File(imgUrl);
            Uri imageuri = Uri.fromFile(photo);


            String url = Constant.AppUrl;

            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append("Face Placer App Available here..Play Link");
            int start = builder.length();
            builder.append(url);
            int end = builder.length();

            builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
            String[] recipients2 = new String[]{"[email protected]", "",};
            emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
            emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
            emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
            emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
            emailIntent2.setType("text/html");
            emailIntent2.setType("image/JPEG");
            startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));

        } catch (Exception e) {
            // TODO: handle exception

            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
        }
    }


    private void Image_Link() {

        try {

            File photo = new File(imgUrl);
            Uri imageuri = Uri.fromFile(photo);


            String url = Constant.AppUrl;

            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append("Face Placer App Available here..Play Link");
            int start = builder.length();
            builder.append(url);
            int end = builder.length();

            builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
            String[] recipients2 = new String[]{"[email protected]", "",};
            emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
            emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
            emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
            emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
            emailIntent2.setType("text/html");
            emailIntent2.putExtra(Intent.EXTRA_TEXT, "Face Placer App Available here..Play Link " + url);
            emailIntent2.setType("image/JPEG");
            startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));

        } catch (Exception e) {
            // TODO: handle exception

            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
        }
    }


    private void deleted() {
        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(ImageDetail.this);
        builder.setTitle(getString(R.string.removeoption));
        builder.setMessage(getString(R.string.deleteimage));
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                dialog.cancel();
                File fileDel = new File(imgUrl);
                boolean isCheck1 = fileDel.delete();

                if (isCheck1) {
                    deleted = true;
                    finish();
                    MyGallery.imageAdapter.notifyDataSetChanged();

                } else {
                    Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
                }
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                dialog.cancel();

            }
        });
        Dialog dialog = builder.create();
        dialog.show();


    }


    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni == null) {
            // There are no active networks.
            return false;
        } else
            return true;
    }

    private void requestNewInterstitial() {
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
                .build();

        mInterstitialAd.loadAd(adRequest);
    }

}

Create its xml image_detail.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/bg"
android:orientation="vertical">

<ImageView
    android:id="@+id/mainImageView"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentBottom="true"
    android:contentDescription="@string/app_name"
    android:focusable="true"
    android:focusableInTouchMode="true" />

<LinearLayout
    android:id="@+id/adlayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:orientation="horizontal"
    android:visibility="gone"></LinearLayout>

<LinearLayout
    android:id="@+id/menuTop"
    android:layout_width="fill_parent"
    android:layout_height="56dp"
    android:layout_alignWithParentIfMissing="true"
    android:layout_below="@+id/adlayout"
    android:background="@color/colorPrimary"
    android:orientation="vertical"
    android:padding="10.0dip"
    android:visibility="visible">

    <TextView
        android:id="@+id/titletxt"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Islamic Gifs"
        android:textColor="#000000"
        android:textSize="22sp"
        android:textStyle="bold" />
</LinearLayout>

<TableLayout
    android:id="@+id/menuBottom"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:background="@color/colorPrimary"
    android:padding="10.0dip"
    android:stretchColumns="*"
    android:visibility="visible">

    <TableRow>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal">

            <ImageView
                android:id="@+id/mailButton"
                android:layout_width="52dp"
                android:layout_height="52dp"
                android:background="@drawable/selector_shareimage"
                android:contentDescription="@string/app_name" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal">

            <ImageView
                android:id="@+id/shareButton"
                android:layout_width="52dp"
                android:layout_height="52dp"
                android:background="@drawable/selector_shareimage_small"
                android:contentDescription="@string/app_name" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal">

            <ImageView
                android:id="@+id/delButton"
                android:layout_width="52dp"
                android:layout_height="52dp"
                android:background="@drawable/selector_delete"
                android:contentDescription="@string/app_name" />
        </LinearLayout>
    </TableRow>
</TableLayout>

<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/menuTop"
    android:layout_centerHorizontal="true"
    android:visibility="gone"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_id"></com.google.android.gms.ads.AdView>

Add your own Drawable to Selector class,and create it res>drawable>selector_shareimage.xml

<?xml version="1.0" encoding="utf-8"?>
<item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_pressed="true"/>
<item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_focused="true"/>
<item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_selected="true"/>
<item android:drawable="@drawable/result_bt_mail_s"/>

enter image description here

Dont forget to add in application tag for sdk version 29 and 30 legacy to add this line

android:requestLegacyExternalStorage="true"

 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:requestLegacyExternalStorage="true"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

Visual Studio can't build due to rc.exe

In my case the error was due to a bad setting in a vcxproj. The vcxproj was from a third party, so I'm not sure how it got in that state.

Specifically, for one of the platform/profile combos, the platform folder was missing from the Windows SDK bin folder:

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
 <ExecutablePath>$(VCInstallDir)bin\x86_amd64;$(VCInstallDir)bin;$(WindowsSdkDir)bin\NETFX 4.0 Tools;$(WindowsSdkDir)bin\x86;

is correct, where

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
 <ExecutablePath>$(VCInstallDir)bin\x86_amd64;$(VCInstallDir)bin;$(WindowsSdkDir)bin\NETFX 4.0 Tools;$(WindowsSdkDir)bin;

was incorrect. Might need to scroll to the end of the code boxes to see the difference.

Note also, that for some strange reason $(WindowsSdkDir)bin\x64; did NOT work for me. Tried to figure out why, when rc.exe definitely exists in that folder, but I gave up.

In my opinion, the solutions from previous posters that involve copying rc.exe all over the place are wrong, because your project will not work on anyone else's machine. If you fix up the paths in the project correctly, it should work on any machine with a correct installation of the Windows SDK.

Convert a Python list with strings all to lowercase or uppercase

You could try using:

my_list = ['india', 'america', 'china', 'korea']

def capitalize_list(item):
    return item.upper()

print(list(map(capitalize_list, my_list)))

Python not working in the command line of git bash

I am using MINGW64 via Visual Studio Code on Windows 10 and trying to install node-sass (which requires python2). I followed felixrieseberg/windows-build-tools #56 on Github which solved my issue.

This is a special case, but I'm posting in case someone has the same problem:

npm --add-python-to-path='true' --debug install --global windows-build-tools

This installs python and other required build tools to %USERPROFILE%\.windows-build-tools\python27.

Do while loop in SQL Server 2008

If you are not very offended by the GOTO keyword, it can be used to simulate a DO / WHILE in T-SQL. Consider the following rather nonsensical example written in pseudocode:

SET I=1
DO
 PRINT I
 SET I=I+1
WHILE I<=10

Here is the equivalent T-SQL code using goto:

DECLARE @I INT=1;
START:                -- DO
  PRINT @I;
  SET @I+=1;
IF @I<=10 GOTO START; -- WHILE @I<=10

Notice the one to one mapping between the GOTO enabled solution and the original DO / WHILE pseudocode. A similar implementation using a WHILE loop would look like:

DECLARE @I INT=1;
WHILE (1=1)              -- DO
 BEGIN
  PRINT @I;
  SET @I+=1;
  IF NOT (@I<=10) BREAK; -- WHILE @I<=10
 END

Now, you could of course rewrite this particular example as a simple WHILE loop, since this is not such a good candidate for a DO / WHILE construct. The emphasis was on example brevity rather than applicability, since legitimate cases requiring a DO / WHILE are rare.


REPEAT / UNTIL, anyone (does NOT work in T-SQL)?

SET I=1
REPEAT
  PRINT I
  SET I=I+1
UNTIL I>10

... and the GOTO based solution in T-SQL:

DECLARE @I INT=1;
START:                    -- REPEAT
  PRINT @I;
  SET @I+=1;
IF NOT(@I>10) GOTO START; -- UNTIL @I>10

Through creative use of GOTO and logic inversion via the NOT keyword, there is a very close relationship between the original pseudocode and the GOTO based solution. A similar solution using a WHILE loop looks like:

DECLARE @I INT=1;
WHILE (1=1)       -- REPEAT
 BEGIN
  PRINT @I;
  SET @I+=1;
  IF @I>10 BREAK; -- UNTIL @I>10
 END

An argument can be made that for the case of the REPEAT / UNTIL, the WHILE based solution is simpler, because the if condition is not inverted. On the other hand it is also more verbose.

If it wasn't for all of the disdain around the use of GOTO, these might even be idiomatic solutions for those few times when these particular (evil) looping constructs are necessary in T-SQL code for the sake of clarity.

Use these at your own discretion, trying not to suffer the wrath of your fellow developers when they catch you using the much maligned GOTO.

How to URL encode in Python 3?

You misread the documentation. You need to do two things:

  1. Quote each key and value from your dictionary, and
  2. Encode those into a URL

Luckily urllib.parse.urlencode does both those things in a single step, and that's the function you should be using.

from urllib.parse import urlencode, quote_plus

payload = {'username':'administrator', 'password':'xyz'}
result = urlencode(payload, quote_via=quote_plus)
# 'password=xyz&username=administrator'

Bind service to activity in Android

There is a method called unbindService that will take a ServiceConnection which you will have created upon calling bindService. This will allow you to disconnect from the service while still leaving it running.

This may pose a problem when you connect to it again, since you probably don't know whether it's running or not when you start the activity again, so you'll have to consider that in your activity code.

Good luck!

Is there a way to get colored text in GitHubflavored Markdown?

You cannot include style directives in GFM.

The most complete documentation/example is "Markdown Cheatsheet", and it illustrates that this element <style> is missing.

If you manage to include your text in one of the GFM elements, then you can play with a github.css stylesheet in order to colors that way, meaning to color using inline CSS style directives, referring to said css stylesheet.

Bash write to file without echo?

I had the problem not being able to send ">" and ended up with echo!

echo "Hello world" | dd of=test.txt

How to split a comma-separated string?

This is an easy way to split string by comma,

import java.util.*;

public class SeparatedByComma{
public static void main(String []args){
     String listOfStates = "Hasalak, Mahiyanganaya, Dambarawa, Colombo";
     List<String> stateList = Arrays.asList(listOfStates.split("\\,"));
     System.out.println(stateList);
 }
}

How to resize a custom view programmatically?

I solved it this way.. I have basically a simple view inside xml file.

 View viewname = findViewById(R.id.prod_extra);
             prodExtra.getLayoutParams().height=64;

What is Type-safe?

Type-Safe is code that accesses only the memory locations it is authorized to access, and only in well-defined, allowable ways. Type-safe code cannot perform an operation on an object that is invalid for that object. The C# and VB.NET language compilers always produce type-safe code, which is verified to be type-safe during JIT compilation.

How to empty/destroy a session in rails?

add this code to your ApplicationController

def reset_session
  @_request.reset_session
end

( Dont know why no one above just mention this code as it fixed my problem ) http://apidock.com/rails/ActionController/RackDelegation/reset_session

Passing command line arguments to R CMD BATCH

I add an answer because I think a one line solution is always good! Atop of your myRscript.R file, add the following line:

eval(parse(text=paste(commandArgs(trailingOnly = TRUE), collapse=";")))

Then submit your script with something like:

R CMD BATCH [options] '--args arguments you want to supply' myRscript.R &

For example:

R CMD BATCH --vanilla '--args N=1 l=list(a=2, b="test") name="aname"' myscript.R &

Then:

> ls()
[1] "N"    "l"    "name"

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

There are two reasons for this error

1) In the array of import if you imported HttpModule twice

enter image description here

2) If you haven't import:

import { HttpModule, JsonpModule } from '@angular/http'; 

If you want then run:

npm install @angular/http

Pointers in C: when to use the ampersand and the asterisk?

Ok, looks like your post got editted...

double foo[4];
double *bar_1 = &foo[0];

See how you can use the & to get the address of the beginning of the array structure? The following

Foo_1(double *bar, int size){ return bar[size-1]; }
Foo_2(double bar[], int size){ return bar[size-1]; }

will do the same thing.

Is it possible to put CSS @media rules inline?

yes,you can do with javascript by the window.matchMedia

  1. desktop for red colour text

  2. tablet for green colour text

  3. mobile for blue colour text

_x000D_
_x000D_
//isat_style_media_query_for_desktop_mobile_tablets_x000D_
var tablets = window.matchMedia("(max-width:  768px)");//for tablet devices_x000D_
var mobiles = window.matchMedia("(max-width: 480px)");//for mobile devices_x000D_
var desktops = window.matchMedia("(min-width: 992px)");//for desktop devices_x000D_
_x000D_
_x000D_
_x000D_
isat_find_device_tablets(tablets);//apply style for tablets_x000D_
isat_find_device_mobile(mobiles);//apply style for mobiles_x000D_
isat_find_device_desktops(desktops);//apply style for desktops_x000D_
// isat_find_device_desktops(desktops,tablets,mobiles);// Call listener function at run time_x000D_
tablets.addListener(isat_find_device_tablets);//listen untill detect tablet screen size_x000D_
desktops.addListener(isat_find_device_desktops);//listen untill detect desktop screen size_x000D_
mobiles.addListener(isat_find_device_mobile);//listen untill detect mobile devices_x000D_
// desktops.addListener(isat_find_device_desktops);_x000D_
_x000D_
 // Attach listener function on state changes_x000D_
_x000D_
function isat_find_device_mobile(mob)_x000D_
{_x000D_
  _x000D_
// isat mobile style here_x000D_
var daynight=document.getElementById("daynight");_x000D_
daynight.style.color="blue";_x000D_
_x000D_
// isat mobile style here_x000D_
_x000D_
}_x000D_
_x000D_
function isat_find_device_desktops(des)_x000D_
{_x000D_
_x000D_
// isat mobile style here_x000D_
_x000D_
var daynight=document.getElementById("daynight");_x000D_
daynight.style.color="red";_x000D_
 _x000D_
//  isat mobile style here_x000D_
}_x000D_
_x000D_
function isat_find_device_tablets(tab)_x000D_
{_x000D_
_x000D_
// isat mobile style here_x000D_
var daynight=document.getElementById("daynight");_x000D_
daynight.style.color="green";_x000D_
_x000D_
//  isat mobile style here_x000D_
}_x000D_
_x000D_
_x000D_
//isat_style_media_query_for_desktop_mobile_tablets
_x000D_
    <div id="daynight">tricky style for mobile,desktop and tablet</div>
_x000D_
_x000D_
_x000D_

What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

No events get triggered when the element is having disabled attribute.

None of the below will get triggered.

$("[disabled]").click( function(){ console.log("clicked") });//No Impact
$("[disabled]").hover( function(){ console.log("hovered") });//No Impact
$("[disabled]").dblclick( function(){ console.log("double clicked") });//No Impact

While readonly will be triggered.

$("[readonly]").click( function(){ console.log("clicked") });//log - clicked
$("[readonly]").hover( function(){ console.log("hovered") });//log - hovered
$("[readonly]").dblclick( function(){ console.log("double clicked") });//log - double clicked

How to stash my previous commit?

If you've not pushed either commit to your remote repository, you could use interactive rebasing to 'reorder' your commits and stash the (new) most recent commit's changes only.

Assuming you have the tip of your current branch (commit 111 in your example) checked out, execute the following:

git rebase -i HEAD~2

This will open your default editor, listing most recent 2 commits and provide you with some instructions. Be very cautious as to what you do here, as you are going to effectively 'rewrite' the history of your repository, and can potentially lose work if you aren't careful (make a backup of the whole repository first if necessary). I've estimated commit hashes/titles below for example

pick 222 commit to be stashed
pick 111 commit to be pushed to remote

# Rebase 111..222 onto 333
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

Reorder the two commits (they are listed oldest => newest) like this:

pick 111 commit to be pushed to remote
pick 222 commit to be stashed

Save and exit, at which point git will do some processing to rewrite the two commits you have changed. Assuming no issues, you should have reversed the order of your two changesets. This can be confirmed with git log --oneline -5 which will output newest-first.

At this point, you can simply do a soft-reset on the most recent commit, and stash your working changes:

git reset --soft HEAD~1
git stash

It's important to mention that this option is only really viable if you have not previously pushed any of these changes to your remote, otherwise it can cause issues for everyone using the repository.

Setting the MySQL root user password on OS X

mysqld_safe --skip-grant-tables
mysql -u root
UPDATE mysql.user SET authentication_string='yourpasswd' WHERE User='root';
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'yourpasswd';

I somehow need to do this every time my Macbook restarts. Posting this for personal reference, hopefully it helps someone else as well.

error: This is probably not a problem with npm. There is likely additional logging output above

I already have the same problem . and I fix it using npm update & npm cache clean --force

hibernate: LazyInitializationException: could not initialize proxy

This generally means that the owning Hibernate session has already closed. You can do one of the following to fix it:

  1. whichever object creating this problem, use HibernateTemplate.initialize(object name)
  2. Use lazy=false in your hbm files.

How to stop process from .BAT file?

To terminate a process you know the name of, try:

taskkill /IM notepad.exe

This will ask it to close, but it may refuse, offer to "save changes", etc. If you want to forcibly kill it, try:

taskkill /F /IM notepad.exe

How to center a navigation bar with CSS or HTML?

You could also use float and inline-block to center your nav like the following:

nav li {
   float: left;
}
nav {
   display: inline-block;
}

JSchException: Algorithm negotiation fail

FWIW, I had this same error message under JSch 0.1.50. Upgrading to 0.1.52 solved the problem.

How to cancel a pull request on github?

Super EASY way to close a Pull Request - LATEST!

  1. Navigate to the Original Repository where the pull request has been submitted to.
  2. Select the Pull requests tab
  3. Select your pull request that you wish to remove. This will open it up.
  4. Towards the bottom, just enter a valid comment for closure and press Close Pull Request button

enter image description here

How do I set a JLabel's background color?

For the Background, make sure you have imported java.awt.Color into your package.

In your main method, i.e. public static void main(String[] args), call the already imported method:

JLabel name_of_your_label=new JLabel("the title of your label");
name_of_your_label.setBackground(Color.the_color_you_wish);
name_of_your_label.setOpaque(true);

NB: Setting opaque will affect its visibility. Remember the case sensitivity in Java.

Unfinished Stubbing Detected in Mockito

For those who use com.nhaarman.mockitokotlin2.mock {}

This error occurs when, for example, we create a mock inside another mock

mock {
    on { x() } doReturn mock {
        on { y() } doReturn z()
    }
}

The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.

val liveDataMock = mock {
        on { y() } doReturn z()
}
mock {
    on { x() } doReturn liveDataMock
}

GL

How to convert List<string> to List<int>?

Convert string value into integer list

var myString = "010"; 
int myInt;
List<int> B = myString.ToCharArray().Where(x => int.TryParse(x.ToString(), out myInt)).Select(x => int.Parse(x.ToString())).ToList();

Get my phone number in android

As Answered here

Use below code :

TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

In AndroidManifest.xml, give the following permission:

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

But remember, this code does not always work, since Cell phone number is dependent on the SIM Card and the Network operator / Cell phone carrier.

Also, try checking in Phone--> Settings --> About --> Phone Identity, If you are able to view the Number there, the probability of getting the phone number from above code is higher. If you are not able to view the phone number in the settings, then you won't be able to get via this code!

Suggested Workaround:

  1. Get the user's phone number as manual input from the user.
  2. Send a code to the user's mobile number via SMS.
  3. Ask user to enter the code to confirm the phone number.
  4. Save the number in sharedpreference.

Do the above 4 steps as one time activity during the app's first launch. Later on, whenever phone number is required, use the value available in shared preference.

How can I get the SQL of a PreparedStatement?

To do this you need a JDBC Connection and/or driver that supports logging the sql at a low level.

Take a look at log4jdbc

How to outline text in HTML / CSS

from: Outline effect to text

.strokeme
{
    color: white;
    text-shadow:
    -1px -1px 0 #000,
    1px -1px 0 #000,
    -1px 1px 0 #000,
    1px 1px 0 #000;  
}

How do I print the full value of a long string in gdb?

As long as your program's in a sane state, you can also call (void)puts(your_string) to print it to stdout. Same principle applies to all functions available to the debugger, actually.

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

The most likely reason why the Java Runtime Environment JRE or Java Development Kit JDK is that it's owned by Oracle not Google and they would need a redistribution agreement which if you know there is some history between the two companies.

Lucky for us that Sun Microsystems before it was bought by Oracle open sourced Java and MySQL a win for us little guys.... Thank you Sun!

Google should probably have a caveat saying you may also need JRE OR JDK

How do I mock an autowired @Value field in Spring with Mockito?

You can also mock your property configuration into your test class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:test-context.xml" })
public class MyTest 
{ 
   @Configuration
   public static class MockConfig{
       @Bean
       public Properties myProps(){
             Properties properties = new Properties();
             properties.setProperty("default.url", "myUrl");
             properties.setProperty("property.value2", "value2");
             return properties;
        }
   }
   @Value("#{myProps['default.url']}")
   private String defaultUrl;

   @Test
   public void testValue(){
       Assert.assertEquals("myUrl", defaultUrl);
   }
}

npm install gives error "can't find a package.json file"

You don't say what module you want to install - hence npm looks for a file package.json which describes your dependencies, and obviously this file is missing.

So either you have to explicitly tell npm which module to install, e.g.

npm install express

or

npm install -g express-generator

or you have to add a package.json file and register your modules here. The easiest way to get such a file is to let npm create one by running

npm init

and then add what you need. Please note that this does only work for locally installed modules, not for global ones.

A simple example might look like this:

{
  "name": "myapp",
  "version": "0.0.1",
  "dependencies": {
    "express": "4.0.0"
  }
}

or something like that. For more info on the package.json file see its official documentation and this interactive guide.

How to set a value of a variable inside a template code?

Use the with statement.

{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

I can't imply the code in first paragraph in this answer. Maybe the template language had deprecated the old format.

How do I disable right click on my web page?

 $(document).ready(function () {
            document.oncontextmenu = document.body.oncontextmenu = function () { return false; }
        });