Programs & Examples On #Thread static

How can I find script's directory?

I use:

import os
import sys

def get_script_path():
    return os.path.dirname(os.path.realpath(sys.argv[0]))

As aiham points out in a comment, you can define this function in a module and use it in different scripts.

Using Git, show all commits that are in one branch, but not the other(s)

If it is one (single) branch that you need to check, for example if you want that branch 'B' is fully merged into branch 'A', you can simply do the following:

$ git checkout A
$ git branch -d B

git branch -d <branchname> has the safety that "The branch must be fully merged in HEAD."

Caution: this actually deletes the branch B if it is merged into A.

How to get unique device hardware id in Android?

Update: 19 -11-2019

The below answer is no more relevant to present day.

So for any one looking for answers you should look at the documentation linked below

https://developer.android.com/training/articles/user-data-ids


Old Answer - Not relevant now. You check this blog in the link below

http://android-developers.blogspot.in/2011/03/identifying-app-installations.html

ANDROID_ID

import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(),
                                                    Secure.ANDROID_ID); 

The above is from the link @ Is there a unique Android device ID?

More specifically, Settings.Secure.ANDROID_ID. This is a 64-bit quantity that is generated and stored when the device first boots. It is reset when the device is wiped.

ANDROID_ID seems a good choice for a unique device identifier. There are downsides: First, it is not 100% reliable on releases of Android prior to 2.2 (“Froyo”). Also, there has been at least one widely-observed bug in a popular handset from a major manufacturer, where every instance has the same ANDROID_ID.

The below solution is not a good one coz the value survives device wipes (“Factory resets”) and thus you could end up making a nasty mistake when one of your customers wipes their device and passes it on to another person.

You get the imei number of the device using the below

  TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
  telephonyManager.getDeviceId();

http://developer.android.com/reference/android/telephony/TelephonyManager.html#getDeviceId%28%29

Add this is manifest

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

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

How to sum digits of an integer in java?

without mapping ? the quicker lambda solution

Integer.toString( num ).chars().boxed().collect( Collectors.summingInt( (c) -> c - '0' ) );

…or same with the slower % operator

Integer.toString( num ).chars().boxed().collect( Collectors.summingInt( (c) -> c % '0' ) );


…or Unicode compliant

Integer.toString( num ).codePoints().boxed().collect( Collectors.summingInt( Character::getNumericValue ) );

Why isn't my Pandas 'apply' function referencing multiple columns working?

All of the suggestions above work, but if you want your computations to by more efficient, you should take advantage of numpy vector operations (as pointed out here).

import pandas as pd
import numpy as np


df = pd.DataFrame ({'a' : np.random.randn(6),
             'b' : ['foo', 'bar'] * 3,
             'c' : np.random.randn(6)})

Example 1: looping with pandas.apply():

%%timeit
def my_test2(row):
    return row['a'] % row['c']

df['Value'] = df.apply(my_test2, axis=1)

The slowest run took 7.49 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 481 µs per loop

Example 2: vectorize using pandas.apply():

%%timeit
df['a'] % df['c']

The slowest run took 458.85 times longer than the fastest. This could mean that an intermediate result is being cached. 10000 loops, best of 3: 70.9 µs per loop

Example 3: vectorize using numpy arrays:

%%timeit
df['a'].values % df['c'].values

The slowest run took 7.98 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 6.39 µs per loop

So vectorizing using numpy arrays improved the speed by almost two orders of magnitude.

Multi-threading in VBA

I was looking for something similar and the official answer is no. However, I was able to find an interesting concept by Daniel at ExcelHero.com.

Basically, you need to create worker vbscripts to execute the various things you want and have it report back to excel. For what I am doing, retrieving HTML data from various website, it works great!

Take a look:

http://www.excelhero.com/blog/2010/05/multi-threaded-vba.html

push_back vs emplace_back

Specific use case for emplace_back: If you need to create a temporary object which will then be pushed into a container, use emplace_back instead of push_back. It will create the object in-place within the container.

Notes:

  1. push_back in the above case will create a temporary object and move it into the container. However, in-place construction used for emplace_back would be more performant than constructing and then moving the object (which generally involves some copying).
  2. In general, you can use emplace_back instead of push_back in all the cases without much issue. (See exceptions)

jQuery UI Color Picker

You can find some demos and plugins here.

http://jqueryui.pbworks.com/ColorPicker

Read a zipped file as a pandas DataFrame

https://www.kaggle.com/jboysen/quick-gz-pandas-tutorial

Please follow this link.

import pandas as pd
traffic_station_df = pd.read_csv('C:\\Folders\\Jupiter_Feed.txt.gz', compression='gzip',
                                 header=1, sep='\t', quotechar='"')

#traffic_station_df['Address'] = 'address'

#traffic_station_df.append(traffic_station_df)
print(traffic_station_df)

How to access a property of an object (stdClass Object) member/element of an array?

How about something like this.

function objectToArray( $object ){
   if( !is_object( $object ) && !is_array( $object ) ){
    return $object;
 }
if( is_object( $object ) ){
    $object = get_object_vars( $object );
}
    return array_map( 'objectToArray', $object );
}

and call this function with your object

$array = objectToArray( $yourObject );

reference

How to post a file from a form with Axios

If you don't want to use a FormData object (e.g. your API takes specific content-type signatures and multipart/formdata isn't one of them) then you can do this instead:

uploadFile: function (event) {
    const file = event.target.files[0]
    axios.post('upload_file', file, {
        headers: {
          'Content-Type': file.type
        }
    })
}

How do you make strings "XML safe"?

Since PHP 5.4 you can use:

htmlspecialchars($string, ENT_XML1);

You should specify the encoding, such as:

htmlspecialchars($string, ENT_XML1, 'UTF-8');

Update

Note that the above will only convert:

  • & to &amp;
  • < to &lt;
  • > to &gt;

If you want to escape text for use in an attribute enclosed in double quotes:

htmlspecialchars($string, ENT_XML1 | ENT_COMPAT, 'UTF-8');

will convert " to &quot; in addition to &, < and >.


And if your attributes are enclosed in single quotes:

htmlspecialchars($string, ENT_XML1 | ENT_QUOTES, 'UTF-8');

will convert ' to &apos; in addition to &, <, > and ".

(Of course you can use this even outside of attributes).


See the manual entry for htmlspecialchars.

Equivalent function for DATEADD() in Oracle

Method1: ADD_MONTHS

ADD_MONTHS(SYSDATE, -6)

Method 2: Interval

SYSDATE - interval '6' month

Note: if you want to do the operations from start of the current month always, TRUNC(SYSDATE,'MONTH') would give that. And it expects a Date datatype as input.

Got a NumberFormatException while trying to parse a text file for objects

I changed Scanner fin = new Scanner(file); to Scanner fin = new Scanner(new File(file)); and it works perfectly now. I didn't think the difference mattered but there you go.

Wait for a void async method

Best practice is to mark function async void only if it is fire and forget method, if you want to await on, you should mark it as async Task.

In case if you still want to await, then wrap it like so await Task.Run(() => blah())

How to Populate a DataTable from a Stored Procedure

Use the SqlDataAdapter, this would simplify everything.

//Your code to this point
DataTable dt = new DataTable();

using(var cmd = new SqlCommand("usp_GetABCD", sqlcon))
{
  using(var da = new SqlDataAdapter(cmd))
  {
      da.Fill(dt):
  }
}

and your DataTable will have the information you are looking for, so long as your stored proceedure returns a data set (cursor).

Correct way to convert size in bytes to KB, MB, GB in JavaScript

This solution builds upon previous solutions, but takes into account both metric and binary units:

function formatBytes(bytes, decimals, binaryUnits) {
    if(bytes == 0) {
        return '0 Bytes';
    }
    var unitMultiple = (binaryUnits) ? 1024 : 1000; 
    var unitNames = (unitMultiple === 1024) ? // 1000 bytes in 1 Kilobyte (KB) or 1024 bytes for the binary version (KiB)
        ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']: 
        ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    var unitChanges = Math.floor(Math.log(bytes) / Math.log(unitMultiple));
    return parseFloat((bytes / Math.pow(unitMultiple, unitChanges)).toFixed(decimals || 0)) + ' ' + unitNames[unitChanges];
}

Examples:

formatBytes(293489203947847, 1);    // 293.5 TB
formatBytes(1234, 0);   // 1 KB
formatBytes(4534634523453678343456, 2); // 4.53 ZB
formatBytes(4534634523453678343456, 2, true));  // 3.84 ZiB
formatBytes(4566744, 1);    // 4.6 MB
formatBytes(534, 0);    // 534 Bytes
formatBytes(273403407, 0);  // 273 MB

adding noise to a signal in python

AWGN Similar to Matlab Function

def awgn(sinal):
    regsnr=54
    sigpower=sum([math.pow(abs(sinal[i]),2) for i in range(len(sinal))])
    sigpower=sigpower/len(sinal)
    noisepower=sigpower/(math.pow(10,regsnr/10))
    noise=math.sqrt(noisepower)*(np.random.uniform(-1,1,size=len(sinal)))
    return noise

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

JPQL mostly is case-insensitive. One of the things that is case-sensitive is Java entity names. Change your query to:

"SELECT r FROM FooBar r"

Iterating through map in template

As Herman pointed out, you can get the index and element from each iteration.

{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}

Working example:

package main

import (
    "html/template"
    "os"
)

type EntetiesClass struct {
    Name string
    Value int32
}

// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`

func main() {
    data := map[string][]EntetiesClass{
        "Yoga": {{"Yoga", 15}, {"Yoga", 51}},
        "Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
    }

    t := template.New("t")
    t, err := t.Parse(htmlTemplate)
    if err != nil {
        panic(err)
    }

    err = t.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }

}

Output:

Pilates
3
6
9

Yoga
15
51

Playground: http://play.golang.org/p/4ISxcFKG7v

How to open adb and use it to send commands

The adb tool can be found in sdk/platform-tools/

If you don't see this directory in your SDK, launch the SDK Manager and install "Android SDK Platform-tools"

Also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.

How can I refresh or reload the JFrame?

Try

SwingUtilities.updateComponentTreeUI(frame);

If it still doesn't work then after completing the above step try

frame.invalidate();
frame.validate();
frame.repaint();

What is the purpose of "pip install --user ..."?

pip defaults to installing Python packages to a system directory (such as /usr/local/lib/python3.4). This requires root access.

--user makes pip install packages in your home directory instead, which doesn't require any special privileges.

CSS How to set div height 100% minus nPx

You can do something like height: calc(100% - nPx); for example height: calc(100% - 70px);

JavaScript: How to pass object by value?

As a consideration to jQuery users, there is also a way to do this in a simple way using the framework. Just another way jQuery makes our lives a little easier.

var oShallowCopy = jQuery.extend({}, o);
var oDeepCopy    = jQuery.extend(true, {}, o); 

references :

Laravel: PDOException: could not find driver

In window OS. I have uncomment extension=pdo_mysql for php.ini file that locate at same directory of php.exe. after that it work fine.

Fitting a histogram with python

Starting Python 3.8, the standard library provides the NormalDist object as part of the statistics module.

The NormalDist object can be built from a set of data with the NormalDist.from_samples method and provides access to its mean (NormalDist.mean) and standard deviation (NormalDist.stdev):

from statistics import NormalDist

# data = [0.7237248252340628, 0.6402731706462489, -1.0616113628912391, -1.7796451823371144, -0.1475852030122049, 0.5617952240065559, -0.6371760932160501, -0.7257277223562687, 1.699633029946764, 0.2155375969350495, -0.33371076371293323, 0.1905125348631894, -0.8175477853425216, -1.7549449090704003, -0.512427115804309, 0.9720486316086447, 0.6248742504909869, 0.7450655841312533, -0.1451632129830228, -1.0252663611514108]
norm = NormalDist.from_samples(data)
# NormalDist(mu=-0.12836704320073597, sigma=0.9240861018557649)
norm.mean
# -0.12836704320073597
norm.stdev
# 0.9240861018557649

Unit Tests not discovered in Visual Studio 2017

For me was easier to create a new test project that works perfectly fine with Visual Studio 2017... and just copy the test files, add references, and NuGet packages as required.

enter image description here

AngularJS passing data to $http.get request

Here's a complete example of an HTTP GET request with parameters using angular.js in ASP.NET MVC:

CONTROLLER:

public class AngularController : Controller
{
    public JsonResult GetFullName(string name, string surname)
    {
        System.Diagnostics.Debugger.Break();
        return Json(new { fullName = String.Format("{0} {1}",name,surname) }, JsonRequestBehavior.AllowGet);
    }
}

VIEW:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
    var myApp = angular.module("app", []);

    myApp.controller('controller', function ($scope, $http) {

        $scope.GetFullName = function (employee) {

            //The url is as follows - ControllerName/ActionName?name=nameValue&surname=surnameValue

            $http.get("/Angular/GetFullName?name=" + $scope.name + "&surname=" + $scope.surname).
            success(function (data, status, headers, config) {
                alert('Your full name is - ' + data.fullName);
            }).
            error(function (data, status, headers, config) {
                alert("An error occurred during the AJAX request");
            });

        }
    });

</script>

<div ng-app="app" ng-controller="controller">

    <input type="text" ng-model="name" />
    <input type="text" ng-model="surname" />
    <input type="button" ng-click="GetFullName()" value="Get Full Name" />
</div>

stale element reference: element is not attached to the page document

This errors have two common causes: The element has been deleted entirely, or the element is no longer attached to the DOM.

If you already checked if it is not your case, you could be facing the same problem as me.

The element in the DOM is not found because your page is not entirely loaded when Selenium is searching for the element. To solve that, you can put an explicit wait condition that tells Selenium to wait until the element is available to be clicked on.

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, 'someid')))

See: https://selenium-python.readthedocs.io/waits.html

Best way to extract a subvector from a vector?

vector<T>::const_iterator first = myVec.begin() + 100000;
vector<T>::const_iterator last = myVec.begin() + 101000;
vector<T> newVec(first, last);

It's an O(N) operation to construct the new vector, but there isn't really a better way.

Java - Relative path of a file in a java web application

Many popular Java webapps, including Jenkins and Nexus, use this mechanism:

  1. Optionally, check a servlet context-param / init-param. This allows configuring multiple webapp instances per servlet container, using context.xml which can be done by modifying the WAR or by changing server settings (in case of Tomcat).

  2. Check an environment variable (using System.getenv), if it is set, then use that folder as your application data folder. e.g. Jenkins uses JENKINS_HOME and Nexus uses PLEXUS_NEXUS_WORK. This allows flexible configuration without any changes to WAR.

  3. Otherwise, use a subfolder inside user's home folder, e.g. $HOME/.yourapp. In Java code this will be:

    final File appFolder = new File(System.getProperty("user.home"), ".yourapp");
    

How do I remove a library from the arduino environment?

as of 1.8.X IDE C:\Users***\Documents\Arduino\Libraries\

What are static factory methods?

We avoid providing direct access to database connections because they're resource intensive. So we use a static factory method getDbConnection that creates a connection if we're below the limit. Otherwise, it tries to provide a "spare" connection, failing with an exception if there are none.

public class DbConnection{
   private static final int MAX_CONNS = 100;
   private static int totalConnections = 0;

   private static Set<DbConnection> availableConnections = new HashSet<DbConnection>();

   private DbConnection(){
     // ...
     totalConnections++;
   }

   public static DbConnection getDbConnection(){

     if(totalConnections < MAX_CONNS){
       return new DbConnection();

     }else if(availableConnections.size() > 0){
         DbConnection dbc = availableConnections.iterator().next();
         availableConnections.remove(dbc);
         return dbc;

     }else {
         throw new NoDbConnections();
     }
   }

   public static void returnDbConnection(DbConnection dbc){
     availableConnections.add(dbc);
     //...
   }
}

FIFO based Queue implementations?

Yeah. Queue

LinkedList being the most trivial concrete implementation.

How can I update window.location.hash without jumping the document?

There is a workaround by using the history API on modern browsers with fallback on old ones:

if(history.pushState) {
    history.pushState(null, null, '#myhash');
}
else {
    location.hash = '#myhash';
}

Credit goes to Lea Verou

Generating a SHA-256 hash from the Linux command line

echo produces a trailing newline character which is hashed too. Try:

/bin/echo -n foobar | sha256sum 

What does it mean when an HTTP request returns status code 0?

In my case, the error occurred in a page requested with HTTP protocol, with a Javascript inside it trying to make an HTTPS request. And vice-versa.

After page loading, press F12 (or Ctrl + U) and take a look at the HTML code of your page. If you see something like that in your code:

<!-- javascript request inside the page -->
<script>
var ajaxurl = "https://example.com/wp-admin/admin-ajax.php";
(...)
</script>

And your page was requested this way:

http://example.com/example-page/2019/09/13/my-post/#elf_l1_Lw

You certainly will face this error.

To fix it, set the protocol of the Javascript request equal to the protocol of page request.

This situation involving different protocols, for page and js requests, was mentioned before in the answer of Brad Parks but, I guess the diagnostic technique presented here is easier, for the majority of users.

ImportError in importing from sklearn: cannot import name check_build

I had problems importing SKLEARN after installing a new 64bit version of Python 3.4 from python.org.

Turns out that it was the SCIPY module that was broken, and alos failed when I tried to "import scipy".

Solution was to uninstall scipy and reinstall it with pip3:

C:\> pip uninstall scipy

[lots of reporting messages deleted]

Proceed (y/n)? y
  Successfully uninstalled scipy-1.0.0

C:\Users\>pip3 install scipy

Collecting scipy
  Downloading scipy-1.0.0-cp36-none-win_amd64.whl (30.8MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 30.8MB 33kB/s
Requirement already satisfied: numpy>=1.8.2 in c:\users\johnmccurdy\appdata\loca
l\programs\python\python36\lib\site-packages (from scipy)
Installing collected packages: scipy
Successfully installed scipy-1.0.0

C:\Users>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)]
 on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import scipy
>>>
>>> import sklearn
>>>

switch() statement usage

In short, yes. But there are times when you might favor one vs. the other. Google "case switch vs. if else". There are some discussions already on SO too. Also, here is a good video that talks about it in the context of MATLAB:

http://blogs.mathworks.com/pick/2008/01/02/matlab-basics-switch-case-vs-if-elseif/

Personally, when I have 3 or more cases, I usually just go with case/switch.

Reading from memory stream to string

string result = Encoding.UTF8.GetString((stream as MemoryStream).ToArray());

If Browser is Internet Explorer: run an alternative script instead

For IE10+ standard conditions don't work cause of engine change or some another reasons, cause, you know, it's MSIE. But for IE10+ you need to run something like this in your scripts:

if (navigator.userAgent.match(/Trident\/7\./)) {
  // do stuff for IE.
}

Batch file include external file for variables

Let's not forget good old parameters. When starting your *.bat or *.cmd file you can add up to nine parameters after the command file name:

call myscript.bat \\path\to\my\file.ext type
call myscript.bat \\path\to\my\file.ext "Del /F"

Example script

The myscript.bat could be something like this:

@Echo Off
Echo The path of this scriptfile %~0
Echo The name of this scriptfile %~n0
Echo The extension of this scriptfile %~x0
Echo.
If "%~2"=="" (
   Echo Parameter missing, quitting.
   GoTo :EOF
)
If Not Exist "%~1" (
   Echo File does not exist, quitting.
   GoTo :EOF
)
Echo Going to %~2 this file: %~1
%~2 "%~1"
If %errorlevel%  NEQ 0 (
   Echo Failed to %~2 the %~1.
)
@Echo On

Example output

c:\>c:\bats\myscript.bat \\server\path\x.txt type
The path of this scriptfile c:\bats\myscript.bat
The name of this scriptfile myscript
The extension of this scriptfile .bat

Going to type this file: \\server\path\x.txt
This is the content of the file:
Some alphabets: ABCDEFG abcdefg
Some numbers: 1234567890

c:\>c:\bats\myscript.bat \\server\path\x.txt "del /f "
The path of this scriptfile c:\bats\myscript.bat
The name of this scriptfile myscript
The extension of this scriptfile .bat

Going to del /f  this file: \\server\path\x.txt

c:\>

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

If you run into this issue now, it's an Apple issue. They are releasing a new version of iTunesConnect. A bunch of my builds had been getting stuck in Processing these past few days. Today, they were getting stuck on Uploaded. Multiple phone calls and different answers later, the new site was just released and my builds are showing as Processing or available for submission. Though, they all have a yellow warning icon next to them. Not sure what that is.

HTTP Status 504

Suppose access a proxy server A(eg. nginx), and the server A forwards the request to another server B(eg. tomcat).

If this process continues for a long time (more than the proxy server read timeout setting), A still did not get a completed response of B. It happens.

for nginx, You can configure the proxy_read_timeout(in location) property to solve his.But this is usually not a good idea, if you set the value too high. This may hide the real error.You'd better improve the design to really solve this problem.

Access props inside quotes in React JSX

For People, looking for answers w.r.t to 'map' function and dynamic data, here is a working example.

<img src={"http://examole.com/randomview/images" + each_actor['logo']} />

This gives the URL as "http://examole.com/randomview/images/2/dp_pics/182328.jpg" (random example)

Bash Templating: How to build configuration files from templates with Bash?

# Usage: template your_file.conf.template > your_file.conf
template() {
        local IFS line
        while IFS=$'\n\r' read -r line ; do
                line=${line//\\/\\\\}         # escape backslashes
                line=${line//\"/\\\"}         # escape "
                line=${line//\`/\\\`}         # escape `
                line=${line//\$/\\\$}         # escape $
                line=${line//\\\${/\${}       # de-escape ${         - allows variable substitution: ${var} ${var:-default_value} etc
                # to allow arithmetic expansion or command substitution uncomment one of following lines:
#               line=${line//\\\$\(/\$\(}     # de-escape $( and $(( - allows $(( 1 + 2 )) or $( command ) - UNSECURE
#               line=${line//\\\$\(\(/\$\(\(} # de-escape $((        - allows $(( 1 + 2 ))
                eval "echo \"${line}\"";
        done < "$1"
}

This is the pure bash function adjustable to your liking, used in production and should not break on any input. If it breaks - let me know.

Equivalent of varchar(max) in MySQL?

For Sql Server

alter table prg_ar_report_colors add Text_Color_Code VARCHAR(max);

For MySql

alter table prg_ar_report_colors add Text_Color_Code longtext;

For Oracle

alter table prg_ar_report_colors add Text_Color_Code CLOB;

How can I use external JARs in an Android project?

For Eclipse

A good way to add external JARs to your Android project or any Java project is:

  1. Create a folder called libs in your project's root folder
  2. Copy your JAR files to the libs folder
  3. Now right click on the Jar file and then select Build Path > Add to Build Path, which will create a folder called 'Referenced Libraries' within your project

    By doing this, you will not lose your libraries that are being referenced on your hard drive whenever you transfer your project to another computer.

For Android Studio

  1. If you are in Android View in project explorer, change it to Project view as below

Missing Image

  1. Right click the desired module where you would like to add the external library, then select New > Directroy and name it as 'libs'
  2. Now copy the blah_blah.jar into the 'libs' folder
  3. Right click the blah_blah.jar, Then select 'Add as Library..'. This will automatically add and entry in build.gradle as compile files('libs/blah_blah.jar') and sync the gradle. And you are done

Please Note : If you are using 3rd party libraries then it is better to use transitive dependencies where Gradle script automatically downloads the JAR and the dependency JAR when gradle script run.

Ex : compile 'com.google.android.gms:play-services-ads:9.4.0'

Read more about Gradle Dependency Mangement

Scale Image to fill ImageView width and keep aspect ratio

Try this: it solved the problem for me

   android:adjustViewBounds="true"
    android:scaleType="fitXY"

Generating an MD5 checksum of a file

In Python 3.8+ you can do

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

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

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

How to "pull" from a local branch into another one?

you have to tell git where to pull from, in this case from the current directory/repository:

git pull . master

but when working locally, you usually just call merge (pull internally calls merge):

git merge master

getSupportActionBar() The method getSupportActionBar() is undefined for the type TaskActivity. Why?

You have to change the extends Activity to extends AppCompactActivity then try set and getSupportActionBar()

What does PermGen actually stand for?

If I remember correctly, the gen stands for generation, as in a generational garbage collector (that treats younger objects differently than mid-life and "permanent" objects). Principle of locality suggests that recently created objects will be wiped out first.

Is there any way to configure multiple registries in a single npmrc file

You can have multiple registries for scoped packages in your .npmrc file. For example:

@polymer:registry=<url register A>
registry=http://localhost:4873/

Packages under @polymer scope will be received from https://registry.npmjs.org, but the rest will be received from your local NPM.

Display open transactions in MySQL

Although there won't be any remaining transaction in the case, as @Johan said, you can see the current transaction list in InnoDB with the query below if you want.

SELECT * FROM information_schema.innodb_trx\G

From the document:

The INNODB_TRX table contains information about every transaction (excluding read-only transactions) currently executing inside InnoDB, including whether the transaction is waiting for a lock, when the transaction started, and the SQL statement the transaction is executing, if any.

Phone validation regex

enter image description hereThis solution actually validates the numbers and the format. For example: 123-456-7890 is a valid format but is NOT a valid US number and this answer bears that out where others here do not.


If you do not want the extension capability remove the following including the parenthesis: (?:\s*(?:#|x.?|ext.?|extension)\s*(\d+)\s*)? :)

edit (addendum) I needed this in a client side only application so I converted it. Here it is for the javascript folks:

var myPhoneRegex = /(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]??)\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]??|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})\s*(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+)\s*)?$/i;
if (myPhoneRegex.test(phoneVar)) {
    // Successful match
} else {
    // Match attempt failed
}

hth. end edit

This allows extensions or not and works with .NET

(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]??)\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]??|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$

To validate with or without trailing spaces. Perhaps when using .NET validators and trimming server side use this slightly different regex:

(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]??)\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]??|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})\s*(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+)\s*)?$

All valid:

1 800 5551212

800 555 1212

8005551212

18005551212

+1800 555 1212 extension65432

800 5551212 ext3333

Invalid #s

234-911-5678

314-159-2653

123-234-5678


EDIT: Based on Felipe's comment I have updated this for international.

Based on what I could find out from here and here regarding valid global numbers

This is tested as a first line of defense of course. An overarching element of the international number is that it is no longer than 15 characters. I did not write a replace for all the non digits and sum the result. It should be done for completeness. Also, you may notice that I have not combined the North America regex with this one. The reason is that this international regex will match North American numbers, however, it will also accept known invalid # such as +1 234-911-5678. For more accurate results you should separate them as well.

Pauses and other dialing instruments are not mentioned and therefore invalid per E.164

\(?\+[0-9]{1,3}\)? ?-?[0-9]{1,3} ?-?[0-9]{3,5} ?-?[0-9]{4}( ?-?[0-9]{3})?

With 1-10 letter word for extension and 1-6 digit extension:

\(?\+[0-9]{1,3}\)? ?-?[0-9]{1,3} ?-?[0-9]{3,5} ?-?[0-9]{4}( ?-?[0-9]{3})? ?(\w{1,10}\s?\d{1,6})?

Valid International: Country name for ref its not a match.

+55 11 99999-5555 Brazil

+593 7 282-3889 Ecuador

(+44) 0848 9123 456 UK

+1 284 852 5500 BVI

+1 345 9490088 Grand Cayman

+32 2 702-9200 Belgium

+65 6511 9266 Asia Pacific

+86 21 2230 1000 Shanghai

+9124 4723300 India

+821012345678 South Korea

And for your extension pleasure

+55 11 99999-5555 ramal 123 Brazil

+55 11 99999-5555 foo786544 Brazil

Enjoy

Writing sqlplus output to a file

just to save my own deductions from all this is (for saving DBMS_OUTPUT output on the client, using sqlplus):

  • no matter if i use Toad/with polling or sqlplus, for a long running script with occasional dbms_output.put_line commands, i will get the output in the end of the script execution
  • set serveroutput on; and dbms_output.enable(); should be present in the script
  • to save the output SPOOL command was not enough to get the DBMS_OUTPUT lines printed to a file - had to use the usual > windows CMD redirection. the passwords etc. can be given to the empty prompt, after invoking sqlplus. also the "/" directives and the "exit;" command should be put either inside the script, or given interactively as the password above (unless it is specified during the invocation of sqlplus)

Should I use px or rem value units in my CSS?

pt is similar to rem, in that it's relatively fixed, but almost always DPI-independent, even when non-compliant browsers treat px in a device-dependent fashion. rem varies with the font size of the root element, but you can use something like Sass/Compass to do this automatically with pt.

If you had this:

html {
    font-size: 12pt;
}

then 1rem would always be 12pt. rem and em are only as device-independent as the elements on which they rely; some browsers don't behave according to spec, and treat px literally. Even in the old days of the Web, 1 point was consistently regarded as 1/72 inch--that is, there are 72 points in an inch.

If you have an old, non-compliant browser, and you have:

html {
    font-size: 16px;
}

then 1rem is going to be device-dependent. For elements that would inherit from html by default, 1em would also be device-dependent. 12pt would be the hopefully guaranteed device-independent equivalent: 16px / 96px * 72pt = 12pt, where 96px = 72pt = 1in.

It can get pretty complicated to do the math if you want to stick to specific units. For example, .75em of html = .75rem = 9pt, and .66em of .75em of html = .5rem = 6pt. A good rule of thumb:

  • Use pt for absolute sizes. If you really need this to be dynamic relative to the root element, you're asking too much of CSS; you need a language that compiles to CSS, like Sass/SCSS.
  • Use em for relative sizes. It's pretty handy to be able to say, "I want the margin on the left to be about the maximum width of a letter," or, "Make this element's text just a bit bigger than its surroundings." <h1> is a good element on which to use a font size in ems, since it might appear in various places, but should always be bigger than nearby text. This way, you don't have to have a separate font size for every class that's applied to h1: the font size will adapt automatically.
  • Use px for very tiny sizes. At very small sizes, pt can get blurry in some browsers at 96 DPI, since pt and px don't quite line up. If you just want to create a thin, one-pixel border, say so. If you have a high-DPI display, this won't be obvious to you during testing, so be sure to test on a generic 96-DPI display at some point.
  • Don't deal in subpixels to make things fancy on high-DPI displays. Some browsers might support it--particularly on high-DPI displays--but it's a no-no. Most users prefer big and clear, though the web has taught us developers otherwise. If you want to add extended detail for your users with state-of-the-art screens, you can use vector graphics (read: SVG), which you should be doing anyway.

Best way to check if object exists in Entity Framework?

If you don't want to execute SQL directly, the best way is to use Any(). This is because Any() will return as soon as it finds a match. Another option is Count(), but this might need to check every row before returning.

Here's an example of how to use it:

if (context.MyEntity.Any(o => o.Id == idToMatch))
{
    // Match!
}

And in vb.net

If context.MyEntity.Any(function(o) o.Id = idToMatch) Then
    ' Match!
End If

How to force garbage collector to run?

GC.Collect();

Keep in mind, though, that the Garbage Collector might not always clean up what you expect...

what does numpy ndarray shape do?

Unlike it's most popular commercial competitor, numpy pretty much from the outset is about "arbitrary-dimensional" arrays, that's why the core class is called ndarray. You can check the dimensionality of a numpy array using the .ndim property. The .shape property is a tuple of length .ndim containing the length of each dimensions. Currently, numpy can handle up to 32 dimensions:

a = np.ones(32*(1,))
a
# array([[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ 1.]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]])
a.shape
# (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
a.ndim
# 32

If a numpy array happens to be 2d like your second example, then it's appropriate to think about it in terms of rows and columns. But a 1d array in numpy is truly 1d, no rows or columns.

If you want something like a row or column vector you can achieve this by creating a 2d array with one of its dimensions equal to 1.

a = np.array([[1,2,3]]) # a 'row vector'
b = np.array([[1],[2],[3]]) # a 'column vector'
# or if you don't want to type so many brackets:
b = np.array([[1,2,3]]).T

How to stretch in width a WPF user control to its window?

Does setting the HorizontalAlignment to Stretch, and the Width to Auto on the user control achieve the desired results?

RegEx to extract all matches from string using RegExp.exec

My guess is that if there would be edge cases such as extra or missing spaces, this expression with less boundaries might also be an option:

^\s*\[\s*([^\s\r\n:]+)\s*:\s*"([^"]*)"\s*([^\s\r\n:]+)\s*:\s*"([^"]*)"\s*\]\s*$

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Test

_x000D_
_x000D_
const regex = /^\s*\[\s*([^\s\r\n:]+)\s*:\s*"([^"]*)"\s*([^\s\r\n:]+)\s*:\s*"([^"]*)"\s*\]\s*$/gm;_x000D_
const str = `[description:"aoeu" uuid:"123sth"]_x000D_
[description : "aoeu" uuid: "123sth"]_x000D_
[ description : "aoeu" uuid: "123sth" ]_x000D_
 [ description : "aoeu"   uuid : "123sth" ]_x000D_
 [ description : "aoeu"uuid  : "123sth" ] `;_x000D_
let m;_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
    // This is necessary to avoid infinite loops with zero-width matches_x000D_
    if (m.index === regex.lastIndex) {_x000D_
        regex.lastIndex++;_x000D_
    }_x000D_
    _x000D_
    // The result can be accessed through the `m`-variable._x000D_
    m.forEach((match, groupIndex) => {_x000D_
        console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
    });_x000D_
}
_x000D_
_x000D_
_x000D_

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Reading a List from properties file and load with spring annotation @Value

All the above answers are correct. But you can achieve this in just one line. Please try following declaration and you will get all the comma separated values in a String list.

private @Value("#{T(java.util.Arrays).asList(projectProperties['my.list.of.strings'])}") List<String> myList;

And also you need to have the following line defined in your xml configuration.

<util:properties id="projectProperties" location="/project.properties"/>

just replace the path and file name of your properties file. And you are good to go. :)

Hope this helps you. Cheers.

java.lang.OutOfMemoryError: Java heap space in Maven

When I run maven test, java.lang.OutOfMemoryError happens. I google it for solutions and have tried to export MAVEN_OPTS=-Xmx1024m, but it did not work.

Setting the Xmx options using MAVEN_OPTS does work, it does configure the JVM used to start Maven. That being said, the maven-surefire-plugin forks a new JVM by default, and your MAVEN_OPTS are thus not passed.

To configure the sizing of the JVM used by the maven-surefire-plugin, you would either have to:

  • change the forkMode to never (which is be a not so good idea because Maven won't be isolated from the test) ~or~
  • use the argLine parameter (the right way):

In the later case, something like this:

<configuration>
  <argLine>-Xmx1024m</argLine>
</configuration>

But I have to say that I tend to agree with Stephen here, there is very likely something wrong with one of your test and I'm not sure that giving more memory is the right solution to "solve" (hide?) your problem.

References

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

Many times I have been facing this problem, I have experienced ClassNotFoundException. if jar is not at physical location.

So make sure .jar file(mysql connector) in the physical location of WEB-INF lib folder. and make sure restarting Tomcat by using shutdown command in cmd. it should work.

Docker: How to delete all local Docker images

  1. sudo docker images / docker images // list of images with id
  2. sudo docker rm image <image_id> / docker rm image <image_id>

How to maximize a plt.show() window using Python

In my versions (Python 3.6, Eclipse, Windows 7), snippets given above didn't work, but with hints given by Eclipse/pydev (after typing: mng.), I found:

mng.full_screen_toggle()

It seems that using mng-commands is ok only for local development...

How do I get the Date & Time (VBS)

nowreturns the current date and time

Represent space and tab in XML tag

For me, to make it work I need to encode hex value of space within CDATA xml element, so that post parsing it adds up just as in the htm webgae & when viewed in browser just displays a space!. ( all above ideas & answers are useful )

<my-xml-element><![CDATA[&#x20;]]></my-xml-element>

How to read a config file using python

Since your config file is a normal text file, just read it using the open function:

file = open("abc.txt", 'r')
content = file.read()
paths = content.split("\n") #split it into lines
for path in paths:
    print path.split(" = ")[1]

This will print your paths. You can also store them using dictionaries or lists.

path_list = []
path_dict = {}
for path in paths:
    p = path.split(" = ")
    path_list.append(p)[1]
    path_dict[p[0]] = p[1]

More on reading/writing file here. Hope this helps!

How to define several include path in Makefile

You need to use -I with each directory. But you can still delimit the directories with whitespace if you use (GNU) make's foreach:

INC=$(DIR1) $(DIR2) ...
INC_PARAMS=$(foreach d, $(INC), -I$d)

How to create war files

I've always just selected Export from Eclipse. It builds the war file and includes all necessary files. Providing you created the project as a web project that's all you'll need to do. Eclipse makes it very simple to do.

Docker: "no matching manifest for windows/amd64 in the manifest list entries"

Another possible way to do this:

In system tray, right click on docker icon, then click on Switch to Linux containers.

(Docker for Windows, Community Edition, version 18.03.1)

MIME types missing in IIS 7 for ASP.NET - 404.17

There are two reasons you might get this message:

  1. ASP.Net is not configured. For this run from Administrator command %FrameworkDir%\%FrameworkVersion%\aspnet_regiis -i. Read the message carefully. On Windows8/IIS8 it may say that this is no longer supported and you may have to use Turn Windows Features On/Off dialog in Install/Uninstall a Program in Control Panel.
  2. Another reason this may happen is because your App Pool is not configured correctly. For example, you created website for WordPress and you also want to throw in few aspx files in there, WordPress creates app pool that says don't run CLR stuff. To fix this just open up App Pool and enable CLR.

Why do we need virtual functions in C++?

Are you familiar with function pointers? Virtual functions are a similar idea, except you can easily bind data to virtual functions (as class members). It is not as easy to bind data to function pointers. To me, this is the main conceptual distinction. A lot of other answers here are just saying "because... polymorphism!"

Asus Zenfone 5 not detected by computer

Try a different usb cable. My cable was bad. Charging was ok but did not attach the phone.

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

Open your terminal and run

curl -sSL https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer | bash -s stable

When this is complete, you need to restart your terminal for the rvm command to work.

Now, run rvm list known

This shows the list of versions of the ruby.

Now, run rvm install ruby@latest to get the latest ruby version.

If you type ruby -v in the terminal, you should see ruby X.X.X.

If it still shows you ruby 2.0., run rvm use ruby-X.X.X --default.

Prerequisites for windows 10:

  • C compiler. You can use http://www.mingw.org/
  • make command available otherwise it will complain that "bash: make: command not found". You can install it by running mingw-get install msys-make
  • Add "C:\MinGW\msys\1.0\bin" and "C:\MinGW\bin" to your path enviroment variable

Accessing private member variables from prototype-defined functions

No, there's no way to do it. That would essentially be scoping in reverse.

Methods defined inside the constructor have access to private variables because all functions have access to the scope in which they were defined.

Methods defined on a prototype are not defined within the scope of the constructor, and will not have access to the constructor's local variables.

You can still have private variables, but if you want methods defined on the prototype to have access to them, you should define getters and setters on the this object, which the prototype methods (along with everything else) will have access to. For example:

function Person(name, secret) {
    // public
    this.name = name;

    // private
    var secret = secret;

    // public methods have access to private members
    this.setSecret = function(s) {
        secret = s;
    }

    this.getSecret = function() {
        return secret;
    }
}

// Must use getters/setters 
Person.prototype.spillSecret = function() { alert(this.getSecret()); };

Extract elements of list at odd positions

list_ = list(range(9)) print(list_[1::2])

How to calculate the width of a text string of a specific font and font-size?

sizeWithFont: is now deprecated, use sizeWithAttributes: instead:

UIFont *font = [UIFont fontWithName:@"Helvetica" size:30];
NSDictionary *userAttributes = @{NSFontAttributeName: font,
                                 NSForegroundColorAttributeName: [UIColor blackColor]};
NSString *text = @"hello";
...
const CGSize textSize = [text sizeWithAttributes: userAttributes];

Trigger a Travis-CI rebuild without pushing a commit?

I should mention here that we now have a means of triggering a new build on the web. See https://blog.travis-ci.com/2017-08-24-trigger-custom-build for details.

TL;DR Click on "More options", and choose "Trigger build".

How to JOIN three tables in Codeigniter

Use this code in model

public function funcname($id)
{
    $this->db->select('*');
    $this->db->from('Album a'); 
    $this->db->join('Category b', 'b.cat_id=a.cat_id', 'left');
    $this->db->join('Soundtrack c', 'c.album_id=a.album_id', 'left');
    $this->db->where('c.album_id',$id);
    $this->db->order_by('c.track_title','asc');         
    $query = $this->db->get(); 
    if($query->num_rows() != 0)
    {
        return $query->result_array();
    }
    else
    {
        return false;
    }
}

SQL Error: ORA-01861: literal does not match format string 01861

If you provide proper date format it should work please recheck once if you have given correct date format in insert values

C - casting int to char and append char to char

Casting int to char is done simply by assigning with the type in parenthesis:

int i = 65535;
char c = (char)i;

Note: I thought that you might be losing data (as in the example), because the type sizes are different.

Appending characters to characters cannot be done (unless you mean arithmetics, then it's simple operators). You need to use strings, AKA arrays of characters, and <string.h> functions like strcat or sprintf.

Deleting queues in RabbitMQ

You assert that a queue exists (and create it if it does not) by using queue.declare. If you originally set auto-delete to false, calling queue.declare again with autodelete true will result in a soft error and the broker will close the channel.

You need to use queue.delete now in order to delete it.

See the API documentation for details:

If you use another client, you'll need to find the equivalent method. Since it's part of the protocol, it should be there, and it's probably part of Channel or the equivalent.

You might also want to have a look at the rest of the documentation, in particular the Geting Started section which covers a lot of common use cases.

Finally, if you have a question and can't find the answer elsewhere, you should try posting on the RabbitMQ Discuss mailing list. The developers do their best to answer all questions asked there.

Remove scrollbars from textarea

Try the following, not sure which will work for all browsers or the browser you are working with, but it would be best to try all:

<textarea style="overflow:auto"></textarea>

Or

<textarea style="overflow:hidden"></textarea>

...As suggested above

You can also try adding this, I never used it before, just saw it posted on a site today:

<textarea style="resize:none"></textarea>

This last option would remove the ability to resize the textarea. You can find more information on the CSS resize property here

Implement a loading indicator for a jQuery AJAX call

I'm guessing you're using jQuery.get or some other jQuery ajax function to load the modal. You can show the indicator before the ajax call, and hide it when the ajax completes. Something like

$('#indicator').show();
$('#someModal').get(anUrl, someData, function() { $('#indicator').hide(); });

Global variables in Java

public class GlobalImpl {   

 public static int global = 5;

}

you can call anywhere you want:

GlobalImpl.global // 5

Copy every nth line from one sheet to another

If your original data is in column form with multiple columns and the first entry of your original data in C42, and you want your new (down-sampled) data to be in column form as well, but only every seventh row, then you will also need to subtract out the row number of the first entry, like so:

=OFFSET(C$42,(ROW(C42)-ROW(C$42))*7,0)

Trigger event on body load complete js/jquery

Isn't

  $(document).ready(function() {

  });

what you are looking for?

"Rate This App"-link in Google Play store app on the phone

A kotlin version

fun openAppInPlayStore() {
    val uri = Uri.parse("market://details?id=" + context.packageName)
    val goToMarketIntent = Intent(Intent.ACTION_VIEW, uri)

    var flags = Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_ACTIVITY_MULTIPLE_TASK
    flags = if (Build.VERSION.SDK_INT >= 21) {
        flags or Intent.FLAG_ACTIVITY_NEW_DOCUMENT
    } else {
        flags or Intent.FLAG_ACTIVITY_CLEAR_TASK
    }
    goToMarketIntent.addFlags(flags)

    try {
        startActivity(context, goToMarketIntent, null)
    } catch (e: ActivityNotFoundException) {
        val intent = Intent(Intent.ACTION_VIEW,
                Uri.parse("http://play.google.com/store/apps/details?id=" + context.packageName))

        startActivity(context, intent, null)
    }
}

How to read existing text files without defining path

There are many ways to get a path. See CurrentDirrectory mentioned. Also, you can get the full file name of your application by using Assembly.GetExecutingAssembly().Location and then use Path class to get a directory name.

Animate scroll to ID on page load

Pure javascript solution with scrollIntoView() function:

_x000D_
_x000D_
document.getElementById('title1').scrollIntoView({block: 'start', behavior: 'smooth'});
_x000D_
<h2 id="title1">Some title</h2>
_x000D_
_x000D_
_x000D_

P.S. 'smooth' parameter now works from Chrome 61 as julien_c mentioned in the comments.

Python's time.clock() vs. time.time() accuracy?

Others have answered re: time.time() vs. time.clock().

However, if you're timing the execution of a block of code for benchmarking/profiling purposes, you should take a look at the timeit module.

What is the difference between the HashMap and Map objects in Java?

HashMap<String, Object> map1 = new HashMap<String, Object>();
Map<String, Object> map2 = new HashMap<String, Object>();  

First of all Map is an interface it has different implementation like - HashMap, TreeHashMap, LinkedHashMap etc. Interface works like a super class for the implementing class. So according to OOP's rule any concrete class that implements Map is a Map also. That means we can assign/put any HashMap type variable to a Map type variable without any type of casting.

In this case we can assign map1 to map2 without any casting or any losing of data -

map2 = map1

How to search and replace text in a file?

I got the same issue. The problem is that when you load a .txt in a variable you use it like an array of string while it's an array of character.

swapString = []
with open(filepath) as f: 
    s = f.read()
for each in s:
    swapString.append(str(each).replace('this','that'))
s = swapString
print(s)

Is it possible for UIStackView to scroll?

In case anyone is looking for a solution without code, I created an example to do this completely in the storyboard, using Auto Layout.

You can get it from github.

Basically, to recreate the example (for vertical scrolling):

  1. Create a UIScrollView, and set its constraints.
  2. Add a UIStackView to the UIScrollView
  3. Set the constraints: Leading, Trailing, Top & Bottom should be equal to the ones from UIScrollView
  4. Set up an equal Width constraint between the UIStackView and UIScrollView.
  5. Set Axis = Vertical, Alignment = Fill, Distribution = Equal Spacing, and Spacing = 0 on the UIStackView
  6. Add a number of UIViews to the UIStackView
  7. Run

Exchange Width for Height in step 4, and set Axis = Horizontal in step 5, to get a horizontal UIStackView.

How to check empty object in angular 2 template using *ngIf

From the above answeres, following did not work or less preferable:

  • (previous_info | json) != '{}' works only for {} empty case, not for null or undefined case
  • Object.getOwnPropertyNames(previous_info).length also did not work, as Object is not accessible in the template
  • I would not like to create a dedicated variable this.objectLength = Object.keys(this.previous_info).length !=0;
  • I would not like to create a dedicated function

    isEmptyObject(obj) {
       return (obj && (Object.keys(obj).length === 0));
    }
    

Solution: keyvalue pipe along with ?. (safe navigation operator); and it seems simple.

It works well when previous_info = null or previous_info = undefined or previous_info = {} and treats as falsy value.

<div  *ngIf="(previous_info | keyvalue)?.length">

keyvalue - Transforms Object or Map into an array of key value pairs.

?. - The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined

DEMO: demo with angular 9, though it works for previous versions as well

How to grant remote access to MySQL for a whole subnet?

EDIT: Consider looking at and upvoting Malvineous's answer on this page. Netmasks are a much more elegant solution.


Simply use a percent sign as a wildcard in the IP address.

From http://dev.mysql.com/doc/refman/5.1/en/grant.html

You can specify wildcards in the host name. For example, user_name@'%.example.com' applies to user_name for any host in the example.com domain, and user_name@'192.168.1.%' applies to user_name for any host in the 192.168.1 class C subnet.

creating array without declaring the size - java

Using Java.util.ArrayList or LinkedList is the usual way of doing this. With arrays that's not possible as I know.

Example:

List<Float> unindexedVectors = new ArrayList<Float>();

unindexedVectors.add(2.22f);

unindexedVectors.get(2);

Can I set enum start value in Java?

Java enums are not like C or C++ enums, which are really just labels for integers.

Java enums are implemented more like classes - and they can even have multiple attributes.

public enum Ids {
    OPEN(100), CLOSE(200);

    private final int id;
    Ids(int id) { this.id = id; }
    public int getValue() { return id; }
}

The big difference is that they are type-safe which means you don't have to worry about assigning a COLOR enum to a SIZE variable.

See http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html for more.

How can I scan barcodes on iOS?

liteqr is a "Lite QR Reader in Objective C ported from zxing" on github and has support for Xcode 4.

How to convert rdd object to dataframe in spark

Note: This answer was originally posted here

I am posting this answer because I would like to share additional details about the available options that I did not find in the other answers


To create a DataFrame from an RDD of Rows, there are two main options:

1) As already pointed out, you could use toDF() which can be imported by import sqlContext.implicits._. However, this approach only works for the following types of RDDs:

  • RDD[Int]
  • RDD[Long]
  • RDD[String]
  • RDD[T <: scala.Product]

(source: Scaladoc of the SQLContext.implicits object)

The last signature actually means that it can work for an RDD of tuples or an RDD of case classes (because tuples and case classes are subclasses of scala.Product).

So, to use this approach for an RDD[Row], you have to map it to an RDD[T <: scala.Product]. This can be done by mapping each row to a custom case class or to a tuple, as in the following code snippets:

val df = rdd.map({ 
  case Row(val1: String, ..., valN: Long) => (val1, ..., valN)
}).toDF("col1_name", ..., "colN_name")

or

case class MyClass(val1: String, ..., valN: Long = 0L)
val df = rdd.map({ 
  case Row(val1: String, ..., valN: Long) => MyClass(val1, ..., valN)
}).toDF("col1_name", ..., "colN_name")

The main drawback of this approach (in my opinion) is that you have to explicitly set the schema of the resulting DataFrame in the map function, column by column. Maybe this can be done programatically if you don't know the schema in advance, but things can get a little messy there. So, alternatively, there is another option:


2) You can use createDataFrame(rowRDD: RDD[Row], schema: StructType) as in the accepted answer, which is available in the SQLContext object. Example for converting an RDD of an old DataFrame:

val rdd = oldDF.rdd
val newDF = oldDF.sqlContext.createDataFrame(rdd, oldDF.schema)

Note that there is no need to explicitly set any schema column. We reuse the old DF's schema, which is of StructType class and can be easily extended. However, this approach sometimes is not possible, and in some cases can be less efficient than the first one.

Limit String Length

Do a little homework with the php online manual's string functions. You'll want to use strlen in a comparison setting, substr to cut it if you need to, and the concatenation operator with "..." or "&hellip;"

Converting a list to a set changes element order

  1. A set is an unordered data structure, so it does not preserve the insertion order.

  2. This depends on your requirements. If you have an normal list, and want to remove some set of elements while preserving the order of the list, you can do this with a list comprehension:

    >>> a = [1, 2, 20, 6, 210]
    >>> b = set([6, 20, 1])
    >>> [x for x in a if x not in b]
    [2, 210]
    

    If you need a data structure that supports both fast membership tests and preservation of insertion order, you can use the keys of a Python dictionary, which starting from Python 3.7 is guaranteed to preserve the insertion order:

    >>> a = dict.fromkeys([1, 2, 20, 6, 210])
    >>> b = dict.fromkeys([6, 20, 1])
    >>> dict.fromkeys(x for x in a if x not in b)
    {2: None, 210: None}
    

    b doesn't really need to be ordered here – you could use a set as well. Note that a.keys() - b.keys() returns the set difference as a set, so it won't preserve the insertion order.

    In older versions of Python, you can use collections.OrderedDict instead:

    >>> a = collections.OrderedDict.fromkeys([1, 2, 20, 6, 210])
    >>> b = collections.OrderedDict.fromkeys([6, 20, 1])
    >>> collections.OrderedDict.fromkeys(x for x in a if x not in b)
    OrderedDict([(2, None), (210, None)])
    

List all files from a directory recursively with Java

Java's interface for reading filesystem folder contents is not very performant (as you've discovered). JDK 7 fixes this with a completely new interface for this sort of thing, which should bring native level performance to these sorts of operations.

The core issue is that Java makes a native system call for every single file. On a low latency interface, this is not that big of a deal - but on a network with even moderate latency, it really adds up. If you profile your algorithm above, you'll find that the bulk of the time is spent in the pesky isDirectory() call - that's because you are incurring a round trip for every single call to isDirectory(). Most modern OSes can provide this sort of information when the list of files/folders was originally requested (as opposed to querying each individual file path for it's properties).

If you can't wait for JDK7, one strategy for addressing this latency is to go multi-threaded and use an ExecutorService with a maximum # of threads to perform your recursion. It's not great (you have to deal with locking of your output data structures), but it'll be a heck of a lot faster than doing this single threaded.

In all of your discussions about this sort of thing, I highly recommend that you compare against the best you could do using native code (or even a command line script that does roughly the same thing). Saying that it takes an hour to traverse a network structure doesn't really mean that much. Telling us that you can do it native in 7 second, but it takes an hour in Java will get people's attention.

Run MySQLDump without Locking Tables

For InnoDB tables use flag --single-transaction

it dumps the consistent state of the database at the time when BEGIN was issued without blocking any applications

MySQL DOCS

http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_single-transaction

Removing double quotes from variables in batch file creates problems with CMD environment

This sounds like a simple bug where you are using %~ somewhere where you shouldn't be. The use if %~ doesn't fundamentally change the way batch files work, it just removes quotes from the string in that single situation.

modal View controllers - how to display and dismiss

I wanted this:

MapVC is a Map in full screen.

When I press a button, it opens PopupVC (not in full screen) above the map.

When I press a button in PopupVC, it returns to MapVC, and then I want to execute viewDidAppear.

I did this:

MapVC.m: in the button action, a segue programmatically, and set delegate

- (void) buttonMapAction{
   PopupVC *popvc = [self.storyboard instantiateViewControllerWithIdentifier:@"popup"];
   popvc.delegate = self;
   [self presentViewController:popvc animated:YES completion:nil];
}

- (void)dismissAndPresentMap {
  [self dismissViewControllerAnimated:NO completion:^{
    NSLog(@"dismissAndPresentMap");
    //When returns of the other view I call viewDidAppear but you can call to other functions
    [self viewDidAppear:YES];
  }];
}

PopupVC.h: before @interface, add the protocol

@protocol PopupVCProtocol <NSObject>
- (void)dismissAndPresentMap;
@end

after @interface, a new property

@property (nonatomic,weak) id <PopupVCProtocol> delegate;

PopupVC.m:

- (void) buttonPopupAction{
  //jump to dismissAndPresentMap on Map view
  [self.delegate dismissAndPresentMap];
}

Linq filter List<string> where it contains a string value from another List<string>

you can do that

var filteredFileList = fileList.Where(fl => filterList.Contains(fl.ToString()));

DELETE ... FROM ... WHERE ... IN

You can achieve this using exists:

DELETE
  FROM table1
 WHERE exists(
           SELECT 1
             FROM table2
            WHERE table2.stn = table1.stn
              and table2.jaar = year(table1.datum)
       )

PHP regular expressions: No ending delimiter '^' found in

Your regex pattern needs to be in delimiters:

$numpattern="/^([0-9]+)$/";

Printing all properties in a Javascript Object

Your syntax is incorrect. The var keyword in your for loop must be followed by a variable name, in this case its propName

var propValue;
for(var propName in nyc) {
    propValue = nyc[propName]

    console.log(propName,propValue);
}

I suggest you have a look here for some basics:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Disable text input history

<input type="text" autocomplete="off"/>

Should work. Alternatively, use:

<form autocomplete="off" … >

for the entire form (see this related question).

Using a bitmask in C#

The traditional way to do this is to use the Flags attribute on an enum:

[Flags]
public enum Names
{
    None = 0,
    Susan = 1,
    Bob = 2,
    Karen = 4
}

Then you'd check for a particular name as follows:

Names names = Names.Susan | Names.Bob;

// evaluates to true
bool susanIsIncluded = (names & Names.Susan) != Names.None;

// evaluates to false
bool karenIsIncluded = (names & Names.Karen) != Names.None;

Logical bitwise combinations can be tough to remember, so I make life easier on myself with a FlagsHelper class*:

// The casts to object in the below code are an unfortunate necessity due to
// C#'s restriction against a where T : Enum constraint. (There are ways around
// this, but they're outside the scope of this simple illustration.)
public static class FlagsHelper
{
    public static bool IsSet<T>(T flags, T flag) where T : struct
    {
        int flagsValue = (int)(object)flags;
        int flagValue = (int)(object)flag;

        return (flagsValue & flagValue) != 0;
    }

    public static void Set<T>(ref T flags, T flag) where T : struct
    {
        int flagsValue = (int)(object)flags;
        int flagValue = (int)(object)flag;

        flags = (T)(object)(flagsValue | flagValue);
    }

    public static void Unset<T>(ref T flags, T flag) where T : struct
    {
        int flagsValue = (int)(object)flags;
        int flagValue = (int)(object)flag;

        flags = (T)(object)(flagsValue & (~flagValue));
    }
}

This would allow me to rewrite the above code as:

Names names = Names.Susan | Names.Bob;

bool susanIsIncluded = FlagsHelper.IsSet(names, Names.Susan);

bool karenIsIncluded = FlagsHelper.IsSet(names, Names.Karen);

Note I could also add Karen to the set by doing this:

FlagsHelper.Set(ref names, Names.Karen);

And I could remove Susan in a similar way:

FlagsHelper.Unset(ref names, Names.Susan);

*As Porges pointed out, an equivalent of the IsSet method above already exists in .NET 4.0: Enum.HasFlag. The Set and Unset methods don't appear to have equivalents, though; so I'd still say this class has some merit.


Note: Using enums is just the conventional way of tackling this problem. You can totally translate all of the above code to use ints instead and it'll work just as well.

How to show progress bar while loading, using ajax

_x000D_
_x000D_
$(document).ready(function () { _x000D_
 $(document).ajaxStart(function () {_x000D_
        $('#wait').show();_x000D_
    });_x000D_
    $(document).ajaxStop(function () {_x000D_
        $('#wait').hide();_x000D_
    });_x000D_
    $(document).ajaxError(function () {_x000D_
        $('#wait').hide();_x000D_
    });   _x000D_
});
_x000D_
<div id="wait" style="display: none; width: 100%; height: 100%; top: 100px; left: 0px; position: fixed; z-index: 10000; text-align: center;">_x000D_
            <img src="../images/loading_blue2.gif" width="45" height="45" alt="Loading..." style="position: fixed; top: 50%; left: 50%;" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

From an array of objects, extract value of a property as array

Example to collect the different fields from the object array

_x000D_
_x000D_
let inputArray = [
  { id: 1, name: "name1", value: "value1" },
  { id: 2, name: "name2", value: "value2" },
];

let ids = inputArray.map( (item) => item.id);
let names = inputArray.map((item) => item.name);
let values = inputArray.map((item) => item.value);

console.log(ids);
console.log(names);
console.log(values);
_x000D_
_x000D_
_x000D_

Result :

[ 1, 2 ]
[ 'name1', 'name2' ]
[ 'value1', 'value2' ]

How to print full stack trace in exception?

I usually use the .ToString() method on exceptions to present the full exception information (including the inner stack trace) in text:

catch (MyCustomException ex)
{
    Debug.WriteLine(ex.ToString());
}

Sample output:

ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes!
   at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24
   at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14
   --- End of inner exception stack trace ---
   at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18
   at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23
   at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13

Disabling of EditText in Android

Simply:

editText.setEnabled(false);

Horizontal scroll on overflow of table

   .search-table-outter {border:2px solid red; overflow-x:scroll;}
   .search-table{table-layout: fixed; margin:40px auto 0px auto;   }
   .search-table, td, th{border-collapse:collapse; border:1px solid #777;}
   th{padding:20px 7px; font-size:15px; color:#444; background:#66C2E0;}
   td{padding:5px 10px; height:35px;}

You should provide scroll in div.

How to match "any character" in regular expression?

Yes that will work, though note that . will not match newlines unless you pass the DOTALL flag when compiling the expression:

Pattern pattern = Pattern.compile(".*123", Pattern.DOTALL);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();

Image height and width not working?

http://www.markrafferty.com/wp-content/w3tc/min/7415c412.e68ae1.css

Line 11:

.postItem img {
    height: auto;
    width: 450px;
}

You can either edit your CSS, or you can listen to Mageek and use INLINE STYLING to override the CSS styling that's happening:

<img src="theSource" style="width:30px;" />

Avoid setting both width and height, as the image itself might not be scaled proportionally. But you can set the dimensions to whatever you want, as per Mageek's example.

Check if input value is empty and display an alert

Better one is here.

$('#submit').click(function()
{
    if( !$('#myMessage').val() ) {
       alert('warning');
    }
});

And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:

$('#submit').on('click',function()
{
    if( $('#myMessage').val().length === 0 ) {
        alert('warning');
    }
});

If you're sure it will always operate on a textfield element then you can just use this.value.

$('#submit').click(function()
{
      if( !document.getElementById('myMessage').value ) {
          alert('warning');
      }
});

Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).

C# list.Orderby descending

list.OrderByDescending();

works for me.

jquery validate check at least one checkbox

$("#idform").validate({
    rules: {            
        'roles': {
            required: true,
        },
    },
    messages: {            
        'roles': {
            required: "One Option please",
        },
    }
});

Getting the source HTML of the current page from chrome extension

Here is my solution:

chrome.runtime.onMessage.addListener(function(request, sender) {
        if (request.action == "getSource") {
            this.pageSource = request.source;
            var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];
            alert(title)
        }
    });

    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
        chrome.tabs.executeScript(
            tabs[0].id,
            { code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }
        );
    });

Serial Port (RS -232) Connection in C++

For the answer above, the default serial port is

        serialParams.BaudRate = 9600;
        serialParams.ByteSize = 8;
        serialParams.StopBits = TWOSTOPBITS;
        serialParams.Parity = NOPARITY;

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

a kernel is part of the operating system, it is the first thing that the boot loader loads onto the cpu (for most operating systems), it is the part that interfaces with the hardware, and it also manages what programs can do what with the hardware, it is really the central part of the os, it is made up of drivers, a driver is a program that interfaces with a particular piece of hardware, for example: if I made a digital camera for computers, I would need to make a driver for it, the drivers are the only programs that can control the input and output of the computer

Ripple effect on Android Lollipop CardView

Add the following to your xml:

android:clickable="true"
android:focusable="true"
android:background="?android:attr/selectableItemBackground"

And add to your adapter (if it's your case)

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val attrs = intArrayOf(R.attr.selectableItemBackground)
            val typedArray = holder.itemView.context.obtainStyledAttributes(attrs)
            val selectableItemBackground = typedArray.getResourceId(0, 0)
            typedArray.recycle()

            holder.itemView.isClickable = true
            holder.itemView.isFocusable = true
            holder.itemView.foreground = holder.itemView.context.getDrawable(selectableItemBackground)
        }
    }

Return array in a function

In C++11, you can return std::array.

#include <array>
using namespace std;

array<int, 5> fillarr(int arr[])
{
    array<int, 5> arr2;
    for(int i=0; i<5; ++i) {
        arr2[i]=arr[i]*2;
    }
    return arr2;
}

Remove directory from remote repository after adding them to .gitignore

The rules in your .gitignore file only apply to untracked files. Since the files under that directory were already committed in your repository, you have to unstage them, create a commit, and push that to GitHub:

git rm -r --cached some-directory
git commit -m 'Remove the now ignored directory "some-directory"'
git push origin master

You can't delete the file from your history without rewriting the history of your repository - you shouldn't do this if anyone else is working with your repository, or you're using it from multiple computers. If you still want to do that, you can use git filter-branch to rewrite the history - there is a helpful guide to that here.

Additionally, note the output from git rm -r --cached some-directory will be something like:

rm 'some-directory/product/cache/1/small_image/130x130/small_image.jpg'
rm 'some-directory/product/cache/1/small_image/135x/small_image.jpg'
rm 'some-directory/.htaccess'
rm 'some-directory/logo.jpg'

The rm is feedback from git about the repository; the files are still in the working directory.

How does JPA orphanRemoval=true differ from the ON DELETE CASCADE DML clause

An example taken form here:

When an Employee entity object is removed, the remove operation is cascaded to the referenced Address entity object. In this regard, orphanRemoval=true and cascade=CascadeType.REMOVE are identical, and if orphanRemoval=true is specified, CascadeType.REMOVE is redundant.

The difference between the two settings is in the response to disconnecting a relationship. For example, such as when setting the address field to null or to another Address object.

  • If orphanRemoval=true is specified the disconnected Address instance is automatically removed. This is useful for cleaning up dependent objects (e.g. Address) that should not exist without a reference from an owner object (e.g. Employee).

  • If only cascade=CascadeType.REMOVE is specified, no automatic action is taken since disconnecting a relationship is not a remove operation.

To avoid dangling references as a result of orphan removal, this feature should only be enabled for fields that hold private non shared dependent objects.

I hope this makes it more clear.

How to use double or single brackets, parentheses, curly braces

In Bash, test and [ are shell builtins.

The double bracket, which is a shell keyword, enables additional functionality. For example, you can use && and || instead of -a and -o and there's a regular expression matching operator =~.

Also, in a simple test, double square brackets seem to evaluate quite a lot quicker than single ones.

$ time for ((i=0; i<10000000; i++)); do [[ "$i" = 1000 ]]; done

real    0m24.548s
user    0m24.337s
sys 0m0.036s
$ time for ((i=0; i<10000000; i++)); do [ "$i" = 1000 ]; done

real    0m33.478s
user    0m33.478s
sys 0m0.000s

The braces, in addition to delimiting a variable name are used for parameter expansion so you can do things like:

  • Truncate the contents of a variable

    $ var="abcde"; echo ${var%d*}
    abc
    
  • Make substitutions similar to sed

    $ var="abcde"; echo ${var/de/12}
    abc12
    
  • Use a default value

    $ default="hello"; unset var; echo ${var:-$default}
    hello
    
  • and several more

Also, brace expansions create lists of strings which are typically iterated over in loops:

$ echo f{oo,ee,a}d
food feed fad

$ mv error.log{,.OLD}
(error.log is renamed to error.log.OLD because the brace expression
expands to "mv error.log error.log.OLD")

$ for num in {000..2}; do echo "$num"; done
000
001
002

$ echo {00..8..2}
00 02 04 06 08

$ echo {D..T..4}
D H L P T

Note that the leading zero and increment features weren't available before Bash 4.

Thanks to gboffi for reminding me about brace expansions.

Double parentheses are used for arithmetic operations:

((a++))

((meaning = 42))

for ((i=0; i<10; i++))

echo $((a + b + (14 * c)))

and they enable you to omit the dollar signs on integer and array variables and include spaces around operators for readability.

Single brackets are also used for array indices:

array[4]="hello"

element=${array[index]}

Curly brace are required for (most/all?) array references on the right hand side.

ephemient's comment reminded me that parentheses are also used for subshells. And that they are used to create arrays.

array=(1 2 3)
echo ${array[1]}
2

Convert an integer to an array of digits

The <= in the for statement should be a <.

BTW, it is possible to do this much more efficiently without using strings, but instead using /10 and %10 of integers.

Saving a Excel File into .txt format without quotes

The answer from this question provided the answer to this question much more simply.

Write is a special statement designed to generate machine-readable files that are later consumed with Input.

Use Print to avoid any fiddling with data.

Thank you user GSerg

Use JSTL forEach loop's varStatus as an ID

Its really helped me to dynamically generate ids of showDetailItem for the below code.

<af:forEach id="fe1" items="#{viewScope.bean.tranTypeList}" var="ttf" varStatus="ttfVs" > 
<af:showDetailItem  id ="divIDNo${ttfVs.count}" text="#{ttf.trandef}"......>

if you execute this line <af:outputText value="#{ttfVs}"/> prints the below:

{index=3, count=4, last=false, first=false, end=8, step=1, begin=0}

Can you get a Windows (AD) username in PHP?

No. But what you can do is have your Active Directory admin enable LDAP so that users can maintain one set of credentials

http://us2.php.net/ldap

How to reset a timer in C#?

I just assigned a new value to the timer:

mytimer.Change(10000, 0); // reset to 10 seconds

It works fine for me.

at the top of the code define the timer: System.Threading.Timer myTimer;

if (!active)
    myTimer = new Timer(new TimerCallback(TimerProc));

myTimer.Change(10000, 0);
active = true;

private void TimerProc(object state)
{
    // The state object is the Timer object.
    var t = (Timer)state;

    t.Dispose();
    Console.WriteLine("The timer callback executes.");
    active = false;
    
    // Action to do when timer is back to zero
}

ORA-00979 not a group by expression

Include in the GROUP BY clause all SELECT expressions that are not group function arguments.

SyntaxError: Cannot use import statement outside a module

I had the same issue and the following has fixed it (using node 12.13.1):

  • Change .js files extension to .mjs
  • Add --experimental-modules flag upon running your app.
  • Optional: add "type": "module" in your package.json

more info: https://nodejs.org/api/esm.html

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

How to write a test which expects an Error to be thrown in Jasmine?

You are using:

expect(fn).toThrow(e)

But if you'll have a look on the function comment (expected is string):

294 /**
295  * Matcher that checks that the expected exception was thrown by the actual.
296  *
297  * @param {String} expected
298  */
299 jasmine.Matchers.prototype.toThrow = function(expected) {

I suppose you should probably write it like this (using lambda - anonymous function):

expect(function() { parser.parse(raw); } ).toThrow("Parsing is not possible");

This is confirmed in the following example:

expect(function () {throw new Error("Parsing is not possible")}).toThrow("Parsing is not possible");

Douglas Crockford strongly recommends this approach, instead of using "throw new Error()" (prototyping way):

throw {
   name: "Error",
   message: "Parsing is not possible"
}

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

Not exactly the same problem for me, because I was running the last java version 1.8.0_92, IE v11 and windows 7.

My situation was also that I had Chrome as the default browser.

So what for me fixed it, was to set IExplorer as the default browser again, uninstall Java, go to Java.com using the IExplorer, and from the IExplorer download and install Java again to the last version.

method in class cannot be applied to given types

I think you want something like this. The formatting is off, but it should give the essential information you want.

   import java.util.Scanner;
public class BookstoreCredit 
{

   public static void computeDiscount(String name, double gpa) 
   {
      double credits;
      credits = gpa * 10;
      System.out.println(name + " your GPA is " +
         gpa + " so your credit is $" + credits);
   
   }

   public static void main (String args[]) 
   {
      String studentName;
      double gradeAverage;
      Scanner inputDevice = new Scanner(System.in);
      System.out.println("Enter Student name: ");
      studentName = inputDevice.nextLine();
      System.out.println("Enter student GPA: ");
      gradeAverage = inputDevice.nextDouble();  
      
      computeDiscount(studentName, gradeAverage);
   }
}

Rename a column in MySQL

In mysql your query should be like

ALTER TABLE table_name change column_1 column_2 Data_Type;

you have written the query in Oracle.

How to require a controller in an angularjs directive

I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".


It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.

Share a Controller

Two directives can use the same controller by passing the same method to two directives, like so:

app.controller( 'MyCtrl', function ( $scope ) {
  // do stuff...
});

app.directive( 'directiveOne', function () {
  return {
    controller: 'MyCtrl'
  };
});

app.directive( 'directiveTwo', function () {
  return {
    controller: 'MyCtrl'
  };
});

Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.

Require a Controller

If you want to share the same instance of a controller, then you use require.

require ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel.

^require, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.

In either event, you have to use the two directives together for this to work. require is a way of communicating between components.

Check out the Guide page of directives for more info: http://docs.angularjs.org/guide/directive

How do we check if a pointer is NULL pointer?

I always think simply if(p != NULL){..} will do the job.

It will.

Change Timezone in Lumen or Laravel 5

For me the app.php was here /vendor/laravel/lumen-framework/config/app.php but I also could change it from the .env file where it can be set to any of the values listed here (PHP original documentation here).

Align a div to center

this works nicely

width:40%; // the width of the content div
right:0;
margin-right:30%; // 1/2 the remaining space

This resizes nicely with adaptive layouts also..

CSS example would be:

.centered-div {
   position:fixed;
   background-color:#fff;
   text-align:center;
   width:40%;
   right:0;
   margin-right:30%;
}

Correct use for angular-translate in controllers

EDIT: Please see the answer from PascalPrecht (the author of angular-translate) for a better solution.


The asynchronous nature of the loading causes the problem. You see, with {{ pageTitle | translate }}, Angular will watch the expression; when the localization data is loaded, the value of the expression changes and the screen is updated.

So, you can do that yourself:

.controller('FirstPageCtrl', ['$scope', '$filter', function ($scope, $filter) {
    $scope.$watch(
        function() { return $filter('translate')('HELLO_WORLD'); },
        function(newval) { $scope.pageTitle = newval; }
    );
});

However, this will run the watched expression on every digest cycle. This is suboptimal and may or may not cause a visible performance degradation. Anyway it is what Angular does, so it cant be that bad...

In C#, can a class inherit from another class and an interface?

I found the answer to the second part of my questions. Yes, a class can implement an interface that is in a different class as long that the interface is declared as public.

Using Mysql in the command line in osx - command not found?

for me the following commands worked:

$ brew install mysql

$ brew services start mysql

Add new column with foreign key constraint in one command

In MS SQL SERVER:

With user defined foreign key name

ALTER TABLE tableName
ADD columnName dataType,
CONSTRAINT fkName FOREIGN KEY(fkColumnName) 
   REFERENCES pkTableName(pkTableColumnName);

Without user defined foreign key name

ALTER TABLE tableName
ADD columnName dataType,
FOREIGN KEY(fkColumnName) REFERENCES pkTableName(pkTableColumnName);

How to exit an application properly

in this case I start Outlook and then close it

Dim ol 

Set ol = WScript.CreateObject("Outlook.Application") 'Starts Outlook

ol.quit 'Closes Outlook

How can I hide an HTML table row <tr> so that it takes up no space?

You can set

<table>
  <tr style="visibility: hidden"></tr>
</table> 

Putting HTML inside Html.ActionLink(), plus No Link Text?

Instead of using Html.ActionLink you can render a url via Url.Action

<a href="<%= Url.Action("Index", "Home") %>"><span>Text</span></a>
<a href="@Url.Action("Index", "Home")"><span>Text</span></a>

And to do a blank url you could have

<a href="<%= Url.Action("Index", "Home") %>"></a>
<a href="@Url.Action("Index", "Home")"></a>

AngularJS ng-click to go to another page (with Ionic framework)

If you simply want to go to another page, then what you might need is a link that looks like a button with a href like so:

<a href="/#/somepage.html" class="button">Back to Listings</a>

Hope this helps.

std::cin input with spaces?

You have to use cin.getline():

char input[100];
cin.getline(input,sizeof(input));

Reading a cell value in Excel vba and write in another Cell

The individual alphabets or symbols residing in a single cell can be inserted into different cells in different columns by the following code:

For i = 1 To Len(Cells(1, 1))
Cells(2, i) = Mid(Cells(1, 1), i, 1)
Next

If you do not want the symbols like colon to be inserted put an if condition in the loop.

Get all Attributes from a HTML element with Javascript/jQuery

Element.prototype.getA = function (a) {
        if (a) {
            return this.getAttribute(a);
        } else {
            var o = {};
            for(let a of this.attributes){
                o[a.name]=a.value;
            }
            return o;
        }
    }

having <div id="mydiv" a='1' b='2'>...</div> can use

mydiv.getA() // {id:"mydiv",a:'1',b:'2'}

Flushing buffers in C

Flushing the output buffers:

printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is

or

fprintf(fd, "Buffered, will be flushed");
fflush(fd);  //Prints to a file

Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.

Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf(), so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.

I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf() is an expensive operation (which is why it doesn't by default flush the buffer).


As far as flushing the input buffer (stdin), you should not do that. Flushing stdin is undefined behavior according to the C11 standard §7.21.5.2 part 2:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

On some systems, Linux being one as you can see in the man page for fflush(), there's a defined behavior but it's system dependent so your code will not be portable.

Now if you're worried about garbage "stuck" in the input buffer you can use fpurge() on that. See here for more on fflush() and fpurge()

How can I compare time in SQL Server?

One (possibly small) issue I have noted with the solutions so far is that they all seem to require a function call to process the comparison. This means that the query engine will need to do a full table scan to seek the rows you are after - and be unable to use an index. If the table is not going to get particularly large, this probably won't have any adverse affects (and you can happily ignore this answer).

If, on the other hand, the table could get quite large, the performance of the query could suffer.

I know you stated that you do not wish to compare the date part - but is there an actual date being stored in the datetime column, or are you using it to store only the time? If the latter, you can use a simple comparison operator, and this will reduce both CPU usage, and allow the query engine to use statistics and indexes (if present) to optimise the query.

If, however, the datetime column is being used to store both the date and time of the event, this obviously won't work. In this case if you can modify the app and the table structure, separate the date and time into two separate datetime columns, or create a indexed view that selects all the (relevant) columns of the source table, and a further column that contains the time element you wish to search for (use any of the previous answers to compute this) - and alter the app to query the view instead.

What is ANSI format?

Just in case your PC is not a "Western" PC and you don't know which code page is used, you can have a look at this page: National Language Support (NLS) API Reference

[Microsoft removed this reference, take it form web-archive National Language Support (NLS) API Reference

Or you can query your registry:

C:\>reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage /f ACP

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage
    ACP    REG_SZ    1252

End of search: 1 match(es) found.

C:\>

Firebug like plugin for Safari browser

The Safari built in dev tool is great. I have to admit that Firebug on Firefox is my long time favorite, but I think that the Safari tool do a great job too!

Python Requests throwing SSLError

Too late to the party I guess but I wanted to paste the fix for fellow wanderers like myself! So the following worked out for me on Python 3.7.x

Type the following in your terminal

pip install --upgrade certifi      # hold your breath..

Try running your script/requests again and see if it works (I'm sure it won't be fixed yet!). If it didn't work then try running the following command in the terminal directly

open /Applications/Python\ 3.6/Install\ Certificates.command  # please replace 3.6 here with your suitable python version

JSON Java 8 LocalDateTime format in Spring Boot

I am using Springboot 2.0.6 and for some reason, the app yml changes did not work. And also I had more requirements.

I tried creating ObjectMapper and marking it as Primary but spring boot complained that I already have jacksonObjectMapper as marked Primary!!

So this is what I did. I made changes to the internal mapper.

My Serializer and Deserializer are special - they deal with 'dd/MM/YYYY'; and while de-serializing - it tries its best to use 3-4 popular format to make sure I have some LocalDate.

@Autowired
ObjectMapper mapper;

@PostConstruct
public ObjectMapper configureMapper() {
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);

    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, true);
    mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);

    SimpleModule module = new SimpleModule();
    module.addDeserializer(LocalDate.class, new LocalDateDeserializer());
    module.addSerializer(LocalDate.class, new LocalDateSerializer());
    mapper.registerModule(module);

    return mapper;
}

jquery getting post action url

$('#signup').on("submit", function(event) {
    $form = $(this); //wrap this in jQuery

    alert('the action is: ' + $form.attr('action'));
});

Automatically scroll down chat div

It's hard to tell without knowing the HTML code, but I'd assume your div doesn't have a height set and/or doesn't allow overflow (e.g. through CSS height: 200px; overflow: auto).

I've made a working sample on jsfiddle: http://jsfiddle.net/hu4zqq4x/

I created some dummy HTML markup inside a div that is a) overflowing and b) has a set height. Scrolling is done through calling the function

function getMessages(letter) {
    var div = $("#messages");
    div.scrollTop(div.prop('scrollHeight'));
}

, in this case once on 'documentReady'.

prop('scrollHeight') will access the value of the property on the first element in the set of matched elements.

How to auto-generate a C# class file from a JSON string

Five options:

Pros and Cons:

  • jsonclassgenerator converts to PascalCase but the others do not.

  • app.quicktype.io has some logic to recognize dictionaries and handle JSON properties whose names are invalid c# identifiers.

Deleting all files from a folder using PHP?

I've built a really simple package called "Pusheh". Using it, you can clear a directory or remove a directory completely (Github link). It's available on Packagist, also.

For instance, if you want to clear Temp directory, you can do:

Pusheh::clearDir("Temp");

// Or you can remove the directory completely
Pusheh::removeDirRecursively("Temp");

If you're interested, see the wiki.

Creating a button in Android Toolbar

They are called menu items or action buttons in toolbar/actionbar. Here you have Google tutorial how it works and how to add them https://developer.android.com/training/basics/actionbar/adding-buttons.html

Does MS Access support "CASE WHEN" clause if connect with ODBC?

Since you are using Access to compose the query, you have to stick to Access's version of SQL.

To choose between several different return values, use the switch() function. So to translate and extend your example a bit:

select switch(
  age > 40, 4,
  age > 25, 3,
  age > 20, 2,
  age > 10, 1,
  true, 0
) from demo

The 'true' case is the default one. If you don't have it and none of the other cases match, the function will return null.

The Office website has documentation on this but their example syntax is VBA and it's also wrong. I've given them feedback on this but you should be fine following the above example.

Rails 4 - passing variable to partial

Either

render partial: 'user', locals: {size: 30}

Or

render 'user', size: 30

To use locals, you need partial. Without the partial argument, you can just list variables directly (not within locals)

What is the syntax for adding an element to a scala.collection.mutable.Map?

var map:Map[String, String] = Map()

var map1 = map + ("red" -> "#FF0000")

println(map1)

Number of days between two dates in Joda-Time

DateTime  dt  = new DateTime(laterDate);        

DateTime newDate = dt.minus( new  DateTime ( previousDate ).getMillis());

System.out.println("No of days : " + newDate.getDayOfYear() - 1 );    

How to get just numeric part of CSS property with jQuery?

Id go for:

Math.abs(parseFloat($(this).css("property")));

Python - round up to the nearest ten

You can use math.ceil() to round up, and then multiply by 10

import math

def roundup(x):
    return int(math.ceil(x / 10.0)) * 10

To use just do

>>roundup(45)
50

How to insert default values in SQL table?

To insert the default values you should omit them something like this :

Insert into Table (Field2) values(5)

All other fields will have null or their default values if it has defined.

Angular 6: How to set response type as text while making http call

On your backEnd, you should add:

@RequestMapping(value="/blabla",  produces="text/plain" , method = RequestMethod.GET)

On the frontEnd (Service):

methodBlabla() 
{
  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
  return this.http.get(this.url,{ headers, responseType: 'text'});
}

Write a file in UTF-8 using FileWriter (Java)?

Ditch FileWriter and FileReader, which are useless exactly because they do not allow you to specify the encoding. Instead, use

new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)

and

new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);

CORS: credentials mode is 'include'

If it helps, I was using centrifuge with my reactjs app, and, after checking some comments below, I looked at the centrifuge.js library file, which in my version, had the following code snippet:

if ('withCredentials' in xhr) {
 xhr.withCredentials = true;
}

After I removed these three lines, the app worked fine, as expected.

Hope it helps!

HTML tag <a> want to add both href and onclick working

You already have what you need, with a minor syntax change:

<a href="www.mysite.com" onclick="return theFunction();">Item</a>

<script type="text/javascript">
    function theFunction () {
        // return true or false, depending on whether you want to allow the `href` property to follow through or not
    }
</script>

The default behavior of the <a> tag's onclick and href properties is to execute the onclick, then follow the href as long as the onclick doesn't return false, canceling the event (or the event hasn't been prevented)

What values can I pass to the event attribute of the f:ajax tag?

I just input some value that I knew was invalid and here is the output:

'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.

So values you can pass to event are

  • click
  • dblclick
  • keydown
  • mousedown
  • mousemove
  • mouseover
  • mouseup

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

You can try this:

pushd ../
maven install [...]
popd

View RDD contents in Python Spark?

You can simply collect the entire RDD (which will return a list of rows) and print said list:

print(wc.collect())

How to plot data from multiple two column text files with legends in Matplotlib?

Assume your file looks like this and is named test.txt (space delimited):

1 2
3 4
5 6
7 8

Then:

#!/usr/bin/python

import numpy as np
import matplotlib.pyplot as plt

with open("test.txt") as f:
    data = f.read()

data = data.split('\n')

x = [row.split(' ')[0] for row in data]
y = [row.split(' ')[1] for row in data]

fig = plt.figure()

ax1 = fig.add_subplot(111)

ax1.set_title("Plot title...")    
ax1.set_xlabel('your x label..')
ax1.set_ylabel('your y label...')

ax1.plot(x,y, c='r', label='the data')

leg = ax1.legend()

plt.show()

Example plot:

I find that browsing the gallery of plots on the matplotlib site helpful for figuring out legends and axes labels.

How to store array or multiple values in one column

You have a couple of questions here, so I'll address them separately:

I need to store a number of selected items in one field in a database

My general rule is: don't. This is something which all but requires a second table (or third) with a foreign key. Sure, it may seem easier now, but what if the use case comes along where you need to actually query for those items individually? It also means that you have more options for lazy instantiation and you have a more consistent experience across multiple frameworks/languages. Further, you are less likely to have connection timeout issues (30,000 characters is a lot).

You mentioned that you were thinking about using ENUM. Are these values fixed? Do you know them ahead of time? If so this would be my structure:

Base table (what you have now):

| id primary_key sequence
| -- other columns here.

Items table:

| id primary_key sequence
| descript VARCHAR(30) UNIQUE

Map table:

| base_id  bigint
| items_id bigint

Map table would have foreign keys so base_id maps to Base table, and items_id would map to the items table.

And if you'd like an easy way to retrieve this from a DB, then create a view which does the joins. You can even create insert and update rules so that you're practically only dealing with one table.

What format should I use store the data?

If you have to do something like this, why not just use a character delineated string? It will take less processing power than a CSV, XML, or JSON, and it will be shorter.

What column type should I use store the data?

Personally, I would use TEXT. It does not sound like you'd gain much by making this a BLOB, and TEXT, in my experience, is easier to read if you're using some form of IDE.

Simulate Keypress With jQuery

Another option:

$(el).trigger({type: 'keypress', which: 13, keyCode: 13});

http://api.jquery.com/trigger/

Getting Hour and Minute in PHP

print date('H:i');
$var = date('H:i');

Should do it, for the current time. Use a lower case h for 12 hour clock instead of 24 hour.

More date time formats listed here.

How can I pass a parameter to a Java Thread?

via constructor of a Runnable or Thread class

class MyThread extends Thread {

    private String to;

    public MyThread(String to) {
        this.to = to;
    }

    @Override
    public void run() {
        System.out.println("hello " + to);
    }
}

public static void main(String[] args) {
    new MyThread("world!").start();
}

How to use S_ISREG() and S_ISDIR() POSIX Macros?

You're using S_ISREG() and S_ISDIR() correctly, you're just using them on the wrong thing.

In your while((dit = readdir(dip)) != NULL) loop in main, you're calling stat on currentPath over and over again without changing currentPath:

if(stat(currentPath, &statbuf) == -1) {
    perror("stat");
    return errno;
}

Shouldn't you be appending a slash and dit->d_name to currentPath to get the full path to the file that you want to stat? Methinks that similar changes to your other stat calls are also needed.

How to set Spinner Default by its Value instead of Position?

Finally, i solved the problem by using following way, in which the position of the spinner can be get by its string

private int getPostiton(String locationid,Cursor cursor)
{
    int i;
    cursor.moveToFirst(); 
    for(i=0;i< cursor.getCount()-1;i++)
    {  

        String locationVal = cursor.getString(cursor.getColumnIndex(RoadMoveDataBase.LT_LOCATION));  
        if(locationVal.equals(locationid))
        { 
            position = i+1;  
            break;
        }
        else
        {
            position = 0;
        }
        cursor.moveToNext();  
    } 

Calling the method

    Spinner location2 = (Spinner)findViewById(R.id.spinner1);
    int location2id = getPostiton(cursor.getString(3),cursor);
    location2.setSelection(location2id);

I hope it will help for some one..

String formatting in Python 3

That line works as-is in Python 3.

>>> sys.version
'3.2 (r32:88445, Oct 20 2012, 14:09:29) \n[GCC 4.5.2]'
>>> "(%d goals, $%d)" % (self.goals, self.penalties)
'(1 goals, $2)'

Can local storage ever be considered secure?

Not accessible to any webpage (true) but is easily accessible and easily editible via dev tools, such as chrome (ctl-shift-J). Therefore, custom crypto required before storing the value.

But, if javascript needs to decrypt (to validate) then the decrypt algorithm is exposed and can be manipulated.

Javascript needs a fully secure container and the ability to properly implement private variables and functions that are available only to the js interpreter. But, this violates user security - since tracking data can be used with impunity.

Consequently, javascript will never be fully secure.

Python, remove all non-alphabet chars from string

You can use the re.sub() function to remove these characters:

>>> import re
>>> re.sub("[^a-zA-Z]+", "", "ABC12abc345def")
'ABCabcdef'

re.sub(MATCH PATTERN, REPLACE STRING, STRING TO SEARCH)

  • "[^a-zA-Z]+" - look for any group of characters that are NOT a-zA-z.
  • "" - Replace the matched characters with ""