Programs & Examples On #Single instance

How do I open multiple instances of Visual Studio Code?

You can also create a shortcut with an empty filename

"%LOCALAPPDATA%\Local\Code\Code.exe" ""

How to force C# .net app to run only one instance in Windows?

another way to single instance an application is to check their hash sums. after messing around with mutex (didn't work as i want) i got it working this way:

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd);

    public Main()
    {
        InitializeComponent();

        Process current = Process.GetCurrentProcess();
        string currentmd5 = md5hash(current.MainModule.FileName);
        Process[] processlist = Process.GetProcesses();
        foreach (Process process in processlist)
        {
            if (process.Id != current.Id)
            {
                try
                {
                    if (currentmd5 == md5hash(process.MainModule.FileName))
                    {
                        SetForegroundWindow(process.MainWindowHandle);
                        Environment.Exit(0);
                    }
                }
                catch (/* your exception */) { /* your exception goes here */ }
            }
        }
    }

    private string md5hash(string file)
    {
        string check;
        using (FileStream FileCheck = File.OpenRead(file))
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] md5Hash = md5.ComputeHash(FileCheck);
            check = BitConverter.ToString(md5Hash).Replace("-", "").ToLower();
        }

        return check;
    }

it checks only md5 sums by process id.

if an instance of this application was found, it focuses the running application and exit itself.

you can rename it or do what you want with your file. it wont open twice if the md5 hash is the same.

may someone has suggestions to it? i know it is answered, but maybe someone is looking for a mutex alternative.

What is the correct way to create a single-instance WPF application?

It looks like there is a really good way to handle this:

WPF Single Instance Application

This provides a class you can add that manages all the mutex and messaging cruff to simplify the your implementation to the point where it's simply trivial.

How to add screenshot to READMEs in github repository?

The markdown syntax for displaying images is indeed:

![image](https://{url})

BUT: How to provide the url ?

  • You probably do not want to clutter your repo with screenshots, they have nothing to do with code
  • you might not want either to deal with the hassle of making your image available on the web... (upload it to a server... ).

So... you can use this awesome trick to make github host your image file. TDLR:

  1. create an issue on the issue list of your repo
  2. drag and drop your screenshot on this issue
  3. copy the markdown code that github has just created for you to display your image
  4. paste it on your readme (or wherever you want)

http://solutionoptimist.com/2013/12/28/awesome-github-tricks/

Handling NULL values in Hive

To check for the NULL data for column1 and consider your datatype of it is String, you could use below command :

select * from tbl_name where column1 is null or column1 <> '';

Convert NSNumber to int in Objective-C

A less verbose approach:

int number = [dict[@"integer"] intValue];

Does hosts file exist on the iPhone? How to change it?

In case anybody else falls onto this page, you can also solve this by using the Ip address in the URL request instead of the domain:

NSURL *myURL = [NSURL URLWithString:@"http://10.0.0.2/mypage.php"];

Then you specify the Host manually:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL];
[request setAllHTTPHeaderFields:[NSDictionary dictionaryWithObjectAndKeys:@"myserver",@"Host"]];

As far as the server is concerned, it will behave the exact same way as if you had used http://myserver/mypage.php, except that the iPhone will not have to do a DNS lookup.

100% Public API.

Two way sync with rsync

Try this,

get-music:
 rsync -avzru --delete-excluded server:/media/10001/music/ /media/Incoming/music/

put-music:
 rsync -avzru --delete-excluded /media/Incoming/music/ server:/media/10001/music/

sync-music: get-music put-music

I just test this and it worked for me. I'm doing a 2-way sync between Windows7 (using cygwin with the rsync package installed) and FreeNAS fileserver (FreeNAS runs on FreeBSD with rsync package pre-installed).

Is there a way I can retrieve sa password in sql server 2005

There is no way to get the old password back. Log into the SQL server management console as a machine or domain admin using integrated authentication, you can then change any password (including sa).

Start the SQL service again and use the new created login (recovery in my example) Go via the security panel to the properties and change the password of the SA account.

enter image description here

Now write down the new SA password.

Convert NSDate to NSString

If you don't have NSDate -descriptionWithCalendarFormat:timeZone:locale: available (I don't believe iPhone/Cocoa Touch includes this) you may need to use strftime and monkey around with some C-style strings. You can get the UNIX timestamp from an NSDate using NSDate -timeIntervalSince1970.

error: ORA-65096: invalid common user or role name in oracle

In Oracle 12c and above, we have two types of databases:

  1. Container DataBase (CDB), and
  2. Pluggable DataBase (PDB).

If you want to create an user, you have two possibilities:

  1. You can create a "container user" aka "common user".
    Common users belong to CBDs as well as to current and future PDBs. It means they can perform operations in Container DBs or Pluggable DBs according to assigned privileges.

    create user c##username identified by password;

  2. You can create a "pluggable user" aka "local user".
    Local users belong only to a single PDB. These users may be given administrative privileges, but only for that PDB inside which they exist. For that, you should connect to pluggable datable like that:

    alter session set container = nameofyourpluggabledatabase;

    and there, you can create user like usually:

    create user username identified by password;

Don't forget to specify the tablespace(s) to use, it can be useful during import/export of your DBs. See this for more information about it https://docs.oracle.com/database/121/SQLRF/statements_8003.htm#SQLRF01503

Media Player called in state 0, error (-38,0)

I have change setAudioStreamType to setAudioAttributes;

mediaPlayer.setAudioAttributes(AudioAttributes.Builder()
                .setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
                .setLegacyStreamType(AudioManager.STREAM_ALARM)
                .setUsage(AudioAttributes.USAGE_ALARM)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build());

What does random.sample() method in python do?

random.sample() also works on text

example:

> text = open("textfile.txt").read() 

> random.sample(text, 5)

> ['f', 's', 'y', 'v', '\n']

\n is also seen as a character so that can also be returned

you could use random.sample() to return random words from a text file if you first use the split method

example:

> words = text.split()

> random.sample(words, 5)

> ['the', 'and', 'a', 'her', 'of']

What is the '.well' equivalent class in Bootstrap 4

Card seems to be "discarded" LOL, I found the "well" not working with bootstrap 4.3.1 and jQuery v3.4.1, just working fine with bootstrap 4.3.1 and jQuery v3.3.1. Hope it helps.

JavaScript/regex: Remove text between parentheses

var str = "Hello, this is Mike (example)";

alert(str.replace(/\s*\(.*?\)\s*/g, ''));

That'll also replace excess whitespace before and after the parentheses.

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Replace the dependency in the POM.xml file

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.2.3</version>
</dependency>

By the dependency

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
    </dependency>

Turning off hibernate logging console output

There are several parts of hibernate logging you can control based on the logger hierarchy of the hibernate package (more on logger hierarchy here).

    <!-- Log everything in hibernate -->
    <Logger name="org.hibernate" level="info" additivity="false">
      <AppenderRef ref="Console" />
    </Logger>

    <!-- Log SQL statements -->
    <Logger name="org.hibernate.SQL" level="debug" additivity="false">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />
    </Logger>

    <!-- Log JDBC bind parameters -->
    <Logger name="org.hibernate.type.descriptor.sql" level="trace" additivity="false">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />
    </Logger>

The above was taken from here.

Additionally you could have the property show-sql:true in your configuration file since that supersedes the logging framework settings. More on that here.

How can I remove space (margin) above HTML header?

I solved the space issue by adding a border and removing is by setting a negative margin. Do not know what the underlying problem is though.

header {
  border-top: 1px solid gold !important;
  margin-top: -1px !important;
}

printf and long double

printf and scanf function in C/C++ uses Microsoft C library and this library has no support for 10 byte long double. So when you are using printf and scanf function in your C/C++ code to print a long double as output and to take some input as a long double, it will always give you wrong result.

If you want to use long double then you have to use " __mingw_printf " and " __mingw_scanf " function instead of printf and scanf. It has support for 10 byte long double.

Or you can define two macro like this : " #define printf __mingw_printf " and " #define scanf __mingw_scanf "

Use standard format for long double : %Lf

determine DB2 text string length

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

Add target="_blank" in CSS

This is actually javascript but related/relevant because .querySelectorAll targets by CSS syntax:

var i_will_target_self = document.querySelectorAll("ul.menu li a#example")

this example uses css to target links in a menu with id = "example"

that creates a variable which is a collection of the elements we want to change, but we still have actually change them by setting the new target ("_blank"):

for (var i = 0; i < 5; i++) {
i_will_target_self[i].target = "_blank";
}

That code assumes that there are 5 or less elements. That can be changed easily by changing the phrase "i < 5."

read more here: http://xahlee.info/js/js_get_elements.html

pandas: find percentile stats of a given column

You can even give multiple columns with null values and get multiple quantile values (I use 95 percentile for outlier treatment)

my_df[['field_A','field_B']].dropna().quantile([0.0, .5, .90, .95])

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

Maybe a little late to reply. I happen to run into the same problem today. I find that on Windows you can change the console encoder to utf-8 or other encoder that can represent your data. Then you can print it to sys.stdout.

First, run following code in the console:

chcp 65001
set PYTHONIOENCODING=utf-8

Then, start python do anything you want.

Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./

// The string must contain at least one special character, escaping reserved RegEx characters to avoid conflict
  const hasSpecial = password => {
    const specialReg = new RegExp(
      '^(?=.*[!@#$%^&*"\\[\\]\\{\\}<>/\\(\\)=\\\\\\-_´+`~\\:;,\\.€\\|])',
    );
    return specialReg.test(password);
  };

get all the elements of a particular form

Try this to get all the form fields.

var fields = document['formName'].elements;

Limiting double to 3 decimal places

Doubles don't have decimal places - they're not based on decimal digits to start with. You could get "the closest double to the current value when truncated to three decimal digits", but it still wouldn't be exactly the same. You'd be better off using decimal.

Having said that, if it's only the way that rounding happens that's a problem, you can use Math.Truncate(value * 1000) / 1000; which may do what you want. (You don't want rounding at all, by the sounds of it.) It's still potentially "dodgy" though, as the result still won't really just have three decimal places. If you did the same thing with a decimal value, however, it would work:

decimal m = 12.878999m;
m = Math.Truncate(m * 1000m) / 1000m;
Console.WriteLine(m); // 12.878

EDIT: As LBushkin pointed out, you should be clear between truncating for display purposes (which can usually be done in a format specifier) and truncating for further calculations (in which case the above should work).

Make new column in Panda dataframe by adding values from other columns

The simplest way would be to use DeepSpace answer. However, if you really want to use an anonymous function you can use apply:

df['C'] = df.apply(lambda row: row['A'] + row['B'], axis=1)

Genymotion error at start 'Unable to load virtualbox'

Open Genymotion in Windows as an administrator. My Genymotion works only in this mode

Removing body margin in CSS

Just Remove The Browser Default Margin and Padding Apply Top Of Your Css.

<style>

* {
  margin: 0;
  padding: 0;
}

</style>

NOTE:

  • Try to Reset all the html elements before writing your css.

OR [ Use This In Your Case ]

<style>

  *{
        margin: 0px;
        padding: 0px;
    }

h1 {
        margin-top: 0px;
    }

</style>

DEMO:

_x000D_
_x000D_
<style>_x000D_
_x000D_
  *{_x000D_
        margin: 0px;_x000D_
        padding: 0px;_x000D_
    }_x000D_
_x000D_
h1 {_x000D_
        margin-top: 0px;_x000D_
    }_x000D_
_x000D_
</style>
_x000D_
<html>_x000D_
 <head>_x000D_
 </head>_x000D_
 <body>_x000D_
  <h1>logo</h1>_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Access Control Request Headers, is added to header in AJAX request with jQuery

From client side, I cant solve this problem. From nodejs express side, you can use cors module to handle it.

var express       = require('express');
var app           = express();
var bodyParser = require('body-parser');
var cors = require('cors');

var port = 3000; 
var ip = '127.0.0.1';

app.use('*/myapi', 
          cors(), // with this row OPTIONS has handled
          bodyParser.text({type:'text/*'}),
          function( req, res, next ){
    console.log( '\n.----------------' + req.method + '------------------------' );
        console.log( '| prot:'+req.protocol );
        console.log( '| host:'+req.get('host') );
        console.log( '| url:'+req.originalUrl );
        console.log( '| body:',req.body );
        //console.log( '| req:',req );
    console.log( '.----------------' + req.method + '------------------------' );
    next();
    });

app.listen(port, ip, function() {
    console.log('Listening to port:  ' + port );
});
 
console.log(('dir:'+__dirname ));
console.log('The server is up and running at http://'+ip+':'+port+'/');

Without cors() this OPTIONS has appears before POST.

.----------------OPTIONS------------------------
| prot:http
| host:localhost:3000
| url:/myapi
| body: {}
.----------------OPTIONS------------------------

.----------------POST------------------------
| prot:http
| host:localhost:3000
| url:/myapi
| body: <SOAP-ENV:Envelope .. P-ENV:Envelope>
.----------------POST------------------------

The ajax call:

$.ajax({
    type: 'POST',
    contentType: "text/xml; charset=utf-8",
// these does not works
    //beforeSend: function(request) { 
    //  request.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
    //  request.setRequestHeader('Accept', 'application/vnd.realtime247.sct-giro-v1+cms');
    //  request.setRequestHeader('Access-Control-Allow-Origin', '*');
    //  request.setRequestHeader('Access-Control-Allow-Methods', 'POST, GET');
    //  request.setRequestHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type');
    //},
    //headers: {
    //  'Content-Type': 'text/xml; charset=utf-8',
    //  'Accept': 'application/vnd.realtime247.sct-giro-v1+cms',
    //  'Access-Control-Allow-Origin': '*',
    //  'Access-Control-Allow-Methods': 'POST, GET',
    //  'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type'
    //},
    url: 'http://localhost:3000/myapi',             
    data:       '<SOAP-ENV:Envelope .. P-ENV:Envelope>',                
    success: function( data ) {
      console.log(data.documentElement.innerHTML);
    },
    error: function(jqXHR, textStatus, err) {
      console.log( jqXHR,'\n', textStatus,'\n', err )
    }
  });

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

If you are using cPanel you should just click the wee box that allows you to send to external servers by SMTP.

Login to CPanel > Tweak Settings > All> "Restrict outgoing SMTP to root, exim, and mailman (FKA SMTP Tweak)"

As answered here:

"Password not accepted from server: 535 Incorrect authentication data" when sending with GMail and phpMailer

Parse query string into an array

For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra "e"—in the URL the function will silently fail without an error or exception being thrown:

a=2&b=2&c=5&d=4&e=1&e=2&e=3 

So I prefer using my own parser like so:

//$_SERVER['QUERY_STRING'] = `a=2&b=2&c=5&d=4&e=100&e=200&e=300` 

$url_qry_str  = explode('&', $_SERVER['QUERY_STRING']);

//arrays that will hold the values from the url
$a_arr = $b_arr = $c_arr = $d_arr = $e_arr =  array();

foreach( $url_qry_str as $param )
    {
      $var =  explode('=', $param, 2);
      if($var[0]=="a")      $a_arr[]=$var[1];
      if($var[0]=="b")      $b_arr[]=$var[1];
      if($var[0]=="c")      $c_arr[]=$var[1];
      if($var[0]=="d")      $d_arr[]=$var[1];
      if($var[0]=="e")      $e_arr[]=$var[1];
    }

    var_dump($e_arr); 
    // will return :
    //array(3) { [0]=> string(1) "100" [1]=> string(1) "200" [2]=> string(1) "300" } 

Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.

Hope that helps!

JSON and XML comparison

The XML (extensible Markup Language) is used often XHR because this is a standard broadcasting language, what can be used by any programming language, and supported both server and client side, so this is the most flexible solution. The XML can be separated for more parts so a specified group can develop the part of the program, without affecting the other parts. The XML format can also be determined by the XML DTD or XML Schema (XSL) and can be tested.

The JSON a data-exchange format which is getting more popular as the JavaScript applications possible format. Basically this is an object notation array. JSON has a very simple syntax so can be easily learned. And also the JavaScript support parsing JSON with the eval function. On the other hand, the eval function has got negatives. For example, the program can be very slow parsing JSON and because of security the eval can be very risky. This not mean that the JSON is not good, just we have to be more careful.

My suggestion is that you should use JSON for applications with light data-exchange, like games. Because you don't have to really care about the data-processing, this is very simple and fast.

The XML is best for the bigger websites, for example shopping sites or something like this. The XML can be more secure and clear. You can create basic data-struct and schema to easily test the correction and separate it into parts easily.

I suggest you use XML because of the speed and the security, but JSON for lightweight stuff.

Material effect on button with background color

Here is a simple and backward compatible way to deliver ripple effect to raised buttons with the custom background.

Your layout should look like this

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/my_custom_background"
    android:foreground="?android:attr/selectableItemBackground"/>

Converting ArrayList to Array in java

This is the right answer you want and this solution i have run my self on netbeans

ArrayList a=new ArrayList();
a.add(1);
a.add(3);
a.add(4);
a.add(5);
a.add(8);
a.add(12);

int b[]= new int [6];
        Integer m[] = new Integer[a.size()];//***Very important conversion to array*****
        m=(Integer[]) a.toArray(m);
for(int i=0;i<a.size();i++)
{
    b[i]=m[i]; 
    System.out.println(b[i]);
}   
    System.out.println(a.size());

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

Lets assume you created a Ubuntu VM on your local machine. It's IP address is 192.168.1.104.

You login into VM, and installed Kubernetes. Then you created a pod where nginx image running on it.

1- If you want to access this nginx pod inside your VM, you will create a ClusterIP bound to that pod for example:

$ kubectl expose deployment nginxapp --name=nginxclusterip --port=80 --target-port=8080

Then on your browser you can type ip address of nginxclusterip with port 80, like:

http://10.152.183.2:80

2- If you want to access this nginx pod from your host machine, you will need to expose your deployment with NodePort. For example:

$ kubectl expose deployment nginxapp --name=nginxnodeport --port=80 --target-port=8080 --type=NodePort

Now from your host machine you can access to nginx like:

http://192.168.1.104:31865/

In my dashboard they appear as:

enter image description here

Below is a diagram shows basic relationship.

enter image description here

Android - drawable with rounded corners at the top only

You may need read this https://developer.android.com/guide/topics/resources/drawable-resource.html#Shape

and below there is a Note.

Note Every corner must (initially) be provided a corner radius greater than 1, or else no corners are rounded. If you want specific corners to not be rounded, a work-around is to use android:radius to set a default corner radius greater than 1, but then override each and every corner with the values you really want, providing zero ("0dp") where you don't want rounded corners.

Regular expression to detect semi-colon terminated C++ for & while loops

This is the kind of thing you really shouldn't do with a regular expression. Just parse the string one character at a time, keeping track of opening/closing parentheses.

If this is all you're looking for, you definitely don't need a full-blown C++ grammar lexer/parser. If you want practice, you can write a little recursive-decent parser, but even that's a bit much for just matching parentheses.

Make the first character Uppercase in CSS

<script type="text/javascript">
     $(document).ready(function() {
     var asdf = $('.capsf').text();

    $('.capsf').text(asdf.toLowerCase());
     });
     </script>
<div style="text-transform: capitalize;"  class="capsf">sd GJHGJ GJHgjh gh hghhjk ku</div>

How to close TCP and UDP ports via windows command line

In order to close the port you could identify the process that is listening on this port and kill this process.

How to change the datetime format in pandas

You can use dt.strftime if you need to convert datetime to other formats (but note that then dtype of column will be object (string)):

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '26/1/2016'}})
print (df)
         DOB
0  26/1/2016 
1  26/1/2016

df['DOB'] = pd.to_datetime(df.DOB)
print (df)
         DOB
0 2016-01-26
1 2016-01-26

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print (df)
         DOB        DOB1
0 2016-01-26  01/26/2016
1 2016-01-26  01/26/2016

ASP.net vs PHP (What to choose)

This is impossible to answer and has been brought up many many times before. Do a search, read those threads, then pick the framework you and your team have experience with.

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

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

Happy coding..

Passing Javascript variable to <a href >

put id attribute on anchor element

<a id="link2">

set href attribute on page load event:

(function() {
    var scrt_var = 10;
    var strLink = "2.html&Key=" + scrt_var;
    document.getElementById("link2").setAttribute("href",strLink);
})();

How to convert a Scikit-learn dataset to a Pandas dataset?

This works for me.

dataFrame = pd.dataFrame(data = np.c_[ [iris['data'],iris['target'] ],
columns=iris['feature_names'].tolist() + ['target'])

Node.js Web Application examples/tutorials

The Node Knockout competition wrapped up recently, and many of the submissions are available on github. The competition site doesn't appear to be working right now, but I'm sure you could Google up a few entries to check out.

Create SQLite database in android

If you want to keep the database between uninstalls you have to put it on the SD Card. This is the only place that won't be deleted at the moment your app is deleted. But in return it can be deleted by the user every time.

If you put your DB on the SD Card you can't use the SQLiteOpenHelper anymore, but you can use the source and the architecture of this class to get some ideas on how to implement the creation, updating and opening of a databse.

foreach with index

You can do the following

foreach (var it in someCollection.Select((x, i) => new { Value = x, Index = i }) )
{
   if (it.Index > SomeNumber) //      
}

This will create an anonymous type value for every entry in the collection. It will have two properties

  • Value: with the original value in the collection
  • Index: with the index within the collection

Accessing Objects in JSON Array (JavaScript)

Use a loop

for(var i = 0; i < obj.length; ++i){
   //do something with obj[i]
   for(var ind in obj[i]) {
        console.log(ind);
        for(var vals in obj[i][ind]){
            console.log(vals, obj[i][ind][vals]);
        }
   }
}

Demo: http://jsfiddle.net/maniator/pngmL/

How to connect android wifi to adhoc wifi?

I did notice something of interest here: In my 2.3.4 phone I can't see AP/AdHoc SSIDs in the Settings > Wireless & Networks menu. On an Acer A500 running 4.0.3 I do see them, prefixed by (*)

However in the following bit of code that I adapted from (can't remember source, sorry!) I do see the Ad Hoc show up in the Wifi Scan on my 2.3.4 phone. I am still looking to actually connect and create a socket + input/outputStream. But, here ya go:

    public class MainActivity extends Activity {

private static final String CHIPKIT_BSSID = "E2:14:9F:18:40:1C";
private static final int CHIPKIT_WIFI_PRIORITY = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final Button btnDoSomething = (Button) findViewById(R.id.btnDoSomething);
    final Button btnNewScan = (Button) findViewById(R.id.btnNewScan);
    final TextView textWifiManager = (TextView) findViewById(R.id.WifiManager);
    final TextView textWifiInfo = (TextView) findViewById(R.id.WifiInfo);
    final TextView textIp = (TextView) findViewById(R.id.Ip);

    final WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    final WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();

    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.BSSID = CHIPKIT_BSSID;
    wifiConfiguration.priority = CHIPKIT_WIFI_PRIORITY;
    wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
    wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    wifiConfiguration.status = WifiConfiguration.Status.ENABLED;

    myWifiManager.setWifiEnabled(true);

    int netID = myWifiManager.addNetwork(wifiConfiguration);

    myWifiManager.enableNetwork(netID, true);

    textWifiInfo.setText("SSID: " + myWifiInfo.getSSID() + '\n' 
            + myWifiManager.getWifiState() + "\n\n");

    btnDoSomething.setOnClickListener(new View.OnClickListener() {          
        public void onClick(View v) {
            clearTextViews(textWifiManager, textIp);                
        }           
    });

    btnNewScan.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            getNewScan(myWifiManager, textWifiManager, textIp);
        }
    });     
}

private void clearTextViews(TextView...tv) {
    for(int i = 0; i<tv.length; i++){
        tv[i].setText("");
    }       
}

public void getNewScan(WifiManager wm, TextView...textViews) {
    wm.startScan();

    List<ScanResult> scanResult = wm.getScanResults();

    String scan = "";

    for (int i = 0; i < scanResult.size(); i++) {
        scan += (scanResult.get(i).toString() + "\n\n");
    }

    textViews[0].setText(scan);
    textViews[1].setText(wm.toString());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

Don't forget that in Eclipse you can use Ctrl+Shift+[letter O] to fill in the missing imports...

and my manifest:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.digilent.simpleclient"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Hope that helps!

Stop setInterval

Use a variable and call clearInterval to stop it.

var interval;

$(document).on('ready',function()
  interval = setInterval(updateDiv,3000);
  });

  function updateDiv(){
    $.ajax({
      url: 'getContent.php',
      success: function(data){
        $('.square').html(data);
      },
      error: function(){
        $.playSound('oneday.wav');
        $('.square').html('<span style="color:red">Connection problems</span>');
        // I want to stop it here
        clearInterval(interval);
      }
    });
  }

Java error: Implicit super constructor is undefined for default constructor

You get this error because a class which has no constructor has a default constructor, which is argument-less and is equivalent to the following code:

public ACSubClass() {
    super();
}

However since your BaseClass declares a constructor (and therefore doesn't have the default, no-arg constructor that the compiler would otherwise provide) this is illegal - a class that extends BaseClass can't call super(); because there is not a no-argument constructor in BaseClass.

This is probably a little counter-intuitive because you might think that a subclass automatically has any constructor that the base class has.

The simplest way around this is for the base class to not declare a constructor (and thus have the default, no-arg constructor) or have a declared no-arg constructor (either by itself or alongside any other constructors). But often this approach can't be applied - because you need whatever arguments are being passed into the constructor to construct a legit instance of the class.

How to get the PID of a process by giving the process name in Mac OS X ?

The answer above was mostly correct, just needed some tweaking for the different parameters in Mac OSX.

ps -A | grep [f]irefox | awk '{print $1}'

Sieve of Eratosthenes - Finding Primes Python

I just came up with this. It may not be the fastest, but I'm not using anything other than straight additions and comparisons. Of course, what stops you here is the recursion limit.

def nondivsby2():
    j = 1
    while True:
        j += 2
        yield j

def nondivsbyk(k, nondivs):
    j = 0
    for i in nondivs:
        while j < i:
            j += k
        if j > i:
            yield i

def primes():
    nd = nondivsby2()
    while True:
        p = next(nd)
        nd = nondivsbyk(p, nd)
        yield p

def main():
    for p in primes():
        print(p)

Regular expression for validating names and surnames?

It's a very difficult problem to validate something like a name due to all the corner cases possible.

Corner Cases

Sanitize the inputs and let them enter whatever they want for a name, because deciding what is a valid name and what is not is probably way outside the scope of whatever you're doing; given the range of potential strange - and legal names is nearly infinite.

If they want to call themselves Tricyclopltz^2-Glockenschpiel, that's their problem, not yours.

Enter triggers button click

Pressing enter in a form's text field will, by default, submit the form. If you don't want it to work that way you have to capture the enter key press and consume it like you've done. There is no way around this. It will work this way even if there is no button present in the form.

How to add headers to a multicolumn listbox in an Excel userform using VBA

Here's my solution.

I noticed that when I specify the listbox's rowsource via the properties window in the VBE, the headers pop up no problem. Its only when we try define the rowsource through VBA code that the headers get lost.

So I first went a defined the listboxes rowsource as a named range in the VBE for via the properties window, then I can reset the rowsource in VBA code after that. The headers still show up every time.

I am using this in combination with an advanced filter macro from a listobject, which then creates another (filtered) listobject on which the rowsource is based.

This worked for me

Rollback to last git commit

An easy foolproof way to UNDO local file changes since the last commit is to place them in a new branch:

git branch changes
git checkout changes
git add .
git commit

This leaves the changes in the new branch. Return to the original branch to find it back to the last commit:

git checkout master

The new branch is a good place to practice different ways to revert changes without risk of messing up the original branch.

Comparison between Corona, Phonegap, Titanium

For anybody interested in Titanium i must say that they don't have a very good documentation some classes, properties, methods are missing. But a lot is "documented" in their sample app the KitchenSink so it is not THAT bad.

How to Detect if I'm Compiling Code with a particular Visual Studio version?

_MSC_VER should be defined to a specific version number. You can either #ifdef on it, or you can use the actual define and do a runtime test. (If for some reason you wanted to run different code based on what compiler it was compiled with? Yeah, probably you were looking for the #ifdef. :))

Batch script loop

And to iterate on the files of a directory:

@echo off 
setlocal enableDelayedExpansion 

set MYDIR=C:\something
for /F %%x in ('dir /B/D %MYDIR%') do (
  set FILENAME=%MYDIR%\%%x\log\IL_ERROR.log
  echo ===========================  Search in !FILENAME! ===========================
  c:\utils\grep motiv !FILENAME!
)

You must use "enableDelayedExpansion" and !FILENAME! instead of $FILENAME$. In the second case, DOS will interpret the variable only once (before it enters the loop) and not each time the program loops.

How display only years in input Bootstrap Datepicker?

For bootstrap datetimepicker, assign decade value as follow:

$(".years").datetimepicker({
    format: "yyyy",
    startView: 'decade',
    minView: 'decade',
    viewSelect: 'decade',
    autoclose: true,
});

Bootstrap 3: Scroll bars

You need to use the overflow option, but with the following parameters:

.nav {
    max-height:300px;
    overflow-y:auto;  
}

Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.

If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.

Presumably you want something that adapts itself to the content rather then the the opposite.

Hope it may helpful

Concatenate two PySpark dataframes

To make it more generic of keeping both columns in df1 and df2:

import pyspark.sql.functions as F

# Keep all columns in either df1 or df2
def outter_union(df1, df2):

    # Add missing columns to df1
    left_df = df1
    for column in set(df2.columns) - set(df1.columns):
        left_df = left_df.withColumn(column, F.lit(None))

    # Add missing columns to df2
    right_df = df2
    for column in set(df1.columns) - set(df2.columns):
        right_df = right_df.withColumn(column, F.lit(None))

    # Make sure columns are ordered the same
    return left_df.union(right_df.select(left_df.columns))

How to fast get Hardware-ID in C#?

We use a combination of the processor id number (ProcessorID) from Win32_processor and the universally unique identifier (UUID) from Win32_ComputerSystemProduct:

ManagementObjectCollection mbsList = null;
ManagementObjectSearcher mos = new ManagementObjectSearcher("Select ProcessorID From Win32_processor");
mbsList = mos.Get();
string processorId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
    processorId = mo["ProcessorID"] as string;
}

mos = new ManagementObjectSearcher("SELECT UUID FROM Win32_ComputerSystemProduct");
mbsList = mos.Get();
string systemId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
    systemId = mo["UUID"] as string;
}

var compIdStr = $"{processorId}{systemId}";

Previously, we used a combination: processor ID ("Select ProcessorID From Win32_processor") and the motherboard serial number ("SELECT SerialNumber FROM Win32_BaseBoard"), but then we found out that the serial number of the motherboard may not be filled in, or it may be filled in with uniform values:

  • To be filled by O.E.M.
  • None
  • Default string

Therefore, it is worth considering this situation.

Also keep in mind that the ProcessorID number may be the same on different computers.

Required attribute HTML5

A small note on custom attributes: HTML5 allows all kind of custom attributes, as long as they are prefixed with the particle data-, i.e. data-my-attribute="true".

AngularJS ng-class if-else expression

I had a situation where I needed two 'if' statements that could both go true and an 'else' or default if neither were true, not sure if this is an improvement on Jossef's answer but it seemed cleaner to me:

ng-class="{'class-one' : value.one , 'class-two' : value.two}" class="else-class"

Where value.one and value.two are true, they take precedent over the .else-class

The HTTP request is unauthorized with client authentication scheme 'Ntlm' The authentication header received from the server was 'NTLM'

After a lot of trial and error, followed by a stagnant period while I waited for an opportunity to speak with our server guys, I finally had a chance to discuss the problem with them and asked them if they wouldn't mind switching our Sharepoint authentication over to Kerberos.

To my surprise, they said this wouldn't be a problem and was in fact easy to do. They enabled Kerberos and I modified my app.config as follows:

<security mode="Transport">
    <transport clientCredentialType="Windows" />
</security>

For reference, my full serviceModel entry in my app.config looks like this:

<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="TestServerReference" closeTimeout="00:01:00" openTimeout="00:01:00"
             receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
             bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
             maxBufferSize="2000000" maxBufferPoolSize="2000000" maxReceivedMessageSize="2000000"
             messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
             useDefaultWebProxy="true">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                 maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <security mode="Transport">
                    <transport clientCredentialType="Windows" />
                </security>
            </binding>
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="https://path/to/site/_vti_bin/Lists.asmx"
         binding="basicHttpBinding" bindingConfiguration="TestServerReference"
         contract="TestServerReference.ListsSoap" name="TestServerReference" />
    </client>
</system.serviceModel>

After this, everything worked like a charm. I can now (finally!) utilize Sharepoint Web Services. So, if anyone else out there can't get their Sharepoint Web Services to work with NTLM, see if you can convince the sysadmins to switch over to Kerberos.

Add disabled attribute to input element using Javascript

If you're using jQuery then there are a few different ways to set the disabled attribute.

var $element = $(...);
    $element.prop('disabled', true);
    $element.attr('disabled', true); 

    // The following do not require jQuery
    $element.get(0).disabled = true;
    $element.get(0).setAttribute('disabled', true);
    $element[0].disabled = true;
    $element[0].setAttribute('disabled', true);

Create a Date with a set timezone without using a string representation

I don't believe this is possible - there is no ability to set the timezone on a Date object after it is created.

And in a way this makes sense - conceptually (if perhaps not in implementation); per http://en.wikipedia.org/wiki/Unix_timestamp (emphasis mine):

Unix time, or POSIX time, is a system for describing instants in time, defined as the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of Thursday, January 1, 1970.

Once you've constructed one it will represent a certain point in "real" time. The time zone is only relevant when you want to convert that abstract time point into a human-readable string.

Thus it makes sense you would only be able to change the actual time the Date represents in the constructor. Sadly it seems that there is no way to pass in an explicit timezone - and the constructor you are calling (arguably correctly) translates your "local" time variables into GMT when it stores them canonically - so there is no way to use the int, int, int constructor for GMT times.

On the plus side, it's trivial to just use the constructor that takes a String instead. You don't even have to convert the numeric month into a String (on Firefox at least), so I was hoping a naive implementation would work. However, after trying it out it works successfully in Firefox, Chrome, and Opera but fails in Konqueror ("Invalid Date") , Safari ("Invalid Date") and IE ("NaN"). I suppose you'd just have a lookup array to convert the month to a string, like so:

var months = [ '', 'January', 'February', ..., 'December'];

function createGMTDate(xiYear, xiMonth, xiDate) {
   return new Date(months[xiMonth] + ' ' + xiDate + ', ' + xiYear + ' 00:00:00 GMT');
}

How do I get the path of a process in Unix / Linux

I use:

ps -ef | grep 786

Replace 786 with your PID or process name.

Integer division with remainder in JavaScript?

You can use ternary to decide how to handle positive and negative integer values as well.

var myInt = (y > 0) ? Math.floor(y/x) : Math.floor(y/x) + 1

If the number is a positive, all is fine. If the number is a negative, it will add 1 because of how Math.floor handles negatives.

How to determine when Fragment becomes visible in ViewPager

May be very late. This is working for me. I slightly updated the code from @Gobar and @kris Solutions. We have to update the code in our PagerAdapter.

setPrimaryItem is called every time when a tab is visible and returns its position. If the position are same means we are unmoved. If position changed and current position is not our clicked tab set as -1.

private int mCurrentPosition = -1;

@Override
public void setPrimaryItem(@NotNull ViewGroup container, int position, @NotNull Object object) {
    // This is what calls setMenuVisibility() on the fragments
    super.setPrimaryItem(container, position, object);
    if (position == mCurrentPosition) {
        return;
    }
    if (object instanceof YourFragment) {
        YourFragment fragment = (YourFragment) object;
        if (fragment.isResumed()) {
            mCurrentPosition = position;
            fragment.doYourWork();//Update your function
        }
    } else {
        mCurrentPosition = -1;
    }
}

Spring .properties file: get element as an Array

If you define your array in properties file like:

base.module.elementToSearch=1,2,3,4,5,6

You can load such array in your Java class like this:

  @Value("${base.module.elementToSearch}")
  private String[] elementToSearch;

How can I add a .npmrc file?

In MacOS Catalina 10.15.5 the .npmrc file path can be found at

/Users/<user-name>/.npmrc

Open in it in (for first time users, create a new file) any editor and copy-paste your token. Save it.

You are ready to go.

Note: As mentioned by @oligofren, the command npm config ls -l will npm configurations. You will get the .npmrc file from config parameter userconfig

Add table row in jQuery

I found this AddRow plugin quite useful for managing table rows. Though, Luke's solution would be the best fit if you just need to add a new row.

Sqlite or MySql? How to decide?

The sqlite team published an article explaining when to use sqlite that is great read. Basically, you want to avoid using sqlite when you have a lot of write concurrency or need to scale to terabytes of data. In many other cases, sqlite is a surprisingly good alternative to a "traditional" database such as MySQL.

JPA Query selecting only specific columns without using Criteria Query?

Projections can be used to select only specific properties(columns) of an entity object.

From the docs

Spring Data Repositories usually return the domain model when using query methods. However, sometimes, you may need to alter the view of that model for various reasons. In this section, you will learn how to define projections to serve up simplified and reduced views of resources.

Define an interface with only the getters you want.

interface CustomObject {  
    String getA(); // Actual property name is A
    String getB(); // Actual property name is B 
}

Now return CustomObject from your repository like so :

public interface YOU_REPOSITORY_NAME extends JpaRepository<YOUR_ENTITY, Long> {
    CustomObject findByObjectName(String name);
}

Eclipse : Failed to connect to remote VM. Connection refused.

I faced the same issue. But i resolved it by changing my port numbers to different one.

Passing $_POST values with cURL

Check out this page which has an example of how to do it.

How do I set the maximum line length in PyCharm?

For anyone, or myself if I reload my machine, who this is not working for when you do a code reformat there is an additional option to check under editor->code style->python : ensure right margin is not exceeded. Once this was selected the reformat would work.

preference_highlighted

Remove xticks in a matplotlib plot?

Here is an alternative solution that I found on the matplotlib mailing list:

import matplotlib.pylab as plt

x = range(1000)
ax = plt.axes()
ax.semilogx(x, x)
ax.xaxis.set_ticks_position('none') 

graph

Maven build debug in Eclipse

Easiest way I find is to:

  1. Right click project

  2. Debug as -> Maven build ...

  3. In the goals field put -Dmaven.surefire.debug test

  4. In the parameters put a new parameter called forkCount with a value of 0 (previously was forkMode=never but it is deprecated and doesn't work anymore)

Set your breakpoints down and run this configuration and it should hit the breakpoint.

How to set default value for HTML select?

Note: this is JQuery. See Sébastien answer for Javascript

$(function() {
    var temp="a"; 
    $("#MySelect").val(temp);
});

<select name="MySelect" id="MySelect">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
</select>

Controlling number of decimal digits in print output in R

If you are producing the entire output yourself, you can use sprintf(), e.g.

> sprintf("%.10f",0.25)
[1] "0.2500000000"

specifies that you want to format a floating point number with ten decimal points (in %.10f the f is for float and the .10 specifies ten decimal points).

I don't know of any way of forcing R's higher level functions to print an exact number of digits.

Displaying 100 digits does not make sense if you are printing R's usual numbers, since the best accuracy you can get using 64-bit doubles is around 16 decimal digits (look at .Machine$double.eps on your system). The remaining digits will just be junk.

How can I set the initial value of Select2 when using AJAX?

after spending a few hours searching for a solution, I decided to create my own. He it is:

 function CustomInitSelect2(element, options) {
            if (options.url) {
                $.ajax({
                    type: 'GET',
                    url: options.url,
                    dataType: 'json'
                }).then(function (data) {
                    element.select2({
                        data: data
                    });
                    if (options.initialValue) {
                        element.val(options.initialValue).trigger('change');
                    }
                });
            }
        }

And you can initialize the selects using this function:

$('.select2').each(function (index, element) {
            var item = $(element);
            if (item.data('url')) {
                CustomInitSelect2(item, {
                    url: item.data('url'),
                    initialValue: item.data('value')
                });
            }
            else {
                item.select2();
            }
        });

And of course, here is the html:

<select class="form-control select2" id="test1" data-url="mysite/load" data-value="123"></select>

How to execute a JavaScript function when I have its name as a string

There's a very similar thing in my code. I have a server-generated string which contains a function name which I need to pass as a callback for a 3rd party library. So I have a code that takes the string and returns a "pointer" to the function, or null if it isn't found.

My solution was very similar to "Jason Bunting's very helpful function" *, although it doesn't auto-execute, and the context is always on the window. But this can be easily modified.

Hopefully this will be helpful to someone.

/**
 * Converts a string containing a function or object method name to a function pointer.
 * @param  string   func
 * @return function
 */
function getFuncFromString(func) {
    // if already a function, return
    if (typeof func === 'function') return func;

    // if string, try to find function or method of object (of "obj.func" format)
    if (typeof func === 'string') {
        if (!func.length) return null;
        var target = window;
        var func = func.split('.');
        while (func.length) {
            var ns = func.shift();
            if (typeof target[ns] === 'undefined') return null;
            target = target[ns];
        }
        if (typeof target === 'function') return target;
    }

    // return null if could not parse
    return null;
}

Combine two (or more) PDF's

I had to solve a similar problem and what I ended up doing was creating a small pdfmerge utility that uses the PDFSharp project which is essentially MIT licensed.

The code is dead simple, I needed a cmdline utility so I have more code dedicated to parsing the arguments than I do for the PDF merging:

using (PdfDocument one = PdfReader.Open("file1.pdf", PdfDocumentOpenMode.Import))
using (PdfDocument two = PdfReader.Open("file2.pdf", PdfDocumentOpenMode.Import))
using (PdfDocument outPdf = new PdfDocument())
{                
    CopyPages(one, outPdf);
    CopyPages(two, outPdf);

    outPdf.Save("file1and2.pdf");
}

void CopyPages(PdfDocument from, PdfDocument to)
{
    for (int i = 0; i < from.PageCount; i++)
    {
        to.AddPage(from.Pages[i]);
    }
}

How to align a div to the top of its parent but keeping its inline-block behaviour?

Or you could just add some content to the div and use inline-table

"Insufficient Storage Available" even there is lot of free space in device memory

I had the same issue on Galaxy S4 (i9505) on stock ROM (4.2.2 ME2). I had free space like this: 473 MB on /data, 344 MB on /system, 2 GB on /cache. I was getting the free spate error on any download from Play Store (small app, 2.5 MB), I checked LogCat, it said "Cancel download of ABC because insufficient free space".

Then I freed up some space on /data, 600 MB free, and now it's working fine, apps download and install ;). So it seems like this ROM needs a little more free space to work OK...

HttpClient not supporting PostAsJsonAsync method C#

Try to install in your project the NuGet Package: Microsoft.AspNet.WebApi.Client:

Install-Package Microsoft.AspNet.WebApi.Client

Creating a JSON dynamically with each input value using jquery

May be this will help, I'd prefer pure JS wherever possible, it improves the performance drastically as you won't have lots of JQuery function calls.

var obj = [];
var elems = $("input[class=email]");

for (i = 0; i < elems.length; i += 1) {
    var id = this.getAttribute('title');
    var email = this.value;
    tmp = {
        'title': id,
        'email': email
    };

    obj.push(tmp);
}

Center/Set Zoom of Map to cover all visible Markers?

To extend the given answer with few useful tricks:

var markers = //some array;
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
   bounds.extend(markers[i].getPosition());
}

//center the map to a specific spot (city)
map.setCenter(center); 

//center the map to the geometric center of all markers
map.setCenter(bounds.getCenter());

map.fitBounds(bounds);

//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom()-1); 

// set a minimum zoom 
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom()> 15){
  map.setZoom(15);
}

//Alternatively this code can be used to set the zoom for just 1 marker and to skip redrawing.
//Note that this will not cover the case if you have 2 markers on the same address.
if(count(markers) == 1){
    map.setMaxZoom(15);
    map.fitBounds(bounds);
    map.setMaxZoom(Null)
}

UPDATE:
Further research in the topic show that fitBounds() is a asynchronic and it is best to make Zoom manipulation with a listener defined before calling Fit Bounds.
Thanks @Tim, @xr280xr, more examples on the topic : SO:setzoom-after-fitbounds

google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
  this.setZoom(map.getZoom()-1);

  if (this.getZoom() > 15) {
    this.setZoom(15);
  }
});
map.fitBounds(bounds);

Convert cells(1,1) into "A1" and vice versa

The Address property of a cell can get this for you:

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)

returns A1.

The other way around can be done with the Row and Column property of Range:

MsgBox Range("A1").Row & ", " & Range("A1").Column

returns 1,1.

Importing packages in Java

Here is the right way to do imports in Java.

import Dan.Vik;
class Kab
{
public static void main(String args[])
{
    Vik Sam = new Vik();
    Sam.disp();
}
}

You don't import methods in java. There is an advanced usage of static imports but basically you just import packages and classes. If the function you are importing is a static function you can do a static import, but I don't think you are looking for static imports here.

How do I find all files containing specific text on Linux?

Kindly customize below command according to demand and find any string recursively from files.

grep -i hack $(find /etc/ -type f)

Implements vs extends: When to use? What's the difference?

We use SubClass extends SuperClass only when the subclass wants to use some functionality (methods or instance variables) that is already declared in the SuperClass, or if I want to slightly modify the functionality of the SuperClass (Method overriding). But say, I have an Animal class(SuperClass) and a Dog class (SubClass) and there are few methods that I have defined in the Animal class eg. doEat(); , doSleep(); ... and many more.

Now, my Dog class can simply extend the Animal class, if i want my dog to use any of the methods declared in the Animal class I can invoke those methods by simply creating a Dog object. So this way I can guarantee that I have a dog that can eat and sleep and do whatever else I want the dog to do.

Now, imagine, one day some Cat lover comes into our workspace and she tries to extend the Animal class(cats also eat and sleep). She makes a Cat object and starts invoking the methods.

But, say, someone tries to make an object of the Animal class. You can tell how a cat sleeps, you can tell how a dog eats, you can tell how an elephant drinks. But it does not make any sense in making an object of the Animal class. Because it is a template and we do not want any general way of eating.

So instead, I will prefer to make an abstract class that no one can instantiate but can be used as a template for other classes.

So to conclude, Interface is nothing but an abstract class(a pure abstract class) which contains no method implementations but only the definitions(the templates). So whoever implements the interface just knows that they have the templates of doEat(); and doSleep(); but they have to define their own doEat(); and doSleep(); methods according to their need.

You extend only when you want to reuse some part of the SuperClass(but keep in mind, you can always override the methods of your SuperClass according to your need) and you implement when you want the templates and you want to define them on your own(according to your need).

I will share with you a piece of code: You try it with different sets of inputs and look at the results.

class AnimalClass {

public void doEat() {
    
    System.out.println("Animal Eating...");
}

public void sleep() {
    
    System.out.println("Animal Sleeping...");
}

}

public class Dog extends AnimalClass implements AnimalInterface, Herbi{

public static void main(String[] args) {
    
    AnimalInterface a = new Dog();
    Dog obj = new Dog();
    obj.doEat();
    a.eating();
    
    obj.eating();
    obj.herbiEating();
}

public void doEat() {
    System.out.println("Dog eating...");
}

@Override
public void eating() {
    
    System.out.println("Eating through an interface...");
    // TODO Auto-generated method stub
    
}

@Override
public void herbiEating() {
    
    System.out.println("Herbi eating through an interface...");
    // TODO Auto-generated method stub
    
}


}

Defined Interfaces :

public interface AnimalInterface {

public void eating();

}


interface Herbi {

public void herbiEating();

}

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

You need to read from the configuration section manually before your code returns a JsonResult object. Simply read from web.config in single line:

        var jsonResult = Json(resultsForAjaxUI);
        jsonResult.MaxJsonLength = (ConfigurationManager.GetSection("system.web.extensions/scripting/webServices/jsonSerialization") as System.Web.Configuration.ScriptingJsonSerializationSection).MaxJsonLength;
        return jsonResult;

Be sure you defined configuration element in web.config

How to calculate the SVG Path for an arc (of a circle)

An image and some Python

Just to clarify better and offer another solution. Arc [A] command use the current position as a starting point so you have to use Moveto [M] command first.

Then the parameters of Arc are the following:

rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, xf, yf

If we define for example the following svg file:

_x000D_
_x000D_
<svg viewBox="0 0 500 500">_x000D_
    <path fill="red" d="_x000D_
    M 250 250_x000D_
    A 100 100 0 0 0 450 250_x000D_
    Z"/> _x000D_
</svg>
_x000D_
_x000D_
_x000D_

enter image description here

You will set the starting point with M the ending point with the parameters xf and yf of A.

We are looking for circles so we set rx equal to ry doing so basically now it will try to find all the circle of radius rx that intersect the starting and end point.

import numpy as np

def write_svgarc(xcenter,ycenter,r,startangle,endangle,output='arc.svg'):
    if startangle > endangle: 
        raise ValueError("startangle must be smaller than endangle")

    if endangle - startangle < 360:
        large_arc_flag = 0
        radiansconversion = np.pi/180.
        xstartpoint = xcenter + r*np.cos(startangle*radiansconversion)
        ystartpoint = ycenter - r*np.sin(startangle*radiansconversion)
        xendpoint = xcenter + r*np.cos(endangle*radiansconversion)
        yendpoint = ycenter - r*np.sin(endangle*radiansconversion)
        #If we want to plot angles larger than 180 degrees we need this
        if endangle - startangle > 180: large_arc_flag = 1
        with open(output,'a') as f:
            f.write(r"""<path d=" """)
            f.write("M %s %s" %(xstartpoint,ystartpoint))
            f.write("A %s %s 0 %s 0 %s %s" 
                    %(r,r,large_arc_flag,xendpoint,yendpoint))
            f.write("L %s %s" %(xcenter,ycenter))
            f.write(r"""Z"/>""" )

    else:
        with open(output,'a') as f:
            f.write(r"""<circle cx="%s" cy="%s" r="%s"/>"""
                    %(xcenter,ycenter,r))

You can have a more detailed explanation in this post that I wrote.

How to grep for two words existing on the same line?

you could use awk. like this...

cat <yourFile> | awk '/word1/ && /word2/'

Order is not important. So if you have a file and...

a file named , file1 contains:

word1 is in this file as well as word2
word2 is in this file as well as word1
word4 is in this file as well as word1
word5 is in this file as well as word2

then,

/tmp$ cat file1| awk '/word1/ && /word2/'

will result in,

word1 is in this file as well as word2
word2 is in this file as well as word1

yes, awk is slower.

How to index into a dictionary?

actually I found a novel solution that really helped me out, If you are especially concerned with the index of a certain value in a list or data set, you can just set the value of dictionary to that Index!:

Just watch:

list = ['a', 'b', 'c']
dictionary = {}
counter = 0
for i in list:
   dictionary[i] = counter
   counter += 1

print(dictionary) # dictionary = {'a':0, 'b':1, 'c':2}

Now through the power of hashmaps you can pull the index your entries in constant time (aka a whole lot faster)

Laravel form html with PUT method for PUT routes

Just use like this somewhere inside the form

@method('PUT')

Capture key press without placing an input element on the page?

For non-printable keys such as arrow keys and shortcut keys such as Ctrl-z, Ctrl-x, Ctrl-c that may trigger some action in the browser (for instance, inside editable documents or elements), you may not get a keypress event in all browsers. For this reason you have to use keydown instead, if you're interested in suppressing the browser's default action. If not, keyup will do just as well.

Attaching a keydown event to document works in all the major browsers:

document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.ctrlKey && evt.keyCode == 90) {
        alert("Ctrl-Z");
    }
};

For a complete reference, I strongly recommend Jan Wolter's article on JavaScript key handling.

How to take the nth digit of a number in python

Ok, first of all, use the str() function in python to turn 'number' into a string

number = 9876543210 #declaring and assigning
number = str(number) #converting

Then get the index, 0 = 1, 4 = 3 in index notation, use int() to turn it back into a number

print(int(number[3])) #printing the int format of the string "number"'s index of 3 or '6'

if you like it in the short form

print(int(str(9876543210)[3])) #condensed code lol, also no more variable 'number'

how to remove new lines and returns from php string?

$no_newlines = str_replace("\r", '', str_replace("\n", '', $str_with_newlines));

Node.js quick file server (static files over HTTP)

If you are intrested in ultra-light http server without any prerequisites you should have a look at: mongoose

how to implement regions/code collapse in javascript

For those about to use the visual studio 2012, exists the Web Essentials 2012

For those about to use the visual studio 2015, exists the Web Essentials 2015.3

The usage is exactly like @prasad asked

How to Execute a Python File in Notepad ++?

I started using Notepad++ for Python very recently and I found this method very easy. Once you are ready to run the code,right-click on the tab of your code in Notepad++ window and select "Open Containing Folder in cmd". This will open the Command Prompt into the folder where the current program is stored. All you need to do now is to execute:

python

This was done on Notepad++ (Build 10 Jan 2015).

I can't add the screenshots, so here's a blog post with the screenshots - http://coder-decoder.blogspot.in/2015/03/using-notepad-in-windows-to-edit-and.html

Delete column from pandas DataFrame

df.drop('columnname', axis =1, inplace = True)

or else you can go with

del df['colname']

To delete multiple columns based on column numbers

df.drop(df.iloc[:,1:3], axis = 1, inplace = True)

To delete multiple columns based on columns names

df.drop(['col1','col2',..'coln'], axis = 1, inplace = True)

What is the difference between MOV and LEA?

Basically ... "Move into REG ... after computing it..." it seems to be nice for other purposes as well :)

if you just forget that the value is a pointer you can use it for code optimizations/minimization ...what ever..

MOV EBX , 1
MOV ECX , 2

;//with 1 instruction you got result of 2 registers in 3rd one ...
LEA EAX , [EBX+ECX+5]

EAX = 8

originaly it would be:

MOV EAX, EBX
ADD EAX, ECX
ADD EAX, 5

how to get the one entry from hashmap without iterating

This would get a single entry from the map, which about as close as one can get, given 'first' doesn't really apply.

import java.util.*;

public class Friday {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<String, Integer>();

        map.put("code", 10);
        map.put("to", 11);
        map.put("joy", 12);

        if (! map.isEmpty()) {
            Map.Entry<String, Integer> entry = map.entrySet().iterator().next();
            System.out.println(entry);
        }
    }
}

How to format a string as a telephone number in C#

 Label12.Text = Convert.ToInt64(reader[6]).ToString("(###) ###-#### ");

This is my example! I hope can help you with this. regards

Use dynamic variable names in `dplyr`

Since you are dynamically building a variable name as a character value, it makes more sense to do assignment using standard data.frame indexing which allows for character values for column names. For example:

multipetal <- function(df, n) {
    varname <- paste("petal", n , sep=".")
    df[[varname]] <- with(df, Petal.Width * n)
    df
}

The mutate function makes it very easy to name new columns via named parameters. But that assumes you know the name when you type the command. If you want to dynamically specify the column name, then you need to also build the named argument.


dplyr version >= 1.0

With the latest dplyr version you can use the syntax from the glue package when naming parameters when using :=. So here the {} in the name grab the value by evaluating the expression inside.

multipetal <- function(df, n) {
  mutate(df, "petal.{n}" := Petal.Width * n)
}

dplyr version >= 0.7

dplyr starting with version 0.7 allows you to use := to dynamically assign parameter names. You can write your function as:

# --- dplyr version 0.7+---
multipetal <- function(df, n) {
    varname <- paste("petal", n , sep=".")
    mutate(df, !!varname := Petal.Width * n)
}

For more information, see the documentation available form vignette("programming", "dplyr").


dplyr (>=0.3 & <0.7)

Slightly earlier version of dplyr (>=0.3 <0.7), encouraged the use of "standard evaluation" alternatives to many of the functions. See the Non-standard evaluation vignette for more information (vignette("nse")).

So here, the answer is to use mutate_() rather than mutate() and do:

# --- dplyr version 0.3-0.5---
multipetal <- function(df, n) {
    varname <- paste("petal", n , sep=".")
    varval <- lazyeval::interp(~Petal.Width * n, n=n)
    mutate_(df, .dots= setNames(list(varval), varname))
}

dplyr < 0.3

Note this is also possible in older versions of dplyr that existed when the question was originally posed. It requires careful use of quote and setName:

# --- dplyr versions < 0.3 ---
multipetal <- function(df, n) {
    varname <- paste("petal", n , sep=".")
    pp <- c(quote(df), setNames(list(quote(Petal.Width * n)), varname))
    do.call("mutate", pp)
}

Proxy setting for R

This post pertains to R proxy issues on *nix. You should know that R has many libraries/methods to fetch data over internet.

For 'curl', 'libcurl', 'wget' etc, just do the following:

  1. Open a terminal. Type the following command:

    sudo gedit /etc/R/Renviron.site
    
  2. Enter the following lines:

    http_proxy='http://username:[email protected]:port/'
    https_proxy='https://username:[email protected]:port/'
    

    Replace username, password, abc.com, xyz.com and port with these settings specific to your network.

  3. Quit R and launch again.

This should solve your problem with 'libcurl' and 'curl' method. However, I have not tried it with 'httr'. One way to do that with 'httr' only for that session is as follows:

library(httr)
set_config(use_proxy(url="abc.com",port=8080, username="username", password="password"))

You need to substitute settings specific to your n/w in relevant fields.

Random word generator- Python

There is a package random_word could implement this request very conveniently:

 $ pip install random-word

from random_word import RandomWords
r = RandomWords()

# Return a single random word
r.get_random_word()
# Return list of Random words
r.get_random_words()
# Return Word of the day
r.word_of_the_day()

Instantiating a generic class in Java

Here's a rather contrived way to do it without explicitly using an constructor argument. You need to extend a parameterized abstract class.

public class Test {   
    public static void main(String [] args) throws Exception {
        Generic g = new Generic();
        g.initParameter();
    }
}

import java.lang.reflect.ParameterizedType;
public abstract class GenericAbstract<T extends Foo> {
    protected T parameter;

    @SuppressWarnings("unchecked")
    void initParameter() throws Exception, ClassNotFoundException, 
        InstantiationException {
        // Get the class name of this instance's type.
        ParameterizedType pt
            = (ParameterizedType) getClass().getGenericSuperclass();
        // You may need this split or not, use logging to check
        String parameterClassName
            = pt.getActualTypeArguments()[0].toString().split("\\s")[1];
        // Instantiate the Parameter and initialize it.
        parameter = (T) Class.forName(parameterClassName).newInstance();
    }
}

public class Generic extends GenericAbstract<Foo> {
}

public class Foo {
    public Foo() {
        System.out.println("Foo constructor...");
    }
}

onchange event for input type="number"

http://jsfiddle.net/XezmB/8/

$(":input").bind('keyup change click', function (e) {
    if (! $(this).data("previousValue") || 
           $(this).data("previousValue") != $(this).val()
       )
   {
        console.log("changed");           
        $(this).data("previousValue", $(this).val());
   }

});


$(":input").each(function () {
    $(this).data("previousValue", $(this).val());
});?

This is a little bit ghetto, but this way you can use the "click" event to capture the event that runs when you use the mouse to increment/decrement via the little arrows on the input. You can see how I've built in a little manual "change check" routine that makes sure your logic won't fire unless the value actually changed (to prevent false positives from simple clicks on the field).

Is there any way to show a countdown on the lockscreen of iphone?

Or you could figure out the exacting amount of hours and minutes and have that displayed by puttin it into the timer app that already exist in every iphone :)

How do I join two SQLite tables in my Android application?

You need rawQuery method.

Example:

private final String MY_QUERY = "SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.other_id WHERE b.property_id=?";

db.rawQuery(MY_QUERY, new String[]{String.valueOf(propertyId)});

Use ? bindings instead of putting values into raw sql query.

php - get numeric index of associative array

While Fosco's answer is not wrong there is a case to be considered with this one: mixed arrays. Imagine I have an array like this:

$a = array(
  "nice",
  "car" => "fast",
  "none"
);

Now, PHP allows this kind of syntax but it has one problem: if I run Fosco's code I get 0 which is wrong for me, but why this happens?
Because when doing comparisons between strings and integers PHP converts strings to integers (and this is kinda stupid in my opinion), so when array_search() searches for the index it stops at the first one because apparently ("car" == 0) is true.
Setting array_search() to strict mode won't solve the problem because then array_search("0", array_keys($a)) would return false even if an element with index 0 exists.
So my solution just converts all indexes from array_keys() to strings and then compares them correctly:

echo array_search("car", array_map("strval", array_keys($a)));

Prints 1, which is correct.

EDIT:
As Shaun pointed out in the comment below, the same thing applies to the index value, if you happen to search for an int index like this:

$a = array(
  "foo" => "bar",
  "nice",
  "car" => "fast",
  "none"
);
$ind = 0;
echo array_search($ind, array_map("strval", array_keys($a)));

You will always get 0, which is wrong, so the solution would be to cast the index (if you use a variable) to a string like this:

$ind = 0;
echo array_search((string)$ind, array_map("strval", array_keys($a)));

Unzip All Files In A Directory

In any POSIX shell, this will unzip into a different directory for each zip file:

for file in *.zip
do
    directory="${file%.zip}"
    unzip "$file" -d "$directory"
done

What is the keyguard in Android?

In a nutshell, it is your lockscreen.

PIN, pattern, face, password locks or the default lock (slide to unlock), but it is your lock screen.

adb command not found

+ The reason is: you are in the wrong directory (means it doesn't contain adb executor).

+ The solution is (step by step):

1) Find where the adb was installed. Depend on what OS you are using.

Mac, it could be in: "~/Library/Android/sdk/platform-tools"

or

Window, it could be in: "%USERPROFILE%\AppData\Local\Android\sdk\platform-tools\".

However, in case you could NOT remember this such long directory, you can quickly find it by the command "find". Try this in your terminal/ command line, "find / -name "platform-tools" 2> /dev/null" (Note: I didn't test in Window yet, but it works with Mac for sure).

*Explain the find command,

  • Please note there is a space before the "/" character --> only find in User directory not all the computer.
  • "2> /dev/null" --> ignore find results denied by permission. Try the one without this code, you will understand what I mean.

2) Go to where we installed adb. There are 3 ways mentioned by many people:

  • Change the PATH global param (which I won't recommend) by: "export PATH=~/Library/Android/sdk/platform-tools" which is the directory you got from above. Note, this command won't print any result, if you want to make sure you changed PATH successfully, call "export | grep PATH" to see what the PATH is.

  • Add more definition for the PATH global param (which I recommend) by: "export PATH=~/Library/Android/sdk/platform-tools:$PATH" or "export PATH=$PATH:~/Library/Android/sdk/platform-tools"

  • Go to the path we found above by "cd ~/Library/Android/sdk/platform-tools"

3) Use adb:

  • If you change or update the PATH, simply call any adb functions, since you added the PATH as a global param. (e.g: "adb devices")

  • If you go to the PATH by cd command, call adb functions with pre-fix "./ " (e.g: "./ adb devices")

How to use bootstrap datepicker

man you can use the basic Bootstrap Datepicker this way:

<!DOCTYPE html>
<head runat="server">
<title>Test Zone</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="Css/datepicker.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="../Js/bootstrap-datepicker.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#pickyDate').datepicker({
            format: "dd/mm/yyyy"
        });
    });
</script>

and inside body:

<body>
<div id="testDIV">
    <div class="container">
        <div class="hero-unit">
            <input  type="text" placeholder="click to show datepicker"  id="pickyDate"/>
        </div>
    </div>
</div>

datepicker.css and bootstrap-datepicker.js you can download from here on the Download button below "About" on the left side. Hope this help someone, greetings.

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

Properties file in python (similar to Java Properties)

This is what I'm doing in my project: I just create another .py file called properties.py which includes all common variables/properties I used in the project, and in any file need to refer to these variables, put

from properties import *(or anything you need)

Used this method to keep svn peace when I was changing dev locations frequently and some common variables were quite relative to local environment. Works fine for me but not sure this method would be suggested for formal dev environment etc.

Java: Calculating the angle between two points in degrees

Why is everyone complicating this?

The only problem is Math.atan2( x , y)

The corret answer is Math.atan2( y, x)

All they did was mix the variable order for Atan2 causing it to reverse the degree of rotation.

All you had to do was look up the syntax https://www.google.com/amp/s/www.geeksforgeeks.org/java-lang-math-atan2-java/amp/

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

On particular table

_x000D_
_x000D_
<table style="border-collapse: separate; border-spacing: 10px;" >_x000D_
    <tr>_x000D_
      <td>Hi</td>_x000D_
      <td>Hello</td>_x000D_
    <tr/>_x000D_
    <tr>_x000D_
      <td>Hola</td>_x000D_
      <td>Oi!</td>_x000D_
    <tr/>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Convert a string to integer with decimal in Python

How about this?

>>> s = '23.45678'
>>> int(float(s))
23

Or...

>>> int(Decimal(s))
23

Or...

>>> int(s.split('.')[0])
23

I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on.

C# : Converting Base Class to Child Class

Use the cast operator, as such:

var skyfilterClient = (SkyfilterClient)networkClient;

Read contents of a local file into a variable in Rails

Answering my own question here... turns out it's a Windows only quirk that happens when reading binary files (in my case a JPEG) that requires an additional flag in the open or File.open function call. I revised it to open("/path/to/file", 'rb') {|io| a = a + io.read} and all was fine.

javascript windows alert with redirect function

If you would like to redirect the user after the alert, do this:

echo ("<script LANGUAGE='JavaScript'>
          window.alert('Succesfully Updated');
          window.location.href='<URL to redirect to>';
       </script>");

How to put Google Maps V2 on a Fragment using ViewPager

For the issue of getting a NullPointerException when we change the Tabs in a FragmentTabHost you just need to add this code to your class which has the TabHost. I mean the class where you initialize the tabs. This is the code :

/**** Fix for error : Activity has been destroyed, when using Nested tabs 
 * We are actually detaching this tab fragment from the `ChildFragmentManager`
 * so that when this inner tab is viewed back then the fragment is attached again****/

import java.lang.reflect.Field;

@Override
public void onDetach() {
    super.onDetach();
    try {
        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
        childFragmentManager.setAccessible(true);
        childFragmentManager.set(this, null);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

Mysql command not found in OS X 10.7

Use these two commands in your terminal

alias mysql=/usr/local/mysql/bin/mysql
mysql --user=root -p

Then it will ask you to enter password of your user pc

Enter password:

Query to list all users of a certain group

If the DC is Win2k3 SP2 or above, you can use something like:

(&(objectCategory=user)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com))

to get the nested group membership.

Source: https://ldapwiki.com/wiki/Active%20Directory%20Group%20Related%20Searches

How to query a MS-Access Table from MS-Excel (2010) using VBA

Sub Button1_Click()
Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=C:\Documents and Settings\XXXXXX\My Documents\my_access_table.accdb"
    strSql = "SELECT Count(*) FROM mytable;"
    cn.Open strConnection
    Set rs = cn.Execute(strSql)
    MsgBox rs.Fields(0) & " rows in MyTable"

    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing

End Sub

How do you clear a stringstream variable?

This should be the most reliable way regardless of the compiler:

m=std::stringstream();

Set custom attribute using JavaScript

Please use dataset

var article = document.querySelector('#electriccars'),
    data = article.dataset;

// data.columns -> "3"
// data.indexnumber -> "12314"
// data.parent -> "cars"

so in your case for setting data:

getElementById('item1').dataset.icon = "base2.gif";

How to pass multiple parameters in a querystring

Try like this.It should work

Response.Redirect(String.Format("yourpage.aspx?strId={0}&strName={1}&strDate{2}", Server.UrlEncode(strId), Server.UrlEncode(strName),Server.UrlEncode(strDate)));

Difference between Date(dateString) and new Date(dateString)

The following format works in all browsers:

new Date("2010/08/17 12:09:36");

So, to make a yyyy-mm-dd hh:mm:ss formatted date string fully browser compatible you would have to replace dashes with slashes:

var dateString = "2010-08-17 12:09:36";
new Date(dateString.replace(/-/g, "/"));

C++ Object Instantiation

There's no reason to new (on the heap) when you can allocate on the stack (unless for some reason you've got a small stack and want to use the heap.

You might want to consider using a shared_ptr (or one of its variants) from the standard library if you do want to allocate on the heap. That'll handle doing the delete for you once all references to the shared_ptr have gone out of existance.

How to always show the vertical scrollbar in a browser?

Here is a method. This will not only provide scrollbar container, but will also show the scrollbar even if content isnt enough (as per your requirement). Would also work on Iphone, and android devices as well..

<style>
    .scrollholder {
        position: relative;
        width: 310px; height: 350px;
        overflow: auto;
        z-index: 1;
    }
</style>

<script>
    function isTouchDevice() {
        try {
            document.createEvent("TouchEvent");
            return true;
        } catch (e) {
            return false;
        }
    }

    function touchScroll(id) {
        if (isTouchDevice()) { //if touch events exist...
            var el = document.getElementById(id);
            var scrollStartPos = 0;

            document.getElementById(id).addEventListener("touchstart", function (event) {
                scrollStartPos = this.scrollTop + event.touches[0].pageY;
                event.preventDefault();
            }, false);

            document.getElementById(id).addEventListener("touchmove", function (event) {
                this.scrollTop = scrollStartPos - event.touches[0].pageY;
                event.preventDefault();
            }, false);
        }
    }
</script>

<body onload="touchScroll('scrollMe')">

    <!-- title -->
    <!-- <div class="title" onselectstart="return false">Alarms</div> -->
    <div class="scrollholder" id="scrollMe">

</div>
</body>

Android - how do I investigate an ANR?

Basic on @Horyun Lee answer, I wrote a small python script to help to investigate ANR from traces.txt.

The ANRs will output as graphics by graphviz if you have installed grapvhviz on your system.

$ ./anr.py --format png ./traces.txt

A png will output like below if there are ANRs detected in file traces.txt. It's more intuitive.

enter image description here

The sample traces.txt file used above was get from here.

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

Just save the string to a temp variable and then use that in your expression:

var strItem = item.Key.ToString();

IQueryable<entity> pages = from p in context.pages
                           where  p.Serial == strItem
                           select p;

The problem arises because ToString() isn't really executed, it is turned into a MethodGroup and then parsed and translated to SQL. Since there is no ToString() equivalent, the expression fails.

Note:

Make sure you also check out Alex's answer regarding the SqlFunctions helper class that was added later. In many cases it can eliminate the need for the temporary variable.

How to get all enum values in Java?

... or MyEnum.values() ? Or am I missing something?

How can I find the location of origin/master in git, and how do I change it?

1. Find out where Git thinks 'origin/master' is using git-remote

git remote show origin

..which will return something like..

* remote origin
  URL: [email protected]:~/something.git
  Remote branch merged with 'git pull' while on branch master
    master
  Tracked remote branch
    master

A remote is basically a link to a remote repository. When you do..

git remote add unfuddle [email protected]/myrepo.git
git push unfuddle

..git will push changes to that address you added. It's like a bookmark, for remote repositories.

When you run git status, it checks if the remote is missing commits (compared to your local repository), and if so, by how many commits. If you push all your changes to "origin", both will be in sync, so you wont get that message.

2. If it's somewhere else, how do I turn my laptop into the 'origin/master'?

There is no point in doing this. Say "origin" is renamed to "laptop" - you never want to do git push laptop from your laptop.

If you want to remove the origin remote, you do..

git remote rm origin

This wont delete anything (in terms of file-content/revisions-history). This will stop the "your branch is ahead by.." message, as it will no longer compare your repository with the remote (because it's gone!)

One thing to remember is that there is nothing special about origin, it's just a default name git uses.

Git does use origin by default when you do things like git push or git pull. So, if you have a remote you use a lot (Unfuddle, in your case), I would recommend adding unfuddle as "origin":

git remote rm origin
git remote add origin [email protected]:subdomain/abbreviation.git

or do the above in one command using set-url:

git remote set-url origin [email protected]:subdomain/abbreviation.git

Then you can simply do git push or git pull to update, instead of git push unfuddle master

Google Maps: how to get country, state/province/region, city given a lat/long value?

Better make the google object convert as a javascript readable object first.

Create two functions like below and call it passing google map return object.

function getShortAddressObject(object) {
             let address = {};
             const address_components = object[0].address_components;
             address_components.forEach(element => {
                 address[element.types[0]] = element.short_name;
             });
             return address;
 }

 function getLongAddressObject(object) {
             let address = {};
             const address_components = object[0].address_components;
             address_components.forEach(element => {
                 address[element.types[0]] = element.long_name;
             });
             return address;
 }

Then user can access names like below.

var addressObj = getLongAddressObject(object);
var country = addressObj.country; //Sri Lanka

All address parts are like below.

administrative_area_level_1: "Western Province"
administrative_area_level_2: "Colombo"
country: "Sri Lanka"
locality: "xxxx xxxxx"
political: "xxxxx"
route: "xxxxx - xxxxx Road"
street_number: "No:00000"

Update OpenSSL on OS X with Homebrew

In a terminal, run:

export PATH=/usr/local/bin:$PATH
brew link --force openssl

You may have to unlink openssl first if you get a warning: brew unlink openssl

This ensures we're linking the correct openssl for this situation. (and doesn't mess with .profile)

Hat tip to @Olaf's answer and @Felipe's comment. Some people - such as myself - may have some pretty messed up PATH vars.

How to add app icon within phonegap projects?

FAQ: ICON / SPLASH SCREEN (Cordova 5.x / 2015)

I present my answer as a general FAQ that may help you to solve many problems I've encountered while dealing with icons/splash screens. You may find out like me that the documentation is not always very clear nor up to date. This will probably go to StackOverflow documentation when available.

First: answering the question

How can I add custom app icons for iOS and Android with phonegap?

In your version of Cordova the icon tag is useless. It is not even documented in Cordova 3.0.0. You should use the documentation version that fits the cli you are using and not the latest one!

The icon tag does not work for Android at all before the version 3.5.0 according to what I can see in the different versions of the documentation. In 3.4.0 they still advice to manually copy the files

In newer versions: your config.xml looks better for newer Cordova versions. However there are still many things you may want to know. If you decide to upgrade here are some useful things to modify:

  • You don't need the gap: namespace
  • You need <preference name="SplashScreen" value="screen" /> for Android

Here are more details of the questions you might ask yourself when trying to deal with icons and splash screen:

Can I use an old version of Cordova / Phonegap

No, the icon/splashscreen feature was not in former versions of Cordova so you must use a recent version. In former versions, only Phonegap Build did handle the icons/splash screen so building locally and handling icons was only possible with a hook. I don't know the minimum version to use this feature but with 5.1.1 it works fine in both Cordova/Phonegap cli. With Cordova 3.5 it didn't work for me.

Edit: for Android you must use at least 3.5.0

How can I debug the build process about icons?

The cli use a CP command. If you provide an invalid icon path, it will show a cp error:

sebastien@sebastien-xps:cordova (dev *+$%)$ cordova run android --device
cp: no such file or directory: /home/sebastien/Desktop/Stample-react/cordova/res/www/stample_splash.png

Edit: you have use cordova build <platform> --verbose to get logs of cp command usage to see where your icons gets copied

The icons should go in a folder according to the config. For me it goes in many subfolders in : platforms/android/build/intermediates/res/armv7/debug/drawable-hdpi-v4/icon.png

Then you can find the APK, and open it as a zip archive to check the icons are present. They must be in a res/drawable* folder because it's a special folder for Android.

Where should I put the icons/splash screens in my project?

In many examples you will find the icons/splash screens are declared inside a res folder. This res is a special Android folder in the output APK, but it does not mean you have to use a res folder in your project.

You can put your icon anywhere, but the path you use must be relative to the root of the project, and not www so take care! This is documented, but not clearly because all the examples are using res and you don't know where this folder is :(

I mean if you put the icon in www/icon.png you absolutly must include www in your path.

Edit Mars 2016: after upgrading my versions, now it seems that icons are relative to www folder but documentation has not been changed (issue)

Does <icon src="icon.png"/> work?

No it does not!.

On Android, it seems it used to work before (when the density attribute was not supported yet?) but not anymore. See this Cordova issue

On iOS, it seems using this global declaration may override more specific declarations so take care and build with --verbose to ensure everything works as expected.

Can I use the same icon/splash screen file for all the densities.

Yes you can. You can even use the same file for both the icon, and splash screen (just to test!). I have used a "big" icon file of 65kb without any problem.

What's the difference when using the platform tag vs the platform attribute

<icon src="icon.png" platform="android" density="ldpi" />

is the same as

<platform name="android">
    <icon src="www/stample_icon.png" density="ldpi" />
</platform>

Should I use the gap: namespace if using Phonegap?

In my experience new versions of Phonegap or Cordova are both able to understand icon declarations without using any gap: xml namespace.

However I'm still waiting for a valid answer here: cordova/phonegap plugin add VS config.xml

As far as I understand, some features with the gap: namespace may be available earlier in PhonegapBuild, then in Phonegap and then being ported to Cordova (?)

Is <preference name="SplashScreen" value="screen" /> required?

At least for Android yes it is. I opened an issue with additional explainations.

Does icon declaration order matters?

Yes it does! It may not have any impact on Android but it has on iOS according to my tests. This is unexpected and undocumented behavior so I opened another issue.

Do I need cordova-plugin-splashscreen?

Yes this is absolutly required if you want the splash screen to work. The documentation is not clear (issue) and let us think that the plugin is required only to offer a splash screen javascript API.

How can I resize the images for all width/height/densities fastly

There are tools to help you do that. The best one for me is http://makeappicon.com/ but it requires to provide an email address.

Other possible solutions are:

Can you give me an example config?

Yes. Here's my real config.xml

<?xml version='1.0' encoding='utf-8'?>
<widget id="co.x" version="0.2.6" xmlns="http://www.w3.org/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>x</name>
    <description>
        x
    </description>
    <author email="[email protected]" href="https://x.co">
        x
    </author>
    <content src="index.html" />
    <preference name="permissions"                  value="none" />
    <preference name="webviewbounce"                value="false" />
    <preference name="StatusBarOverlaysWebView"     value="false" />
    <preference name="StatusBarBackgroundColor"     value="#0177C6" />
    <preference name="detect-data-types"            value="true" />
    <preference name="stay-in-webview"              value="false" />
    <preference name="android-minSdkVersion"        value="14" />
    <preference name="android-targetSdkVersion"     value="22" />
    <preference name="phonegap-version"             value="cli-5.1.1" />

    <preference name="SplashScreenDelay"            value="10000" />
    <preference name="SplashScreen"                 value="screen" />


    <plugin name="cordova-plugin-device"                spec="1.0.1" />
    <plugin name="cordova-plugin-console"               spec="1.0.1" />
    <plugin name="cordova-plugin-whitelist"             spec="1.1.0" />
    <plugin name="cordova-plugin-crosswalk-webview"     spec="1.2.0" />
    <plugin name="cordova-plugin-statusbar"             spec="1.0.1" />
    <plugin name="cordova-plugin-screen-orientation"    spec="1.3.6" />
    <plugin name="cordova-plugin-splashscreen"          spec="2.1.0" />

    <access origin="http://*" />
    <access origin="https://*" />

    <access launch-external="yes" origin="tel:*" />
    <access launch-external="yes" origin="geo:*" />
    <access launch-external="yes" origin="mailto:*" />
    <access launch-external="yes" origin="sms:*" />
    <access launch-external="yes" origin="market:*" />

    <platform name="android">
        <icon src="www/stample_icon.png" density="ldpi" />
        <icon src="www/stample_icon.png" density="mdpi" />
        <icon src="www/stample_icon.png" density="hdpi" />
        <icon src="www/stample_icon.png" density="xhdpi" />
        <icon src="www/stample_icon.png" density="xxhdpi" />
        <icon src="www/stample_icon.png" density="xxxhdpi" />
        <splash src="www/stample_splash.png" density="land-hdpi"/>
        <splash src="www/stample_splash.png" density="land-ldpi"/>
        <splash src="www/stample_splash.png" density="land-mdpi"/>
        <splash src="www/stample_splash.png" density="land-xhdpi"/>
        <splash src="www/stample_splash.png" density="land-xhdpi"/>
        <splash src="www/stample_splash.png" density="land-xhdpi"/>
        <splash src="www/stample_splash.png" density="port-hdpi"/>
        <splash src="www/stample_splash.png" density="port-ldpi"/>
        <splash src="www/stample_splash.png" density="port-mdpi"/>
        <splash src="www/stample_splash.png" density="port-xhdpi"/>
        <splash src="www/stample_splash.png" density="port-xxhdpi"/>
        <splash src="www/stample_splash.png" density="port-xxxhdpi"/>
    </platform>

    <platform name="ios">
        <icon src="www/stample_icon.png" width="180" height="180" />
        <icon src="www/stample_icon.png" width="60" height="60" />
        <icon src="www/stample_icon.png" width="120" height="120" />
        <icon src="www/stample_icon.png" width="76" height="76" />
        <icon src="www/stample_icon.png" width="152" height="152" />
        <icon src="www/stample_icon.png" width="40" height="40" />
        <icon src="www/stample_icon.png" width="80" height="80" />
        <icon src="www/stample_icon.png" width="57" height="57" />
        <icon src="www/stample_icon.png" width="114" height="114" />
        <icon src="www/stample_icon.png" width="72" height="72" />
        <icon src="www/stample_icon.png" width="144" height="144" />
        <icon src="www/stample_icon.png" width="29" height="29" />
        <icon src="www/stample_icon.png" width="58" height="58" />
        <icon src="www/stample_icon.png" width="50" height="50" />
        <icon src="www/stample_icon.png" width="100" height="100" />
        <splash src="www/stample_splash.png" width="320" height="480"/>
        <splash src="www/stample_splash.png" width="640" height="960"/>
        <splash src="www/stample_splash.png" width="768" height="1024"/>
        <splash src="www/stample_splash.png" width="1536" height="2048"/>
        <splash src="www/stample_splash.png" width="1024" height="768"/>
        <splash src="www/stample_splash.png" width="2048" height="1536"/>
        <splash src="www/stample_splash.png" width="640" height="1136"/>
        <splash src="www/stample_splash.png" width="750" height="1334"/>
        <splash src="www/stample_splash.png" width="1242" height="2208"/>
        <splash src="www/stample_splash.png" width="2208" height="1242"/>
    </platform>

    <allow-intent href="*" />
    <engine name="browser" spec="^3.6.0" />
    <engine name="android" spec="^4.0.2" />
</widget>

A good source of examples are starter kits. Like phonegap-start or Ionic starter

How can I escape double quotes in XML attributes values?

The String conversion page on the Coder's Toolbox site is handy for encoding more than a small amount of HTML or XML code for inclusion as a value in an XML element.

Is there any way to install Composer globally on Windows?

Unfortunately, all the good answers here didn't work for me. So after installing composer on windows 10, I just had to set system variable in environment variables and it worked.

Windows 10 environment variable -> system variables

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

I agree with bizl

[XmlInclude(typeof(ParentOfTheItem))]
[Serializable]
public abstract class WarningsType{ }

also if you need to apply this included class to an object item you can do like that

[System.Xml.Serialization.XmlElementAttribute("Warnings", typeof(WarningsType))]
public object[] Items
{
    get
    {
        return this.itemsField;
    }
    set
    {
        this.itemsField = value;
    }
}

show dbs gives "Not Authorized to execute command" error

one more, after you create user by following cmd-1, please assign read/write/root role to the user by cmd-2. then restart mongodb by cmd "mongod --auth".

The benefit of assign role to the user is you can do read/write operation by mongo shell or python/java and so on, otherwise you will meet "pymongo.errors.OperationFailure: not authorized" when you try to read/write your db.

cmd-1:

use admin
db.createUser({
  user: "newUsername",
  pwd: "password",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})

cmd-2:

db.grantRolesToUser('newUsername',[{ role: "root", db: "admin" }])

Build and Install unsigned apk on device without the development server?

As of react-native 0.57, none of the previously provided answers will work anymore, as the directories in which gradle expects to find the bundle and the assets have changed.

Simple way without react-native bundle

The simplest way to build a debug build is without using the react-native bundle command at all, but by simply modifying your app/build.gradle file.

Inside the project.ext.react map in the app/build.gradle file, add the bundleInDebug: true entry. If you want it to not be a --dev build (no warnings and minified bundle) then you should also add the devDisabledInDebug: true entry to the same map.

With react-native bundle

If for some reason you need to or want to use the react-native bundle command to create the bundle and then the ./gradlew assembleDebug to create the APK with the bundle and the assets you have to make sure to put the bundle and the assets in the correct paths, where gradle can find them.

As of react-native 0.57 those paths are android/app/build/generated/assets/react/debug/index.android.js for the bundle

and android/app/build/generated/res/react/debug for the assets. So the full commands for manually bundling and building the APK with the bundle and assets are:

react-native bundle --dev false --platform android --entry-file index.js --bundle-output ./android/app/build/generated/assets/react/debug/index.android.bundle --assets-dest ./android/app/build/res/react/debug

and then

./gradlew assembleDebug

Bundle and assets path

Note that that paths where gradle looks for the bundle and the assets might be subject to change. To find out where those paths are, look at the react.gradle file in your node_modules/react-native directory. The lines starting with def jsBundleDir = and def resourcesDir = specify the directories where gradle looks for the bundle and the assets respectively.

How to get the last character of a string in a shell?

That's one of the reasons why you need to quote your variables:

echo "${str:$i:1}"

Otherwise, bash expands the variable and in this case does globbing before printing out. It is also better to quote the parameter to the script (in case you have a matching filename):

sh lash_ch.sh 'abcde*'

Also see the order of expansions in the bash reference manual. Variables are expanded before the filename expansion.

To get the last character you should just use -1 as the index since the negative indices count from the end of the string:

echo "${str: -1}"

The space after the colon (:) is REQUIRED.

This approach will not work without the space.

Input type DateTime - Value format?

This works for setting the value of the INPUT:

strftime('%Y-%m-%dT%H:%M:%S', time())

HTML5 Dynamically create Canvas

 <html>
 <head></head>
 <body>
 <canvas id="canvas" width="300" height="300"></canvas>
 <script>
  var sun = new Image();
  var moon = new Image();
  var earth = new Image();
  function init() {
  sun.src = 'https://mdn.mozillademos.org/files/1456/Canvas_sun.png';
  moon.src = 'https://mdn.mozillademos.org/files/1443/Canvas_moon.png';
  earth.src = 'https://mdn.mozillademos.org/files/1429/Canvas_earth.png';
  window.requestAnimationFrame(draw);
  }

  function draw() {
  var ctx = document.getElementById('canvas').getContext('2d');

  ctx.globalCompositeOperation = 'destination-over';
  ctx.clearRect(0, 0, 300, 300);

  ctx.fillStyle = 'rgba(0, 0, 0, 0.4)';
  ctx.strokeStyle = 'rgba(0, 153, 255, 0.4)';
  ctx.save();
  ctx.translate(150, 150);

  // Earth
  var time = new Date();
  ctx.rotate(((2 * Math.PI) / 60) * time.getSeconds() + ((2 * Math.PI) / 60000) * 
  time.getMilliseconds());
  ctx.translate(105, 0);
  ctx.fillRect(10, -19, 55, 31); 
  ctx.drawImage(earth, -12, -12);

   // Moon
  ctx.save();
  ctx.rotate(((2 * Math.PI) / 6) * time.getSeconds() + ((2 * Math.PI) / 6000) * 
  time.getMilliseconds());
  ctx.translate(0, 28.5);
  ctx.drawImage(moon, -3.5, -3.5);
  ctx.restore();

  ctx.restore();

   ctx.beginPath();
   ctx.arc(150, 150, 105, 0, Math.PI * 2, false);
   ctx.stroke();

   ctx.drawImage(sun, 0, 0, 300, 300);

   window.requestAnimationFrame(draw);
    }

   init();
   </script>
   </body>
   </html>

How do I get the last word in each line with bash

tldr;

$ awk '{print $NF}' file.txt | paste -sd, | sed 's/,/, /g'

For a file like this

$ cat file.txt
The quick brown fox
jumps over
the lazy dog.

the given command will print

fox, over, dog.

How it works:

  • awk '{print $NF}' : prints the last field of every line
  • paste -sd, : reads stdin serially (-s, one file at a time) and writes fields comma-delimited (-d,)
  • sed 's/,/, /g' : substitutes "," with ", " globally (for all instances)

References:

List all indexes on ElasticSearch server?

Try

curl 'localhost:9200/_cat/indices?v'

It will give you following self explanatory output in a tabular manner

health index    pri rep docs.count docs.deleted store.size pri.store.size
yellow customer   5   1          0            0       495b           495b

IPython Notebook save location

To add to Victor's answer, I was able to change the save directory on Windows using...

c.NotebookApp.notebook_dir = 'C:\\Users\\User\\Folder'

How to create an exit message

The abort function does this. For example:

abort("Message goes here")

Note: the abort message will be written to STDERR as opposed to puts which will write to STDOUT.

Using Django time/date widgets in custom form

For Django >= 2.0

Note: Using admin widgets for date-time fields is not a good idea as admin style-sheets can conflict with your site style-sheets in case you are using bootstrap or any other CSS frameworks. If you are building your site on bootstrap use my bootstrap-datepicker widget django-bootstrap-datepicker-plus.

Step 1: Add javascript-catalog URL to your project's (not app's) urls.py file.

from django.views.i18n import JavaScriptCatalog

urlpatterns = [
    path('jsi18n', JavaScriptCatalog.as_view(), name='javascript-catalog'),
]

Step 2: Add required JavaScript/CSS resources to your template.

<script type="text/javascript" src="{% url 'javascript-catalog' %}"></script>
<script type="text/javascript" src="{% static '/admin/js/core.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static '/admin/css/widgets.css' %}">
<style>.calendar>table>caption{caption-side:unset}</style><!--caption fix for bootstrap4-->
{{ form.media }}        {# Form required JS and CSS #}

Step 3: Use admin widgets for date-time input fields in your forms.py.

from django.contrib.admin import widgets
from .models import Product

class ProductCreateForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ['name', 'publish_date', 'publish_time', 'publish_datetime']
        widgets = {
            'publish_date': widgets.AdminDateWidget,
            'publish_time': widgets.AdminTimeWidget,
            'publish_datetime': widgets.AdminSplitDateTime,
        }

Find unused code

Resharper is good for this like others have stated. Be careful though, these tools don't find you code that is used by reflection, e.g. cannot know if some code is NOT used by reflection.

How to properly compare two Integers in Java?

Because comparaison method have to be done based on type int (x==y) or class Integer (x.equals(y)) with right operator

public class Example {

    public static void main(String[] args) {
     int[] arr = {-32735, -32735, -32700, -32645, -32645, -32560, -32560};

        for(int j=1; j<arr.length-1; j++)
            if((arr[j-1]!=arr[j]) && (arr[j]!=arr[j+1])) 
                System.out.println("int>"+arr[j]);


    Integer[] I_arr = {-32735, -32735, -32700, -32645, -32645, -32560, -32560};

        for(int j=1; j<I_arr.length-1; j++)
            if((!I_arr[j-1].equals(I_arr[j])) && (!I_arr[j].equals(I_arr[j+1]))) 
                System.out.println("Interger>"+I_arr[j]);
    }
}

Can I recover a branch after its deletion in Git?

Yes, you should be able to do git reflog --no-abbrev and find the SHA1 for the commit at the tip of your deleted branch, then just git checkout [sha]. And once you're at that commit, you can just git checkout -b [branchname] to recreate the branch from there.


Credit to @Cascabel for this condensed/one-liner version and @Snowcrash for how to obtain the sha.

If you've just deleted the branch you'll see something like this in your terminal Deleted branch <your-branch> (was <sha>). Then just use that <sha> in this one-liner:

git checkout -b <your-branch> <sha>

MessageBodyWriter not found for media type=application/json

Uncommenting the below code helped

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
</dependency>

which was present in pom.xml in my maven based project resolved this error for me.

syntax error near unexpected token `('

Since you've got both the shell that you're typing into and the shell that sudo -s runs, you need to quote or escape twice. (EDITED fixed quoting)

sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'

or

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)

Out of curiosity, why do you need -s? Can't you just do this:

sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

Console app arguments, how arguments are passed to Main method

Read MSDN.

it also contains a link to the args.

short answer: no, the main does not get override. when visual studio (actually the compiler) builds your exe it must declare a starting point for the assmebly, that point is the main function.

if you meant how to literary pass args then you can either run you're app from the command line with them (e.g. appname.exe param1 param2) or in the project setup, enter them (in the command line arguments in the Debug tab)

in the main you will need to read those args for example:

for (int i = 0; i < args.Length; i++)
{
    string flag = args.GetValue(i).ToString();
    if (flag == "bla") 
    {
        Bla();
    }
}

Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

Arrrgh! Faced this on macOS today and the issue was as simple as - the pop-up window suggesting to install the new Appium version was showing on the remote CI build server.

Just VNC'ing to it and clicking "Install later" fixed it.

Different ways of clearing lists

It appears to me that del will give you the memory back, while assigning a new list will make the old one be deleted only when the gc runs.matter.

This may be useful for large lists, but for small list it should be negligible.

Edit: As Algorias, it doesn't matter.

Note that

del old_list[ 0:len(old_list) ]

is equivalent to

del old_list[:]

ASP.NET GridView RowIndex As CommandArgument

<asp:LinkButton ID="LnkBtn" runat="server" Text="Text" RowIndex='<%# Container.DisplayIndex %>' CommandArgument='<%# Eval("??") %>' OnClick="LnkBtn_Click" />

inside your event handler :

Protected Sub LnkBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
  dim rowIndex as integer = sender.Attributes("RowIndex")
  'Here you can use also the command argument for any other value.
End Sub

How to dump only specific tables from MySQL?

If you're in local machine then use this command

/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

For remote machine, use below one

/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

Importing a csv into mysql via command line

I know this says command line, but just a tidbit of something quick to try that might work, if you've got MySQL workbench and the csv isn't too large, you can simply

  • SELECT * FROM table
  • Copy entire CSV
  • Paste csv into the query results section of Workbench
  • Hope for the best

I say hope for the best because this is MySQL Workbench. You never know when it's going to explode


If you want to do this on a remote server, you would do

mysql -h<server|ip> -u<username> -p --local-infile bark -e "LOAD DATA LOCAL INFILE '<filename.csv>'  INTO TABLE <table>  FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'"

Note, I didn't put a password after -p as putting one on the command line is considered bad practice

Set session variable in laravel

In Laravel 5.6, you will need to set it as

  session(['variableName'=>$value]);

To retrieve it is as simple as

$variableName = session('variableName')

Convert an image to grayscale in HTML/CSS

For people who are asking about the ignored IE10+ support in other answers, checkout this piece of CSS:

img.grayscale:hover {
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
}

svg {
    background:url(http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s400/a2cf7051-5952-4b39-aca3-4481976cb242.jpg);
}

svg image:hover {
    opacity: 0;
}

Applied on this markup:

<!DOCTYPE HTML>
<html>
<head>

    <title>Grayscaling in Internet Explorer 10+</title>

</head>
<body>

    <p>IE10 with inline SVG</p>
    <svg xmlns="http://www.w3.org/2000/svg" id="svgroot" viewBox="0 0 400 377" width="400" height="377">
      <defs>
         <filter id="filtersPicture">
           <feComposite result="inputTo_38" in="SourceGraphic" in2="SourceGraphic" operator="arithmetic" k1="0" k2="1" k3="0" k4="0" />
           <feColorMatrix id="filter_38" type="saturate" values="0" data-filterid="38" />
        </filter>
      </defs>
      <image filter="url(&quot;#filtersPicture&quot;)" x="0" y="0" width="400" height="377" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s1600/a2cf7051-5952-4b39-aca3-4481976cb242.jpg" />
    </svg>

</body>
</html>

For more demos, checkout IE testdrive's CSS3 Graphics section and this old IE blog http://blogs.msdn.com/b/ie/archive/2011/10/14/svg-filter-effects-in-ie10.aspx

Finding the handle to a WPF window

If you want window handles for ALL of your application's Windows for some reason, you can use the Application.Windows property to get at all the Windows and then use WindowInteropHandler to get at their handles as you have already demonstrated.

hibernate: LazyInitializationException: could not initialize proxy

Okay, finally figured out where I was remiss. I was under the mistaken notion that I should wrap each DAO method in a transaction. Terribly wrong! I've learned my lesson. I've hauled all the transaction code from all the DAO methods and have set up transactions strictly at the application/manager layer. This has totally solved all my problems. Data is properly lazy loaded as I need it, wrapped up and closed down once I do the commit.

Life is goodly... :)

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Expand YourModel.edmx file and open YourModel.Context.cs class under YourModel.Context.tt.

I added the following line in the using section and the error was fixed for me.

using SqlProviderServices = System.Data.Entity.SqlServer.SqlProviderServices;

You may have to add this line to the file each time the file is auto generated.

Maven: mvn command not found

  1. Run 'path' in command prompt and ensure that the maven installation directory is listed.
  2. Ensure the maven is installed in 'C:\Program Files\Maven'.

Possible to make labels appear when hovering over a point in matplotlib?

The other answers did not address my need for properly showing tooltips in a recent version of Jupyter inline matplotlib figure. This one works though:

import matplotlib.pyplot as plt
import numpy as np
import mplcursors
np.random.seed(42)

fig, ax = plt.subplots()
ax.scatter(*np.random.random((2, 26)))
ax.set_title("Mouse over a point")
crs = mplcursors.cursor(ax,hover=True)

crs.connect("add", lambda sel: sel.annotation.set_text(
    'Point {},{}'.format(sel.target[0], sel.target[1])))
plt.show()

Leading to something like the following picture when going over a point with mouse: enter image description here

mongo - couldn't connect to server 127.0.0.1:27017

Resolved.

This problem could be solved by the below mentioned 4 steps

1) Remove .lock file

sudo rm /var/lib/mongodb/mongod.lock 

2) repair the mongodb

mongod -–repair

3) start the mongod server

sudo service mongod start 

4) start the mongo client

mongo

For more details take a look at http://shakthydoss.com/error-couldnt-connect-to-server-127-0-0-127017-srcmongoshellmongo-js-exception-connect-failed/

http://shakthydoss.com/technical/error-couldnt-connect-to-server-127-0-0-127017-srcmongoshellmongo-js-exception-connect-failed/

spring data jpa @query and pageable

You can use pagination with a native query. It is documented here: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#_native_queries

"You can however use native queries for pagination by specifying the count query yourself: Example 59. Declare native count queries for pagination at the query method using @Query"

public interface UserRepository extends JpaRepository<User, Long> {

  @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
    countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
    nativeQuery = true)
  Page<User> findByLastname(String lastname, Pageable pageable);
}

How to create a GUID/UUID in Python

If you need to pass UUID for a primary key for your model or unique field then below code returns the UUID object -

 import uuid
 uuid.uuid4()

If you need to pass UUID as a parameter for URL you can do like below code -

import uuid
str(uuid.uuid4())

If you want the hex value for a UUID you can do the below one -

import uuid    
uuid.uuid4().hex

Express.js - app.listen vs server.listen

I came with same question but after google, I found there is no big difference :)

From Github

If you wish to create both an HTTP and HTTPS server you may do so with the "http" and "https" modules as shown here.

/**
 * Listen for connections.
 *
 * A node `http.Server` is returned, with this
 * application (which is a `Function`) as its
 * callback. If you wish to create both an HTTP
 * and HTTPS server you may do so with the "http"
 * and "https" modules as shown here:
 *
 *    var http = require('http')
 *      , https = require('https')
 *      , express = require('express')
 *      , app = express();
 *
 *    http.createServer(app).listen(80);
 *    https.createServer({ ... }, app).listen(443);
 *
 * @return {http.Server}
 * @api public
 */

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

Also if you want to work with socket.io see their example

See this

I prefer app.listen() :)

WPF MVVM: How to close a window

I use the Publish Subscribe pattern for complicated class-dependencies:

ViewModel:

    public class ViewModel : ViewModelBase
    {
        public ViewModel()
        {
            CloseComand = new DelegateCommand((obj) =>
                {
                    MessageBus.Instance.Publish(Messages.REQUEST_DEPLOYMENT_SETTINGS_CLOSED, null);
                });
        }
}

Window:

public partial class SomeWindow : Window
{
    Subscription _subscription = new Subscription();

    public SomeWindow()
    {
        InitializeComponent();

        _subscription.Subscribe(Messages.REQUEST_DEPLOYMENT_SETTINGS_CLOSED, obj =>
            {
                this.Close();
            });
    }
}

You can leverage Bizmonger.Patterns to get the MessageBus.

MessageBus

public class MessageBus
{
    #region Singleton
    static MessageBus _messageBus = null;
    private MessageBus() { }

    public static MessageBus Instance
    {
        get
        {
            if (_messageBus == null)
            {
                _messageBus = new MessageBus();
            }

            return _messageBus;
        }
    }
    #endregion

    #region Members
    List<Observer> _observers = new List<Observer>();
    List<Observer> _oneTimeObservers = new List<Observer>();
    List<Observer> _waitingSubscribers = new List<Observer>();
    List<Observer> _waitingUnsubscribers = new List<Observer>();

    int _publishingCount = 0;
    #endregion

    public void Subscribe(string message, Action<object> response)
    {
        Subscribe(message, response, _observers);
    }

    public void SubscribeFirstPublication(string message, Action<object> response)
    {
        Subscribe(message, response, _oneTimeObservers);
    }

    public int Unsubscribe(string message, Action<object> response)
    {
        var observers = new List<Observer>(_observers.Where(o => o.Respond == response).ToList());
        observers.AddRange(_waitingSubscribers.Where(o => o.Respond == response));
        observers.AddRange(_oneTimeObservers.Where(o => o.Respond == response));

        if (_publishingCount == 0)
        {
            observers.ForEach(o => _observers.Remove(o));
        }

        else
        {
            _waitingUnsubscribers.AddRange(observers);
        }

        return observers.Count;
    }

    public int Unsubscribe(string subscription)
    {
        var observers = new List<Observer>(_observers.Where(o => o.Subscription == subscription).ToList());
        observers.AddRange(_waitingSubscribers.Where(o => o.Subscription == subscription));
        observers.AddRange(_oneTimeObservers.Where(o => o.Subscription == subscription));

        if (_publishingCount == 0)
        {
            observers.ForEach(o => _observers.Remove(o));
        }

        else
        {
            _waitingUnsubscribers.AddRange(observers);
        }

        return observers.Count;
    }

    public void Publish(string message, object payload)
    {
        _publishingCount++;

        Publish(_observers, message, payload);
        Publish(_oneTimeObservers, message, payload);
        Publish(_waitingSubscribers, message, payload);

        _oneTimeObservers.RemoveAll(o => o.Subscription == message);
        _waitingUnsubscribers.Clear();

        _publishingCount--;
    }

    private void Publish(List<Observer> observers, string message, object payload)
    {
        Debug.Assert(_publishingCount >= 0);

        var subscribers = observers.Where(o => o.Subscription.ToLower() == message.ToLower());

        foreach (var subscriber in subscribers)
        {
            subscriber.Respond(payload);
        }
    }

    public IEnumerable<Observer> GetObservers(string subscription)
    {
        var observers = new List<Observer>(_observers.Where(o => o.Subscription == subscription));
        return observers;
    }

    public void Clear()
    {
        _observers.Clear();
        _oneTimeObservers.Clear();
    }

    #region Helpers
    private void Subscribe(string message, Action<object> response, List<Observer> observers)
    {
        Debug.Assert(_publishingCount >= 0);

        var observer = new Observer() { Subscription = message, Respond = response };

        if (_publishingCount == 0)
        {
            observers.Add(observer);
        }
        else
        {
            _waitingSubscribers.Add(observer);
        }
    }
    #endregion
}

}

Subscription

public class Subscription
{
    #region Members
    List<Observer> _observerList = new List<Observer>();
    #endregion

    public void Unsubscribe(string subscription)
    {
        var observers = _observerList.Where(o => o.Subscription == subscription);

        foreach (var observer in observers)
        {
            MessageBus.Instance.Unsubscribe(observer.Subscription, observer.Respond);
        }

        _observerList.Where(o => o.Subscription == subscription).ToList().ForEach(o => _observerList.Remove(o));
    }

    public void Subscribe(string subscription, Action<object> response)
    {
        MessageBus.Instance.Subscribe(subscription, response);
        _observerList.Add(new Observer() { Subscription = subscription, Respond = response });
    }

    public void SubscribeFirstPublication(string subscription, Action<object> response)
    {
        MessageBus.Instance.SubscribeFirstPublication(subscription, response);
    }
}

Why does Java have transient fields?

As per google transient meaning == lasting only for a short time; impermanent.

Now if you want to make anything transient in java use transient keyword.

Q: where to use transient?

A: Generally in java we can save data to files by acquiring them in variables and writing those variables to files, this process is known as Serialization. Now if we want to avoid variable data to be written to file, we would make that variable as transient.

transient int result=10;

Note: transient variables cannot be local.

CSS: Set a background color which is 50% of the width of the window

Simple solution to achieve "split in two" background:

background: linear-gradient(to left, #ff0000 50%, #0000ff 50%);

You can also use degrees as direction

background: linear-gradient(80deg, #ff0000 50%, #0000ff 50%);

Working with time DURATION, not time of day

The custom format hh:mm only shows the number of hours correctly up to 23:59, after that, you get the remainder, less full days. For example, 48 hours would be displayed as 00:00, even though the underlaying value is correct.

To correctly display duration in hours and seconds (below or beyond a full day), you should use the custom format [h]:mm;@ In this case, 48 hours would be displayed as 48:00.

Cheers.

How to read line by line or a whole text file at once?

You can use std::getline :

#include <fstream>
#include <string>

int main() 
{ 
    std::ifstream file("Read.txt");
    std::string str; 
    while (std::getline(file, str))
    {
        // Process str
    }
}

Also note that it's better you just construct the file stream with the file names in it's constructor rather than explicitly opening (same goes for closing, just let the destructor do the work).

Further documentation about std::string::getline() can be read at CPP Reference.

Probably the easiest way to read a whole text file is just to concatenate those retrieved lines.

std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
  file_contents += str;
  file_contents.push_back('\n');
}  

C# equivalent of C++ vector, with contiguous memory?

You could use a List<T> and when T is a value type it will be allocated in contiguous memory which would not be the case if T is a reference type.

Example:

List<int> integers = new List<int>();
integers.Add(1);
integers.Add(4);
integers.Add(7);

int someElement = integers[1];

How do I pass options to the Selenium Chrome driver using Python?

Found the chrome Options class in the Selenium source code.

Usage to create a Chrome driver instance:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=chrome_options)

installing urllib in Python3.6

This happens because your local module named urllib.py shadows the installed requests module you are trying to use. The current directory is preapended to sys.path, so the local name takes precedence over the installed name.

An extra debugging tip when this comes up is to look at the Traceback carefully, and realize that the name of your script in question is matching the module you are trying to import.

Rename your file to something else like url.py. Then It is working fine. Hope it helps!

How do I generate random numbers in Dart?

its worked for me new Random().nextInt(100); // MAX = number

it will give 0 to 99 random number

Eample::

import 'dart:math';
int MAX = 100;
print(new Random().nextInt(MAX));`

Cause of No suitable driver found for

great I had the similar problem. The advice for all is to check jdbc url sintax

Alter Table Add Column Syntax

Just remove COLUMN from ADD COLUMN

ALTER TABLE Employees
  ADD EmployeeID numeric NOT NULL IDENTITY (1, 1)

ALTER TABLE Employees ADD CONSTRAINT
        PK_Employees PRIMARY KEY CLUSTERED 
        (
          EmployeeID
        ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
        ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

What does [STAThread] do?

The STAThreadAttribute marks a thread to use the Single-Threaded COM Apartment if COM is needed. By default, .NET won't initialize COM at all. It's only when COM is needed, like when a COM object or COM Control is created or when drag 'n' drop is needed, that COM is initialized. When that happens, .NET calls the underlying CoInitializeEx function, which takes a flag indicating whether to join the thread to a multi-threaded or single-threaded apartment.

Read more info here (Archived, June 2009)

and

Why is STAThread required?

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

"Insert if not exists" statement in SQLite

insert into bookmarks (users_id, lessoninfo_id)

select 1, 167
EXCEPT
select user_id, lessoninfo_id
from bookmarks
where user_id=1
and lessoninfo_id=167;

This is the fastest way.

For some other SQL engines, you can use a Dummy table containing 1 record. e.g:

select 1, 167 from ONE_RECORD_DUMMY_TABLE