Programs & Examples On #Nosuchmethoderror

The Java `Error` thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.

How do I fix a NoSuchMethodError?

I have just solved this error by restarting my Eclipse and run the applcation. The reason for my case may because I replace my source files without closing my project or Eclipse. Which caused different version of classes I was using.

"Error: Main method not found in class MyClass, please define the main method as..."

The problem is that you do not have a public void main(String[] args) method in the class you attempt to invoke.

It

  • must be static
  • must have exactly one String array argument (which may be named anything)
  • must be spelled m-a-i-n in lowercase.

Note, that you HAVE actually specified an existing class (otherwise the error would have been different), but that class lacks the main method.

checking for typeof error in JS

var myError = new Error('foo');
myError instanceof Error // true
var myString = "Whatever";
myString instanceof Error // false

Only problem with this is

myError instanceof Object // true

An alternative to this would be to use the constructor property.

myError.constructor === Object // false
myError.constructor === String // false
myError.constructor === Boolean // false
myError.constructor === Symbol // false
myError.constructor === Function // false
myError.constructor === Error // true

Although it should be noted that this match is very specific, for example:

myError.constructor === TypeError // false

Getting Git to work with a proxy server - fails with "Request timed out"

After tirelessly trying every solution on this page, my work around was to use and SSH key instead!

  1. Open Git Bash
  2. $ ssh-keygen.exe -t rsa -C
  3. Open your Git provider (Github, Bitbucket, etc.)
  4. Add copy the id_rsa.pub file contents into Git provider's input page (check your profile)

Absolute position of an element on the screen using jQuery

See .offset() here in the jQuery doc. It gives the position relative to the document, not to the parent. You perhaps have .offset() and .position() confused. If you want the position in the window instead of the position in the document, you can subtract off the .scrollTop() and .scrollLeft() values to account for the scrolled position.

Here's an excerpt from the doc:

The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.

To combine these:

var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft(); 

You can try it here (scroll to see the numbers change): http://jsfiddle.net/jfriend00/hxRPQ/

Setting width to wrap_content for TextView through code

There is another way to achieve same result. In case you need to set only one parameter, for example 'height':

TextView textView = (TextView)findViewById(R.id.text_view);
ViewGroup.LayoutParams params = textView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(params);

How to invoke bash, run commands inside the new shell, and then give control back to user?

Executing commands in a background shell

Just add & to the end of the command, e.g:

bash -c some_command && another_command &

How to iterate object keys using *ngFor

If you are using a map() operator on your response,you could maybe chain a toArray() operator to it...then you should be able to iterate through newly created array...at least that worked for me :)

Difference between "enqueue" and "dequeue"

In my opinion one of the worst chosen word's to describe the process, as it is not related to anything in real-life or similar. In general the word "queue" is very bad as if pronounced, it sounds like the English character "q". See the inefficiency here?

enqueue: to place something into a queue; to add an element to the tail of a queue;

dequeue to take something out of a queue; to remove the first available element from the head of a queue

source: https://www.thefreedictionary.com

How to do fade-in and fade-out with JavaScript and CSS

Heres my code for a fade in/out toggle functions.

fadeIn: function (len) {
                var obj = this.e;
                obj.style.display = '';
                var op = 0; 
                var timer = setInterval(function () {
                    if (op >= 1 || op >= 1.0){
                        console.log('done', op)
                        clearInterval(timer);
                    }
                    obj.style.opacity = op.toFixed(1);
                    op += 0.1;
                    console.log(obj.style.opacity);
                }, len);
                return this;
            },
    fadeOut: function (len) {
                var obj = this.e;
                var op = 1; 
                var timer = setInterval(function () {
                    if (op <= 0){
                        clearInterval(timer);
                        console.log('done', op)
                        obj.style.display = 'none';
                    }
                    obj.style.opacity = op.toFixed(1);
                    op -= 0.1;
                    console.log(obj.style.opacity)
                }, len);
                return this;
            },

This was from a jQuery style lib i did. hope it's helpfull. link to lib on cloud9: https://c9.io/christopherdumas/magik_wb

How to scan multiple paths using the @ComponentScan annotation?

I use:

@ComponentScan(basePackages = {"com.package1","com.package2","com.package3", "com.packagen"})

Private properties in JavaScript ES6 classes

Reading the previous answer i thought that this example can summarise the above solutions

const friend = Symbol('friend');

const ClassName = ((hidden, hiddenShared = 0) => {

    class ClassName {
        constructor(hiddenPropertyValue, prop){
            this[hidden] = hiddenPropertyValue * ++hiddenShared;
            this.prop = prop
        }

        get hidden(){
            console.log('getting hidden');
            return this[hidden];
        }

        set [friend](v){
            console.log('setting hiddenShared');
            hiddenShared = v;
        }

        get counter(){
            console.log('getting hiddenShared');
            return hiddenShared;
        }

        get privileged(){
            console.log('calling privileged method');
            return privileged.bind(this);
        }
    }

    function privileged(value){
        return this[hidden] + value;
    }

    return ClassName;
})(Symbol('hidden'), 0);

const OtherClass = (() => class OtherClass extends ClassName {
    constructor(v){
        super(v, 100);
        this[friend] = this.counter - 1;
    }
})();

UPDATE

now is it possible to make true private properties and methods (at least on chrome based browsers for now).

The syntax is pretty neat

class MyClass {
    #privateProperty = 1
    #privateMethod() { return 2 }
    static #privateStatic = 3
    static #privateStaticMethod(){return 4}
    static get #privateStaticGetter(){return 5}

    // also using is quite straightforward
    method(){
        return (
            this.#privateMethod() +
            this.#privateProperty +
            MyClass.#privateStatic +
            MyClass.#privateStaticMethod() +
            MyClass.#privateStaticGetter
        )
    }
}

new MyClass().method()
// returns 15

Note that for retrieving static references you wouldn't use this.constructor.#private, because it would brake its subclasses. You must use a reference to the proper class in order to retrieve its static private references (that are available only inside the methods of that class), ie MyClass.#private.

What does axis in pandas mean?

axis = 0 means up to down axis = 1 means left to right

sums[key] = lang_sets[key].iloc[:,1:].sum(axis=0)

Given example is taking sum of all the data in column == key.

How to install older version of node.js on Windows?

For windows, best is: nvm-windows

1)install the .exe

2)restart (otherwise, nvm will not be undefined)

3)run CMD as admin,

4)nvm use 5.6.0

Note: You MUST run as Admin to switch node version every time.

jQuery-- Populate select from json

fiddle

var $select = $('#down'); 
$select.find('option').remove();  
$.each(temp,function(key, value) 
{
    $select.append('<option value=' + key + '>' + value + '</option>');
});

How to get the first item from an associative PHP array?

Use reset() function to get the first item out of that array without knowing the key for it like this.

_x000D_
_x000D_
$value = array('foo' => 400, 'bar' => 'xyz');_x000D_
echo reset($value);
_x000D_
_x000D_
_x000D_

output // 400

How do you run a crontab in Cygwin on Windows?

The correct syntax to install cron in cygwin as Windows service is to pass -n as argument and not -D:

cygrunsrv --install cron --path /usr/sbin/cron --args -n

-D returns usage error when starting cron in cygwin:

$

$cygrunsrv --install cron --path /usr/sbin/cron --args -D

$cygrunsrv --start cron

cygrunsrv: Error starting a service: QueryServiceStatus: Win32 error 1062:

The service has not been started.

$cat /var/log/cron.log

cron: unknown option -- D

usage: /usr/sbin/cron [-n] [-x [ext,sch,proc,parc,load,misc,test,bit]]

$

Below page has a good explanation.

Installing & Configuring the Cygwin Cron Service in Windows: https://www.davidjnice.com/cygwin_cron_service.html

P.S. I had to run Cygwin64 Terminal on my Windows 10 PC as administrator in order to install cron as Windows service.

How to compare two colors for similarity/difference

Just an idea that first came to my mind (sorry if stupid). Three components of colors can be assumed 3D coordinates of points and then you could calculate distance between points.

F.E.

Point1 has R1 G1 B1
Point2 has R2 G2 B2

Distance between colors is

d=sqrt((r2-r1)^2+(g2-g1)^2+(b2-b1)^2)

Percentage is

p=d/sqrt((255)^2+(255)^2+(255)^2)

How to Solve Max Connection Pool Error

Check against any long running queries in your database.

Increasing your pool size will only make your webapp live a little longer (and probably get a lot slower)

You can use sql server profiler and filter on duration / reads to see which querys need optimization.

I also see you're probably keeping a global connection?

blnMainConnectionIsCreatedLocal

Let .net do the pooling for you and open / close your connection with a using statement.

Suggestions:

  1. Always open and close a connection like this, so .net can manage your connections and you won't run out of connections:

        using (SqlConnection conn = new SqlConnection(connectionString))
        {
         conn.Open();
         // do some stuff
        } //conn disposed
    
  2. As I mentioned, check your query with sql server profiler and see if you can optimize it. Having a slow query with many requests in a web app can give these timeouts too.

Assigning variables with dynamic names in Java

This is not how you do things in Java. There are no dynamic variables in Java. Java variables have to be declared in the source code1.

Depending on what you are trying to achieve, you should use an array, a List or a Map; e.g.

int n[] = new int[3];
for (int i = 0; i < 3; i++) {
    n[i] = 5;
}

List<Integer> n = new ArrayList<Integer>();
for (int i = 1; i < 4; i++) {
    n.add(5);
}

Map<String, Integer> n = new HashMap<String, Integer>();
for (int i = 1; i < 4; i++) {
    n.put("n" + i, 5);
}

It is possible to use reflection to dynamically refer to variables that have been declared in the source code. However, this only works for variables that are class members (i.e. static and instance fields). It doesn't work for local variables. See @fyr's "quick and dirty" example.

However doing this kind of thing unnecessarily in Java is a bad idea. It is inefficient, the code is more complicated, and since you are relying on runtime checking it is more fragile. And this is not "variables with dynamic names". It is better described as dynamic access to variables with static names.


1 - That statement is slightly inaccurate. If you use BCEL or ASM, you can "declare" the variables in the bytecode file. But don't do it! That way lies madness!

Fatal error: iostream: No such file or directory in compiling C program using GCC

Neither <iostream> nor <iostream.h> are standard C header files. Your code is meant to be C++, where <iostream> is a valid header. Use g++ (and a .cpp file extension) for C++ code.

Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream> and using namespace std;, and replace cout << endl; with putchar('\n');... I advise compiling using C99 (eg. gcc -std=c99)

What do these operators mean (** , ^ , %, //)?

  • **: exponentiation
  • ^: exclusive-or (bitwise)
  • %: modulus
  • //: divide with integral result (discard remainder)

command/usr/bin/codesign failed with exit code 1- code sign error

I Followed all the things mentioned in this thread but still facing same issue-

/usr/bin/codesign --force --sign A7F8FCD694D7923A3E57826398C3380E2E5A5446 --entitlements  unknown error -1=ffffffffffffffff
Command /usr/bin/codesign failed with exit code 1

I have configured Automatic signing with my code base which will work with xcode run as well as xcodebuild run from terminal from my machine but it gives above error when I run it on jenkins pipeline or try to run on terminal from remotely connected machine

In my case Automatic signing is not working if access remotely. because I need to open keychain before archive using

security unlock-keychain -p "newpassword" "/Users/xyz/Library/Keychains/login.keychain"

keychain passwords & login password for macOS X user was different I change it to new same password and it works for me.

Getting list of files in documents folder

Swift 5

// Get the document directory url
let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

do {
    // Get the directory contents urls (including subfolders urls)
    let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
    print(directoryContents)

    // if you want to filter the directory contents you can do like this:
    let mp3Files = directoryContents.filter{ $0.pathExtension == "mp3" }
    print("mp3 urls:",mp3Files)
    let mp3FileNames = mp3Files.map{ $0.deletingPathExtension().lastPathComponent }
    print("mp3 list:", mp3FileNames)

} catch {
    print(error)
}

Java 6 Unsupported major.minor version 51.0

add jdk8 or higher version at JAVA_HOME and path.

add JAVA_HOME add C:\ProgramFiles\Java\jdk1.8.0_201

For Path =>

add %MAVEN_HOME%\bin

and finally restart your pc.

How to implement Rate It feature in Android App

As you see from the other post you have linked, there isn't a way for the app to know if the user has left a review or not. And for good reason.

Think about it, if an app could tell if the user has left a review or not, the developer could restrict certain features that would only be unlocked if the user leaves a 5/5 rating. This would lead the other users of Google Play to not trust the reviews and would undermine the rating system.

The alternative solutions I have seen is that the app reminds the user to submit a rating whenever the app is opened a specific number of times, or a set interval. For example, on every 10th time the app is opened, ask the user to leave a rating and provide a "already done" and "remind me later" button. Keep showing this message if the user has chosen to remind him/her later. Some other apps developers show this message with an increasing interval (like, 5, 10, 15nth time the app is opened), because if a user hasn't left a review on the, for example, 100th time the app was opened, it's probably likely s/he won't be leaving one.

This solution isn't perfect, but I think it's the best you have for now. It does lead you to trust the user, but realize that the alternative would mean a potentially worse experience for everyone in the app market.

How to convert datetime to integer in python

When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like "2018-11-03" must be like 20181103 in int for that you have to 2018*10000 + 100* 11 + 3

Similarly another example, "2018-11-03 10:02:05" must be like 20181103100205 in int

Explanatory Code

dt = datetime(2018,11,3,10,2,5)
print (dt)

#print (dt.timestamp()) # unix representation ... not useful when converting to int

print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100  + dt.day)
print (int(dt.strftime("%Y%m%d")))

print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000  +  dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))

General Function

To avoid that doing manually use below function

def datetime_to_int(dt):
    return int(dt.strftime("%Y%m%d%H%M%S"))

File upload progress bar with jQuery

This solved my problem

var url = "http://localhost/tech1/index.php?route=app/upload/ajax"; 

$.ajax({
  xhr: function() {
    var xhr = new window.XMLHttpRequest();

    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        percentComplete = parseInt(percentComplete * 100);
var $link = $('.'+ids);
          var $img = $link.find('i'); 
          $link.html('Uploading..('+percentComplete+'%)');
          $link.append($img);
      }
    }, false);

    return xhr;
  },
  url: url,
  type: "POST",
  data: JSON.stringify(uploaddata),
  contentType: "application/json",
  dataType: "json",
  success: function(result) {
    console.log(result);
  }
});

EditText onClickListener in Android

Normally, you want maximum compatibility with EditText's normal behaviour.

So you should not use android:focusable="false" as, yes, the view will just not be focusable anymore which looks bad. The background drawable will not show its "pressed" state anymore, for example.

What you should do instead is the following:

myEditText.setInputType(InputType.TYPE_NULL);
myEditText.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // showMyDialog();
    }
});
myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            // showMyDialog();
        }
    }
});

By setting the input type to TYPE_NULL, you prevent the software keyboard from popping up.

By setting the OnClickListener and OnFocusChangeListener, you make sure that your dialog will always open when the user clicks into the EditText field, both when it gains focus (first click) and on subsequent clicks.

Just setting android:inputType="none" or setInputType(InputType.TYPE_NULL) is not always enough. For some devices, you should set android:editable="false" in XML as well, although it is deprecated. If it does not work anymore, it will just be ignored (as all XML attributes that are not supported).

Pass react component as props

Using this.props.children is the idiomatic way to pass instantiated components to a react component

const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>

When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div or span):

const Label = props => <span>{props.children}</span>
const Button = props => {
    const Inner = props.inner; // Note: variable name _must_ start with a capital letter 
    return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>

If what you want to do is to pass a children-like parameter as a prop, you can do that:

const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />

After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.

substring of an entire column in pandas dataframe

Use the str accessor with square brackets:

df['col'] = df['col'].str[:9]

Or str.slice:

df['col'] = df['col'].str.slice(0, 9)

Typescript input onchange event.target.value

as HTMLInputElement works for me

C# Encoding a text string with line breaks

Try \n\n , it will work! :)

public async Task AjudaAsync(IDialogContext context, LuisResult result){
await context.PostAsync("How can I help you? \n\n 1.To Schedule \n\n 2.Consult");
context.Wait(MessageReceived);
}

How to get HTTP Response Code using Selenium WebDriver

You could try Mobilenium (https://github.com/rafpyprog/Mobilenium), a python package that binds BrowserMob Proxy and Selenium.

An usage example:

>>> from mobilenium import mobidriver
>>>
>>> browsermob_path = 'path/to/browsermob-proxy'
>>> mob = mobidriver.Firefox(browsermob_binary=browsermob_path)
>>> mob.get('http://python-requests.org')
301
>>> mob.response['redirectURL']
'http://docs.python-requests.org'
>>> mob.headers['Content-Type']
'application/json; charset=utf8'
>>> mob.title
'Requests: HTTP for Humans \u2014 Requests 2.13.0 documentation'
>>> mob.find_elements_by_tag_name('strong')[1].text
'Behold, the power of Requests'

psql - save results of command to a file

This approach will work with any psql command from the simplest to the most complex without requiring any changes or adjustments to the original command.

NOTE: For Linux servers.


  • Save the contents of your command to a file

MODEL

read -r -d '' FILE_CONTENT << 'HEREDOC'
[COMMAND_CONTENT]

HEREDOC
echo -n "$FILE_CONTENT" > sqlcmd

EXAMPLE

read -r -d '' FILE_CONTENT << 'HEREDOC'
DO $f$
declare
    curid INT := 0;
    vdata BYTEA;
    badid VARCHAR;
    loc VARCHAR;
begin
FOR badid IN SELECT some_field FROM public.some_base LOOP
    begin
    select 'ctid - '||ctid||'pagenumber - '||(ctid::text::point) [0]::bigint
        into loc
        from public.some_base where some_field = badid;
        SELECT file||' '
        INTO vdata
        FROM public.some_base where some_field = badid;
    exception
        when others then
        raise notice 'Block/PageNumber - % ',loc;
            raise notice 'Corrupted id - % ', badid;
            --return;
    end;
end loop;
end;
$f$;

HEREDOC
echo -n "$FILE_CONTENT" > sqlcmd
  • Run the command

MODEL

sudo -u postgres psql [some_db] -c "$(cat sqlcmd)" >>sqlop 2>&1

EXAMPLE

sudo -u postgres psql some_db -c "$(cat sqlcmd)" >>sqlop 2>&1

  • View/track your command output

cat sqlop

Done! Thanks! =D

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

It looks like you're trying to run it on a version of ASP.NET which is running CLR v2. It's hard to know exactly what's going on without more information about how you've deployed it, what version of IIS you're running etc (and to be frank I wouldn't be very much help at that point anyway, though others would). But basically, check your IIS and ASP.NET set-up, and make sure that everything is running v4. Check your application pool configuration, etc.

Grunt watch error - Waiting...Fatal error: watch ENOSPC

After doing some research found the solution. Run the below command.

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

For Arch Linux add this line to /etc/sysctl.d/99-sysctl.conf:

fs.inotify.max_user_watches=524288

Apply a theme to an activity in Android?

You can apply a theme to any activity by including android:theme inside <activity> inside manifest file.

For example:

  1. <activity android:theme="@android:style/Theme.Dialog">
  2. <activity android:theme="@style/CustomTheme">

And if you want to set theme programatically then use setTheme() before calling setContentView() and super.onCreate() method inside onCreate() method.

Get absolute path of initially run script

If you're looking for the absolute path relative to the server root, I've found that this works well:

$_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['SCRIPT_NAME'])

Programmatically check Play Store for app updates

Google introduced In-app updates feature, (https://developer.android.com/guide/app-bundle/in-app-updates) it works on Lollipop+ and gives you the ability to ask the user for an update with a nice dialog (FLEXIBLE) or with mandatory full-screen message (IMMEDIATE).

Here is how Flexible update will look like: enter image description here

and here is Immedtiate update flow: enter image description here

You can check my answer here https://stackoverflow.com/a/56808529/5502121 to get the complete sample code of implementing both Flexible and Immediate update flows. Hope it helps!

Selection with .loc in python

pd.DataFrame.loc can take one or two indexers. For the rest of the post, I'll represent the first indexer as i and the second indexer as j.

If only one indexer is provided, it applies to the index of the dataframe and the missing indexer is assumed to represent all columns. So the following two examples are equivalent.

  1. df.loc[i]
  2. df.loc[i, :]

Where : is used to represent all columns.

If both indexers are present, i references index values and j references column values.


Now we can focus on what types of values i and j can assume. Let's use the following dataframe df as our example:

    df = pd.DataFrame([[1, 2], [3, 4]], index=['A', 'B'], columns=['X', 'Y'])

loc has been written such that i and j can be

  1. scalars that should be values in the respective index objects

    df.loc['A', 'Y']
    
    2
    
  2. arrays whose elements are also members of the respective index object (notice that the order of the array I pass to loc is respected

    df.loc[['B', 'A'], 'X']
    
    B    3
    A    1
    Name: X, dtype: int64
    
    • Notice the dimensionality of the return object when passing arrays. i is an array as it was above, loc returns an object in which an index with those values is returned. In this case, because j was a scalar, loc returned a pd.Series object. We could've manipulated this to return a dataframe if we passed an array for i and j, and the array could've have just been a single value'd array.

      df.loc[['B', 'A'], ['X']]
      
         X
      B  3
      A  1
      
  3. boolean arrays whose elements are True or False and whose length matches the length of the respective index. In this case, loc simply grabs the rows (or columns) in which the boolean array is True.

    df.loc[[True, False], ['X']]
    
       X
    A  1
    

In addition to what indexers you can pass to loc, it also enables you to make assignments. Now we can break down the line of code you provided.

iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
  1. iris_data['class'] == 'versicolor' returns a boolean array.
  2. class is a scalar that represents a value in the columns object.
  3. iris_data.loc[iris_data['class'] == 'versicolor', 'class'] returns a pd.Series object consisting of the 'class' column for all rows where 'class' is 'versicolor'
  4. When used with an assignment operator:

    iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
    

    We assign 'Iris-versicolor' for all elements in column 'class' where 'class' was 'versicolor'

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

They both convert a String to a double value but wherease the parseDouble() method returns the primitive double value, the valueOf() method further converts the primitive double to a Double wrapper class object which contains the primitive double value.

The conversion from String to primitive double may throw NFE(NumberFormatException) if the value in String is not convertible into a primitive double.

how to reference a YAML "setting" from elsewhere in the same YAML file?

I've create a library, available on Packagist, that performs this function: https://packagist.org/packages/grasmash/yaml-expander

Example YAML file:

type: book
book:
  title: Dune
  author: Frank Herbert
  copyright: ${book.author} 1965
  protaganist: ${characters.0.name}
  media:
    - hardcover
characters:
  - name: Paul Atreides
    occupation: Kwisatz Haderach
    aliases:
      - Usul
      - Muad'Dib
      - The Preacher
  - name: Duncan Idaho
    occupation: Swordmaster
summary: ${book.title} by ${book.author}
product-name: ${${type}.title}

Example logic:

// Parse a yaml string directly, expanding internal property references.
$yaml_string = file_get_contents("dune.yml");
$expanded = \Grasmash\YamlExpander\Expander::parse($yaml_string);
print_r($expanded);

Resultant array:

array (
  'type' => 'book',
  'book' => 
  array (
    'title' => 'Dune',
    'author' => 'Frank Herbert',
    'copyright' => 'Frank Herbert 1965',
    'protaganist' => 'Paul Atreides',
    'media' => 
    array (
      0 => 'hardcover',
    ),
  ),
  'characters' => 
  array (
    0 => 
    array (
      'name' => 'Paul Atreides',
      'occupation' => 'Kwisatz Haderach',
      'aliases' => 
      array (
        0 => 'Usul',
        1 => 'Muad\'Dib',
        2 => 'The Preacher',
      ),
    ),
    1 => 
    array (
      'name' => 'Duncan Idaho',
      'occupation' => 'Swordmaster',
    ),
  ),
  'summary' => 'Dune by Frank Herbert',
);

Change values of select box of "show 10 entries" of jquery datatable

$(document).ready(function() {
    $('#example').dataTable( {
    "aLengthMenu": [[25, 50, 75, -1], [25, 50, 75, "All"]],
    "pageLength": 25
    } );
} );

aLengthMenu : This parameter allows you to readily specify the entries in the length drop down menu that DataTables shows when pagination is enabled. It can be either a 1D array of options which will be used for both the displayed option and the value, or a 2D array which will use the array in the first position as the value, and the array in the second position as the displayed options (useful for language strings such as 'All').

Update

Since DataTables v1.10, the options you are looking for are pageLength and lengthMenu

MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

A "BEFORE-INSERT"-trigger is the only way to realize same-table updates on an insert, and is only possible from MySQL 5.5+. However, the value of an auto-increment field is only available to an "AFTER-INSERT" trigger - it defaults to 0 in the BEFORE-case. Therefore the following example code which would set a previously-calculated surrogate key value based on the auto-increment value id will compile, but not actually work since NEW.id will always be 0:

create table products(id int not null auto_increment, surrogatekey varchar(10), description text);
create trigger trgProductSurrogatekey before insert on product
for each row set NEW.surrogatekey = 
  (select surrogatekey from surrogatekeys where id = NEW.id);

What's the difference between a method and a function?

Historically, there may have been a subtle difference with a "method" being something which does not return a value, and a "function" one which does.Each language has its own lexicon of terms with special meaning.

In "C", the word "function" means a program routine.

In Java, the term "function" does not have any special meaning. Whereas "method" means one of the routines that forms the implementation of a class.

In C# that would translate as:

public void DoSomething() {} // method
public int DoSomethingAndReturnMeANumber(){} // function

But really, I re-iterate that there is really no difference in the 2 concepts. If you use the term "function" in informal discussions about Java, people will assume you meant "method" and carry on. Don't use it in proper documents or presentations about Java, or you will look silly.

Error:(1, 0) Plugin with id 'com.android.application' not found

I was using IntelliJ IDEA 13.1.5 and faced with the same problem after I changed versions of Picasso and Retrofit in dependencies in build.gradle file. I tried use many solutions, but without result. Then I cloned my project from remote git (where I pushed it before changing versions of dependencies) and it worked! After that I just closed current project and imported old project from Gradle file to IntelliJ IDEA again and it worked too! So, I think it was strange bug in intersection of IDEA, Gradle and Android plugin. I hope this information can be useful for IDEA-users or anyone else.

How does DHT in torrents work?

What happens with bittorrent and a DHT is that at the beginning bittorrent uses information embedded in the torrent file to go to either a tracker or one of a set of nodes from the DHT. Then once it finds one node, it can continue to find others and persist using the DHT without needing a centralized tracker to maintain it.

The original information bootstraps the later use of the DHT.

JavaScript: How do I print a message to the error console?

If you use Safari, you can write

console.log("your message here");

and it appears right on the console of the browser.

Warning :-Presenting view controllers on detached view controllers is discouraged

Try this code

UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:<your ViewController object>];

[self.view.window.rootViewController presentViewController:navigationController animated:YES completion:nil];

Printing pointers in C

You can't change the value (i.e., address of) a static array. In technical terms, the lvalue of an array is the address of its first element. Hence s == &s. It's just a quirk of the language.

How can I convert string to datetime with format specification in JavaScript?

Moment.js will handle this:

var momentDate = moment('23.11.2009 12:34:56', 'DD.MM.YYYY HH:mm:ss');
var date = momentDate.;

Best way to pretty print a hash

require 'pp'
pp my_hash

Use pp if you need a built-in solution and just want reasonable line breaks.

Use awesome_print if you can install a gem. (Depending on your users, you may wish to use the index:false option to turn off displaying array indices.)

Adding Google Translate to a web site

<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

"installation of package 'FILE_PATH' had non-zero exit status" in R

Try use this:

    apt-get install r-base-dev

It will be help. After then I could makeinstall.packages('//package_name')

Where does the iPhone Simulator store its data?

For Xcode 4.6 it gets stored in the following path...

/Users/[currentuser]/Library/Application Support/iPhone Simulator/6.1/Applications/

To know it programmatically use the following code

  NSLog(@"path:%@",[[NSBundle mainBundle]bundlePath]);

Accessing Objects in JSON Array (JavaScript)

Use a loop

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

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

How to set multiple commands in one yaml file with Kubernetes?

IMHO the best option is to use YAML's native block scalars. Specifically in this case, the folded style block.

By invoking sh -c you can pass arguments to your container as commands, but if you want to elegantly separate them with newlines, you'd want to use the folded style block, so that YAML will know to convert newlines to whitespaces, effectively concatenating the commands.

A full working example:

apiVersion: v1
kind: Pod
metadata:
  name: myapp
  labels:
    app: myapp
spec:
  containers:
  - name: busy
    image: busybox:1.28
    command: ["/bin/sh", "-c"]
    args:
    - >
      command_1 &&
      command_2 &&
      ... 
      command_n

Upgrading Node.js to latest version

Re-install the latest version of nodejs by downloading the latest .msi version from nodejs website here, https://nodejs.org/en/download/

It worked for me in my windows machine.

Android getActivity() is undefined

You want getActivity() inside your class. It's better to use

yourclassname.this.getActivity()

Try this. It's helpful for you.

How do I make a branch point at a specific commit?

If you are currently not on branch master, that's super easy:

git branch -f master 1258f0d0aae

This does exactly what you want: It points master at the given commit, and does nothing else.

If you are currently on master, you need to get into detached head state first. I'd recommend the following two command sequence:

git checkout 1258f0d0aae    #detach from master
git branch -f master HEAD   #exactly as above

#optionally reattach to master
git checkout master

Be aware, though, that any explicit manipulation of where a branch points has the potential to leave behind commits that are no longer reachable by any branches, and thus become object to garbage collection. So, think before you type git branch -f!


This method is better than the git reset --hard approach, as it does not destroy anything in the index or working directory.

jQuery Mobile: document ready vs. page events

While you use .on(), it's basically a live query that you are using.

On the other hand, .ready (as in your case) is a static query. While using it, you can dynamically update data and do not have to wait for the page to load. You can simply pass on the values into your database (if required) when a particular value is entered.

The use of live queries is common in forms where we enter data (account or posts or even comments).

'sudo gem install' or 'gem install' and gem locations

sudo gem install --no-user-install <gem-name>

will install your gem globally, i.e. it will be available to all user's contexts.

why numpy.ndarray is object is not callable in my simple for python loop

Sometimes, when a function name and a variable name to which the return of the function is stored are same, the error is shown. Just happened to me.

jQuery creating objects

You can always make it a function

function writeObject(color){
    $('body').append('<div style="color:'+color+';">Hello!</div>')
}

writeObject('blue') ? enter image description here

POST request via RestTemplate in JSON

If you dont want to process response

private RestTemplate restTemplate = new RestTemplate();
restTemplate.postForObject(serviceURL, request, Void.class);

If you need response to process

String result = restTemplate.postForObject(url, entity, String.class);

How to create multidimensional array

function Array2D(x, y)
{
    var array2D = new Array(x);

    for(var i = 0; i < array2D.length; i++)
    {
        array2D[i] = new Array(y);
    }

    return array2D;
}

var myNewArray = Array2D(4, 9);

myNewArray[3][5] = "booger";

How to initialise a string from NSData in Swift

import Foundation
var string = NSString(data: NSData?, encoding: UInt)

Calculate the mean by group

There are many ways to do this in R. Specifically, by, aggregate, split, and plyr, cast, tapply, data.table, dplyr, and so forth.

Broadly speaking, these problems are of the form split-apply-combine. Hadley Wickham has written a beautiful article that will give you deeper insight into the whole category of problems, and it is well worth reading. His plyr package implements the strategy for general data structures, and dplyr is a newer implementation performance tuned for data frames. They allow for solving problems of the same form but of even greater complexity than this one. They are well worth learning as a general tool for solving data manipulation problems.

Performance is an issue on very large datasets, and for that it is hard to beat solutions based on data.table. If you only deal with medium-sized datasets or smaller, however, taking the time to learn data.table is likely not worth the effort. dplyr can also be fast, so it is a good choice if you want to speed things up, but don't quite need the scalability of data.table.

Many of the other solutions below do not require any additional packages. Some of them are even fairly fast on medium-large datasets. Their primary disadvantage is either one of metaphor or of flexibility. By metaphor I mean that it is a tool designed for something else being coerced to solve this particular type of problem in a 'clever' way. By flexibility I mean they lack the ability to solve as wide a range of similar problems or to easily produce tidy output.


Examples

base functions

tapply:

tapply(df$speed, df$dive, mean)
#     dive1     dive2 
# 0.5419921 0.5103974

aggregate:

aggregate takes in data.frames, outputs data.frames, and uses a formula interface.

aggregate( speed ~ dive, df, mean )
#    dive     speed
# 1 dive1 0.5790946
# 2 dive2 0.4864489

by:

In its most user-friendly form, it takes in vectors and applies a function to them. However, its output is not in a very manipulable form.:

res.by <- by(df$speed, df$dive, mean)
res.by
# df$dive: dive1
# [1] 0.5790946
# ---------------------------------------
# df$dive: dive2
# [1] 0.4864489

To get around this, for simple uses of by the as.data.frame method in the taRifx library works:

library(taRifx)
as.data.frame(res.by)
#    IDX1     value
# 1 dive1 0.6736807
# 2 dive2 0.4051447

split:

As the name suggests, it performs only the "split" part of the split-apply-combine strategy. To make the rest work, I'll write a small function that uses sapply for apply-combine. sapply automatically simplifies the result as much as possible. In our case, that means a vector rather than a data.frame, since we've got only 1 dimension of results.

splitmean <- function(df) {
  s <- split( df, df$dive)
  sapply( s, function(x) mean(x$speed) )
}
splitmean(df)
#     dive1     dive2 
# 0.5790946 0.4864489 

External packages

data.table:

library(data.table)
setDT(df)[ , .(mean_speed = mean(speed)), by = dive]
#    dive mean_speed
# 1: dive1  0.5419921
# 2: dive2  0.5103974

dplyr:

library(dplyr)
group_by(df, dive) %>% summarize(m = mean(speed))

plyr (the pre-cursor of dplyr)

Here's what the official page has to say about plyr:

It’s already possible to do this with base R functions (like split and the apply family of functions), but plyr makes it all a bit easier with:

  • totally consistent names, arguments and outputs
  • convenient parallelisation through the foreach package
  • input from and output to data.frames, matrices and lists
  • progress bars to keep track of long running operations
  • built-in error recovery, and informative error messages
  • labels that are maintained across all transformations

In other words, if you learn one tool for split-apply-combine manipulation it should be plyr.

library(plyr)
res.plyr <- ddply( df, .(dive), function(x) mean(x$speed) )
res.plyr
#    dive        V1
# 1 dive1 0.5790946
# 2 dive2 0.4864489

reshape2:

The reshape2 library is not designed with split-apply-combine as its primary focus. Instead, it uses a two-part melt/cast strategy to perform a wide variety of data reshaping tasks. However, since it allows an aggregation function it can be used for this problem. It would not be my first choice for split-apply-combine operations, but its reshaping capabilities are powerful and thus you should learn this package as well.

library(reshape2)
dcast( melt(df), variable ~ dive, mean)
# Using dive as id variables
#   variable     dive1     dive2
# 1    speed 0.5790946 0.4864489

Benchmarks

10 rows, 2 groups

library(microbenchmark)
m1 <- microbenchmark(
  by( df$speed, df$dive, mean),
  aggregate( speed ~ dive, df, mean ),
  splitmean(df),
  ddply( df, .(dive), function(x) mean(x$speed) ),
  dcast( melt(df), variable ~ dive, mean),
  dt[, mean(speed), by = dive],
  summarize( group_by(df, dive), m = mean(speed) ),
  summarize( group_by(dt, dive), m = mean(speed) )
)

> print(m1, signif = 3)
Unit: microseconds
                                           expr  min   lq   mean median   uq  max neval      cld
                    by(df$speed, df$dive, mean)  302  325  343.9    342  362  396   100  b      
              aggregate(speed ~ dive, df, mean)  904  966 1012.1   1020 1060 1130   100     e   
                                  splitmean(df)  191  206  249.9    220  232 1670   100 a       
  ddply(df, .(dive), function(x) mean(x$speed)) 1220 1310 1358.1   1340 1380 2740   100      f  
         dcast(melt(df), variable ~ dive, mean) 2150 2330 2440.7   2430 2490 4010   100        h
                   dt[, mean(speed), by = dive]  599  629  667.1    659  704  771   100   c     
 summarize(group_by(df, dive), m = mean(speed))  663  710  774.6    744  782 2140   100    d    
 summarize(group_by(dt, dive), m = mean(speed)) 1860 1960 2051.0   2020 2090 3430   100       g 

autoplot(m1)

benchmark 10 rows

As usual, data.table has a little more overhead so comes in about average for small datasets. These are microseconds, though, so the differences are trivial. Any of the approaches works fine here, and you should choose based on:

  • What you're already familiar with or want to be familiar with (plyr is always worth learning for its flexibility; data.table is worth learning if you plan to analyze huge datasets; by and aggregate and split are all base R functions and thus universally available)
  • What output it returns (numeric, data.frame, or data.table -- the latter of which inherits from data.frame)

10 million rows, 10 groups

But what if we have a big dataset? Let's try 10^7 rows split over ten groups.

df <- data.frame(dive=factor(sample(letters[1:10],10^7,replace=TRUE)),speed=runif(10^7))
dt <- data.table(df)
setkey(dt,dive)

m2 <- microbenchmark(
  by( df$speed, df$dive, mean),
  aggregate( speed ~ dive, df, mean ),
  splitmean(df),
  ddply( df, .(dive), function(x) mean(x$speed) ),
  dcast( melt(df), variable ~ dive, mean),
  dt[,mean(speed),by=dive],
  times=2
)

> print(m2, signif = 3)
Unit: milliseconds
                                           expr   min    lq    mean median    uq   max neval      cld
                    by(df$speed, df$dive, mean)   720   770   799.1    791   816   958   100    d    
              aggregate(speed ~ dive, df, mean) 10900 11000 11027.0  11000 11100 11300   100        h
                                  splitmean(df)   974  1040  1074.1   1060  1100  1280   100     e   
  ddply(df, .(dive), function(x) mean(x$speed))  1050  1080  1110.4   1100  1130  1260   100      f  
         dcast(melt(df), variable ~ dive, mean)  2360  2450  2492.8   2490  2520  2620   100       g 
                   dt[, mean(speed), by = dive]   119   120   126.2    120   122   212   100 a       
 summarize(group_by(df, dive), m = mean(speed))   517   521   531.0    522   532   620   100   c     
 summarize(group_by(dt, dive), m = mean(speed))   154   155   174.0    156   189   321   100  b      

autoplot(m2)

benchmark 1e7 rows, 10 groups

Then data.table or dplyr using operating on data.tables is clearly the way to go. Certain approaches (aggregate and dcast) are beginning to look very slow.

10 million rows, 1,000 groups

If you have more groups, the difference becomes more pronounced. With 1,000 groups and the same 10^7 rows:

df <- data.frame(dive=factor(sample(seq(1000),10^7,replace=TRUE)),speed=runif(10^7))
dt <- data.table(df)
setkey(dt,dive)

# then run the same microbenchmark as above
print(m3, signif = 3)
Unit: milliseconds
                                           expr   min    lq    mean median    uq   max neval    cld
                    by(df$speed, df$dive, mean)   776   791   816.2    810   828   925   100  b    
              aggregate(speed ~ dive, df, mean) 11200 11400 11460.2  11400 11500 12000   100      f
                                  splitmean(df)  5940  6450  7562.4   7470  8370 11200   100     e 
  ddply(df, .(dive), function(x) mean(x$speed))  1220  1250  1279.1   1280  1300  1440   100   c   
         dcast(melt(df), variable ~ dive, mean)  2110  2190  2267.8   2250  2290  2750   100    d  
                   dt[, mean(speed), by = dive]   110   111   113.5    111   113   143   100 a     
 summarize(group_by(df, dive), m = mean(speed))   625   630   637.1    633   644   701   100  b    
 summarize(group_by(dt, dive), m = mean(speed))   129   130   137.3    131   142   213   100 a     

autoplot(m3)

enter image description here

So data.table continues scaling well, and dplyr operating on a data.table also works well, with dplyr on data.frame close to an order of magnitude slower. The split/sapply strategy seems to scale poorly in the number of groups (meaning the split() is likely slow and the sapply is fast). by continues to be relatively efficient--at 5 seconds, it's definitely noticeable to the user but for a dataset this large still not unreasonable. Still, if you're routinely working with datasets of this size, data.table is clearly the way to go - 100% data.table for the best performance or dplyr with dplyr using data.table as a viable alternative.

JavaFX How to set scene background image

In addition to @Elltz answer, we can use both fill and image for background:

someNode.setBackground(
            new Background(
                    Collections.singletonList(new BackgroundFill(
                            Color.WHITE, 
                            new CornerRadii(500), 
                            new Insets(10))),
                    Collections.singletonList(new BackgroundImage(
                            new Image("image/logo.png", 100, 100, false, true),
                            BackgroundRepeat.NO_REPEAT,
                            BackgroundRepeat.NO_REPEAT,
                            BackgroundPosition.CENTER,
                            BackgroundSize.DEFAULT))));

Use

setBackground(
                new Background(
                        Collections.singletonList(new BackgroundFill(
                                Color.WHITE,
                                new CornerRadii(0),
                                new Insets(0))),
                        Collections.singletonList(new BackgroundImage(
                                new Image("file:clouds.jpg", 100, 100, false, true),
                                BackgroundRepeat.NO_REPEAT,
                                BackgroundRepeat.NO_REPEAT,
                                BackgroundPosition.DEFAULT,
                                new BackgroundSize(1.0, 1.0, true, true, false, false)
                        ))));

(different last argument) to make the image full-window size.

How to join multiple lines of file names into one with custom delimiter?

EDIT: Simply "ls -m" If you want your delimiter to be a comma

Ah, the power and simplicity !

ls -1 | tr '\n' ','

Change the comma "," to whatever you want. Note that this includes a "trailing comma"

ORA-01008: not all variables bound. They are bound

I found how to run the query without error, but I hesitate to call it a "solution" without really understanding the underlying cause.

This more closely resembles the beginning of my actual query:

-- Comment
-- More comment
SELECT rf.flowrow, rf.stage, rf.process,
rf.instr instnum, rf.procedure_id, rtd_history.runtime, rtd_history.waittime
FROM
(
    -- Comment at beginning of subquery
    -- These two comment lines are the problem
    SELECT sub2.flowrow, sub2.stage, sub2.process, sub2.instr, sub2.pid
    FROM ( ...

The second set of comments above, at the beginning of the subquery, were the problem. When removed, the query executes. Other comments are fine. This is not a matter of some rogue or missing newline causing the following line to be commented, because the following line is a SELECT. A missing select would yield a different error than "not all variables bound."

I asked around and found one co-worker who has run into this -- comments causing query failures -- several times. Does anyone know how this can be the cause? It is my understanding that the very first thing a DBMS would do with comments is see if they contain hints, and if not, remove them during parsing. How can an ordinary comment containing no unusual characters (just letters and a period) cause an error? Bizarre.

Can not change UILabel text color

// This is wrong 
categoryTitle.textColor = [UIColor colorWithRed:188 green:149 blue:88 alpha:1.0];

// This should be  
categoryTitle.textColor = [UIColor colorWithRed:188/255 green:149/255 blue:88/255 alpha:1.0];

// In the documentation, the limit of the parameters are mentioned.

colorWithRed:green:blue:alpha: documentation link

How do I get first name and last name as whole name in a MYSQL query?

You can use a query to get the same:

SELECT CONCAT(FirstName , ' ' , MiddleName , ' ' , Lastname) AS Name FROM TableName;

Note: This query return if all columns have some value if anyone is null or empty then it will return null for all, means Name will return "NULL"

To avoid above we can use the IsNull keyword to get the same.

SELECT Concat(Ifnull(FirstName,' ') ,' ', Ifnull(MiddleName,' '),' ', Ifnull(Lastname,' ')) FROM TableName;

If anyone containing null value the ' ' (space) will add with next value.

run program in Python shell

If you're wanting to run the script and end at a prompt (so you can inspect variables, etc), then use:

python -i test.py

That will run the script and then drop you into a Python interpreter.

How to create a popup windows in javafx

You can either create a new Stage, add your controls into it or if you require the POPUP as Dialog box, then you may consider using DialogsFX or ControlsFX(Requires JavaFX8)

For creating a new Stage, you can use the following snippet

@Override
public void start(final Stage primaryStage) {
    Button btn = new Button();
    btn.setText("Open Dialog");
    btn.setOnAction(
        new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                final Stage dialog = new Stage();
                dialog.initModality(Modality.APPLICATION_MODAL);
                dialog.initOwner(primaryStage);
                VBox dialogVbox = new VBox(20);
                dialogVbox.getChildren().add(new Text("This is a Dialog"));
                Scene dialogScene = new Scene(dialogVbox, 300, 200);
                dialog.setScene(dialogScene);
                dialog.show();
            }
         });
    }

If you don't want it to be modal (block other windows), use:

dialog.initModality(Modality.NONE);

Convert list or numpy array of single element to float in python

Just access the first item of the list/array, using the index access and the index 0:

>>> list_ = [4]
>>> list_[0]
4
>>> array_ = np.array([4])
>>> array_[0]
4

This will be an int since that was what you inserted in the first place. If you need it to be a float for some reason, you can call float() on it then:

>>> float(list_[0])
4.0

Meaning of Open hashing and Closed hashing

The name open addressing refers to the fact that the location ("address") of the element is not determined by its hash value. (This method is also called closed hashing).

In separate chaining, each bucket is independent, and has some sort of ADT (list, binary search trees, etc) of entries with the same index. In a good hash table, each bucket has zero or one entries, because we need operations of order O(1) for insert, search, etc.

This is a example of separate chaining using C++ with a simple hash function using mod operator (clearly, a bad hash function)

JavaScript Loading Screen while page loads

At the beginning of your loading script, just make your

visible through css [display:block;] and make the rest of the page invisible through css[display:none;].

Once the loading is done, just make the loading invisible and the page visible again with the same technique. You can use the document.getElementById() to select the divs you want to change the display.

Edit: Here's what it would sort of look like. When the body finishes loading, it will call the javascript function that will change the display values of the different elements. By default, your style would be to have the page not visible the loading visible.

<head>
    <style>
        #page{
            display: none;
        }
        #loading{
            display: block;
        }
    </style>
    <script>
        function myFunction()
        {
            document.getElementById("page").style.display = "block";
            document.getElementById("loading").style.display = "none";
        }
    </script>
</head>

<body onload="myFunction()">
    <div id="page">

    </div>
    <div id="loading">

    </div>
</body>

What is lexical scope?

Scope defines the area, where functions, variables and such are available. The availability of a variable for example is defined within its the context, let's say the function, file, or object, they are defined in. We usually call these local variables.

The lexical part means that you can derive the scope from reading the source code.

Lexical scope is also known as static scope.

Dynamic scope defines global variables that can be called or referenced from anywhere after being defined. Sometimes they are called global variables, even though global variables in most programmin languages are of lexical scope. This means, it can be derived from reading the code that the variable is available in this context. Maybe one has to follow a uses or includes clause to find the instatiation or definition, but the code/compiler knows about the variable in this place.

In dynamic scoping, by contrast, you search in the local function first, then you search in the function that called the local function, then you search in the function that called that function, and so on, up the call stack. "Dynamic" refers to change, in that the call stack can be different every time a given function is called, and so the function might hit different variables depending on where it is called from. (see here)

To see an interesting example for dynamic scope see here.

For further details see here and here.

Some examples in Delphi/Object Pascal

Delphi has lexical scope.

unit Main;
uses aUnit;  // makes available all variables in interface section of aUnit

interface

  var aGlobal: string; // global in the scope of all units that use Main;
  type 
    TmyClass = class
      strict private aPrivateVar: Integer; // only known by objects of this class type
                                    // lexical: within class definition, 
                                    // reserved word private   
      public aPublicVar: double;    // known to everyboday that has access to a 
                                    // object of this class type
    end;

implementation

  var aLocalGlobal: string; // known to all functions following 
                            // the definition in this unit    

end.

The closest Delphi gets to dynamic scope is the RegisterClass()/GetClass() function pair. For its use see here.

Let's say that the time RegisterClass([TmyClass]) is called to register a certain class cannot be predicted by reading the code (it gets called in a button click method called by the user), code calling GetClass('TmyClass') will get a result or not. The call to RegisterClass() does not have to be in the lexical scope of the unit using GetClass();

Another possibility for dynamic scope are anonymous methods (closures) in Delphi 2009, as they know the variables of their calling function. It does not follow the calling path from there recursively and therefore is not fully dynamic.

angular ng-repeat in reverse

Sorry for bringing this up after a year, but there is an new, easier solution, which works for Angular v1.3.0-rc.5 and later.

It is mentioned in the docs: "If no property is provided, (e.g. '+') then the array element itself is used to compare where sorting". So, the solution will be:

ng-repeat="friend in friends | orderBy:'-'" or

ng-repeat="friend in friends | orderBy:'+':true"

This solution seems to be better because it does not modify an array and does not require additional computational resources (at least in our code). I've read all existing answers and still prefer this one to them.

Select Pandas rows based on list index

you can also use iloc:

df.iloc[[1,3],:]

This will not work if the indexes in your dataframe do not correspond to the order of the rows due to prior computations. In that case use:

df.index.isin([1,3])

... as suggested in other responses.

How to check if a python module exists without importing it

You could just write a little script that would try to import all the modules and tell you which ones are failing and which ones are working:

import pip


if __name__ == '__main__':
    for package in pip.get_installed_distributions():
        pack_string = str(package).split(" ")[0]
        try:
            if __import__(pack_string.lower()):
                print(pack_string + " loaded successfully")
        except Exception as e:
            print(pack_string + " failed with error code: {}".format(e))

Output:

zope.interface loaded successfully
zope.deprecation loaded successfully
yarg loaded successfully
xlrd loaded successfully
WMI loaded successfully
Werkzeug loaded successfully
WebOb loaded successfully
virtualenv loaded successfully
...

Word of warning this will try to import everything so you'll see things like PyYAML failed with error code: No module named pyyaml because the actual import name is just yaml. So as long as you know your imports this should do the trick for you.

How do I resolve ClassNotFoundException?

I was trying to run .jar from C# code using Process class. The java code ran successfully from eclipse but it doesn't from C# visual studio and even clicking directly on the jar file, it always stopped with ClassNotFoundException: exception. Solution for my, was export the java program as "Runnable JAR file" instead of "JAR File". Hope it can help someone.

Eclipse CDT project built but "Launch Failed. Binary Not Found"

I've got the same problem on Eclipse 3.8.1. For me it worked to set the artifact type to executable:

Right click on the project -> C/C++ Build -> Settings -> Build Artifact -> Artifact Type: Executable

Finally rebuilding the project produced the Binaries entry in the Project Explorer.

How to change default text color using custom theme?

In your Manifest you need to reference the name of the style that has the text color item inside it. Right now you are just referencing an empty style. So in your theme.xml do only this style:

<style name="Theme" parent="@android:style/TextAppearance">
    <item name="android:textColor">#ffffffff</item>
</style>

And keep you reference to in the Manifest the same (android:theme="@style/Theme")

EDIT:

theme.xml:

<style name="MyTheme" parent="@android:style/TextAppearance">
    <item name="android:textColor">#ffffffff</item>
    <item name="android:textSize">12dp</item>
</style>

Manifest:

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/MyTheme">

Notice I combine the text color and size into the same style. Also, I changed the name of the theme to MyTheme and am now referencing that in the Manifest. And I changed to @android:style/TextAppearance for the parent value.

Get the cartesian product of a series of lists?

Although there are many answers already, I would like to share some of my thoughts:

Iterative approach

def cartesian_iterative(pools):
  result = [[]]
  for pool in pools:
    result = [x+[y] for x in result for y in pool]
  return result

Recursive Approach

def cartesian_recursive(pools):
  if len(pools) > 2:
    pools[0] = product(pools[0], pools[1])
    del pools[1]
    return cartesian_recursive(pools)
  else:
    pools[0] = product(pools[0], pools[1])
    del pools[1]
    return pools
def product(x, y):
  return [xx + [yy] if isinstance(xx, list) else [xx] + [yy] for xx in x for yy in y]

Lambda Approach

def cartesian_reduct(pools):
  return reduce(lambda x,y: product(x,y) , pools)

Scroll to bottom of div with Vue.js

I tried the accepted solution and it didn't work for me. I use the browser debugger and found out the actual height that should be used is the clientHeight BUT you have to put this into the updated() hook for the whole solution to work.

data(){
return {
  conversation: [
    {
    }
  ]
 },
mounted(){
 EventBus.$on('msg-ctr--push-msg-in-conversation', textMsg => {
  this.conversation.push(textMsg)
  // Didn't work doing scroll here
 })
},
updated(){              <=== PUT IT HERE !!
  var elem = this.$el
  elem.scrollTop = elem.clientHeight;
},

Better way to cast object to int

The cast (int) myobject should just work.

If that gives you an invalid cast exception then it is probably because the variant type isn't VT_I4. My bet is that a variant with VT_I4 is converted into a boxed int, VT_I2 into a boxed short, etc.

When doing a cast on a boxed value type it is only valid to cast it to the type boxed. Foe example, if the returned variant is actually a VT_I2 then (int) (short) myObject should work.

Easiest way to find out is to inspect the returned object and take a look at its type in the debugger. Also make sure that in the interop assembly you have the return value marked with MarshalAs(UnmanagedType.Struct)

Android TextView padding between lines

This supplemental answer shows the effect of changing the line spacing.

enter image description here

You can set the multiplier and/or extra spacing with

textView.setLineSpacing(float add, float mult)

Or you can get the values with

int lineHeight = textView.getLineHeight();
float add = tvSampleText.getLineSpacingExtra();          // API 16+
float mult = tvSampleText.getLineSpacingMultiplier();    // API 16+

where the formula is

lineHeight = fontMetricsLineHeight * mult + add

The default multiplier is 1 and the default extra spacing is 0.

Meaning of *& and **& in C++

That is taking the parameter by reference. So in the first case you are taking a pointer parameter by reference so whatever modification you do to the value of the pointer is reflected outside the function. Second is the simlilar to first one with the only difference being that it is a double pointer. See this example:

void pass_by_value(int* p)
{
    //Allocate memory for int and store the address in p
    p = new int;
}

void pass_by_reference(int*& p)
{
    p = new int;
}

int main()
{
    int* p1 = NULL;
    int* p2 = NULL;

    pass_by_value(p1); //p1 will still be NULL after this call
    pass_by_reference(p2); //p2 's value is changed to point to the newly allocate memory

    return 0;
}

Why did my Git repo enter a detached HEAD state?

A simple accidental way is to do a git checkout head as a typo of HEAD.

Try this:

git init
touch Readme.md
git add Readme.md
git commit
git checkout head

which gives

Note: checking out 'head'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 9354043... Readme

How to detect a route change in Angular?

Location works...

import {Component, OnInit} from '@angular/core';
import {Location} from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {

    constructor(private location: Location) {
        this.location.onUrlChange(x => this.urlChange(x));
    }

    ngOnInit(): void {}

    urlChange(x) {
        console.log(x);
    }
}

PHP display image BLOB from MySQL

Since I have to store various types of content in my blob field/column, I am suppose to update my code like this:

echo "data: $mime" $result['$data']";

where: mime can be an image of any kind, text, word document, text document, PDF document, etc... content datatype is blob in database.

List vs tuple, when to use each?

There's a strong culture of tuples being for heterogeneous collections, similar to what you'd use structs for in C, and lists being for homogeneous collections, similar to what you'd use arrays for. But I've never quite squared this with the mutability issue mentioned in the other answers. Mutability has teeth to it (you actually can't change a tuple), while homogeneity is not enforced, and so seems to be a much less interesting distinction.

Python exit commands - why so many and when should each be used?

Different Means of Exiting

os._exit():

  • Exit the process without calling the cleanup handlers.

exit(0):

  • a clean exit without any errors / problems.

exit(1):

  • There was some issue / error / problem and that is why the program is exiting.

sys.exit():

  • When the system and python shuts down; it means less memory is being used after the program is run.

quit():

  • Closes the python file.

Summary

Basically they all do the same thing, however, it also depends on what you are doing it for.

I don't think you left anything out and I would recommend getting used to quit() or exit().

You would use sys.exit() and os._exit() mainly if you are using big files or are using python to control terminal.

Otherwise mainly use exit() or quit().

Removing object from array in Swift 3

The correct and working one-line solution for deleting a unique object (named "objectToRemove") from an array of these objects (named "array") in Swift 3 is:

if let index = array.enumerated().filter( { $0.element === objectToRemove }).map({ $0.offset }).first {
   array.remove(at: index)
}

Create a CSV File for a user in PHP

<?
    // Connect to database
    $result = mysql_query("select id
    from tablename
    where shid=3");
    list($DBshid) = mysql_fetch_row($result);

    /***********************************
    Write date to CSV file
    ***********************************/

    $_file = 'show.csv';
    $_fp = @fopen( $_file, 'wb' );

    $result = mysql_query("select name,compname,job_title,email_add,phone,url from UserTables where id=3");

    while (list( $Username, $Useremail_add, $Userphone, $Userurl) = mysql_fetch_row($result))
    {
        $_csv_data = $Username.','.$Useremail_add.','.$Userphone.','.$Userurl . "\n";
        @fwrite( $_fp, $_csv_data);
    }
    @fclose( $_fp );
?>

Changing background colour of tr element on mouseover

its easy . Just add !important at the end of your css line :

tr:hover {    background: #000 !important; }

How to style a JSON block in Github Wiki?

You can use some online websites to beautify JSON, such as: JSON Formatter, and then paste the beautified result to WIKI

CSS force image resize and keep aspect ratio

https://jsfiddle.net/sot2qgj6/3/

Here is the answer if you want to put image with fixed percentage of width, but not fixed pixel of width.

And this will be useful when dealing with different size of screen.

The tricks are

  1. Using padding-top to set the height from width.
  2. Using position: absolute to put image in the padding space.
  3. Using max-height and max-width to make sure the image will not over the parent element.
  4. using display:block and margin: auto to center the image.

I've also comment most of the tricks inside the fiddle.


I also find some other ways to make this happen. There will be no real image in html, so I personly perfer the top answer when I need "img" element in html.

simple css by using background http://jsfiddle.net/4660s79h/2/

background-image with word on top http://jsfiddle.net/4660s79h/1/

the concept to use position absolute is from here http://www.w3schools.com/howto/howto_css_aspect_ratio.asp

Java constructor/method with optional parameters?

You can use varargs for optional parameters:

public class Booyah {
    public static void main(String[] args) {
        woohoo(1);
        woohoo(2, 3);
    }
    static void woohoo(int required, Integer... optional) {
        Integer lala;
        if (optional.length == 1) {
            lala = optional[0];
        } else {
            lala = 2;
        }
        System.out.println(required + lala);
    }
}

Also it's important to note the use of Integer over int. Integer is a wrapper around the primitive int, which allows one to make comparisons with null as necessary.

How do I clear my Jenkins/Hudson build history?

If using the Script Console method then try using the following instead to take into account if jobs are being grouped into folder containers.

def jobName = "Your Job Name"
def job = Jenkins.instance.getItemByFullName(jobName)

or

def jobName = "My Folder/Your Job Name
def job = Jenkins.instance.getItemByFullName(jobName)

getElementsByClassName not working

If you want to do it by ClassName you could do:

<script type="text/javascript">
function hideTd(className){
    var elements;

    if (document.getElementsByClassName)
    {
        elements = document.getElementsByClassName(className);
    }
    else
    {
        var elArray = [];
        var tmp = document.getElementsByTagName(elements);  
        var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        elements = elArray;
    }

    for(var i = 0, i < elements.length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

SQLiteOpenHelper onCreate() and onUpgrade() callbacks are invoked when the database is actually opened, for example by a call to getWritableDatabase(). The database is not opened when the database helper object itself is created.

SQLiteOpenHelper versions the database files. The version number is the int argument passed to the constructor. In the database file, the version number is stored in PRAGMA user_version.

onCreate() is only run when the database file did not exist and was just created. If onCreate() returns successfully (doesn't throw an exception), the database is assumed to be created with the requested version number. As an implication, you should not catch SQLExceptions in onCreate() yourself.

onUpgrade() is only called when the database file exists but the stored version number is lower than requested in the constructor. The onUpgrade() should update the table schema to the requested version.

When changing the table schema in code (onCreate()), you should make sure the database is updated. Two main approaches:

  1. Delete the old database file so that onCreate() is run again. This is often preferred at development time where you have control over the installed versions and data loss is not an issue. Some ways to delete the database file:

    • Uninstall the application. Use the application manager or adb uninstall your.package.name from the shell.

    • Clear application data. Use the application manager.

  2. Increment the database version so that onUpgrade() is invoked. This is slightly more complicated as more code is needed.

    • For development time schema upgrades where data loss is not an issue, you can just use execSQL("DROP TABLE IF EXISTS <tablename>") in to remove your existing tables and call onCreate() to recreate the database.

    • For released versions, you should implement data migration in onUpgrade() so your users don't lose their data.

How to see JavaDoc in IntelliJ IDEA?

Use View | Quick Documentation or the corresponding keyboard shortcut (by default: Ctrl+Q on Windows/Linux and Ctrl+J on macOS or F1 in the recent IDE versions). See the documentation for more information.

It's also possible to enable automatic JavaDoc popup on explicit (invoked by a shortcut) code completion in Settings | Editor | General | Code completion (Autopopup documentation):

autopopup documentation

Yet another way to see the quick doc is on mouse move:

on mouse move

<DIV> inside link (<a href="">) tag

No, the link assigned to the containing <a> will be assigned to every elements inside it.

And, this is not the proper way. You can make a <a> behave like a <div>.

An Example [Demo]

CSS

a.divlink { 
     display:block;
     width:500px;
     height:500px; 
     float:left;
}

HTML

<div>
    <a class="divlink" href="yourlink.html">
         The text or elements inside the elements
    </a>
    <a class="divlink" href="yourlink2.html">
         Another text or element
    </a>
</div>

Match groups in Python

this is not a regex solution.

alist={"I love ":""He loves"","Je t'aime ":"Il aime","Ich liebe ":"Er liebt"}
for k in alist.keys():
    if k in statement:
       print alist[k],statement.split(k)[1:]

WCF error: The caller was not authenticated by the service

set anonymous access in your virtual directory

write following credentials to your service

ADTService.ServiceClient adtService = new ADTService.ServiceClient();
adtService.ClientCredentials.Windows.ClientCredential.UserName="windowsuseraccountname";
adtService.ClientCredentials.Windows.ClientCredential.Password="windowsuseraccountpassword";
adtService.ClientCredentials.Windows.ClientCredential.Domain="windowspcname";

after that you call your webservice methods.

Access parent URL from iframe

I just discovered a workaround for this problem that is so simple, and yet I haven't found any discussions anywhere that mention it. It does require control of the parent frame.

In your iFrame, say you want this iframe: src="http://www.example.com/mypage.php"

Well, instead of HTML to specify the iframe, use a javascript to build the HTML for your iframe, get the parent url through javascript "at build time", and send it as a url GET parameter in the querystring of your src target, like so:

<script type="text/javascript">
  url = parent.document.URL;
  document.write('<iframe src="http://example.com/mydata/page.php?url=' + url + '"></iframe>');
</script>

Then, find yourself a javascript url parsing function that parses the url string to get the url variable you are after, in this case it's "url".

I found a great url string parser here: http://www.netlobo.com/url_query_string_javascript.html

How to add icon inside EditText view in Android ?

Use the android:drawableLeft property on the EditText.

<EditText
    ...     
    android:drawableLeft="@drawable/my_icon" />

ArrayList - How to modify a member of an object?

Try this.This works while traversing the code and modifying the fields at once of all the elements of Arraylist.

public Employee(String name,String email){
this.name=name;
this.email=email;
}

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setEmail(String email) {
this.email = email;
}

public String getEmail() {
return email;
}

for(int i=0;i++){
List.get(i).setName("Anonymous");
List.get(i).setEmail("[email protected]");
}

How can I refresh c# dataGridView after update ?

BindingSource is the only way without going for a 3rd party ORM, it may seem long winded at first but the benefits of one update method on the BindingSource are so helpful.

If your source is say for example a list of user strings

List<string> users = GetUsers();
BindingSource source = new BindingSource();
source.DataSource = users;
dataGridView1.DataSource = source;

then when your done editing just update your data object whether that be a DataTable or List of user strings like here and ResetBindings on the BindingSource;

users = GetUsers(); //Update your data object
source.ResetBindings(false);

Create a custom View by inflating a layout?

In practice, I have found that you need to be a bit careful, especially if you are using a bit of xml repeatedly. Suppose, for example, that you have a table that you wish to create a table row for each entry in a list. You've set up some xml:

In my_table_row.xml:

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent" android:id="@+id/myTableRow">
    <ImageButton android:src="@android:drawable/ic_menu_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rowButton"/>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="TextView" android:id="@+id/rowText"></TextView>
</TableRow>

Then you want to create it once per row with some code. It assume that you have defined a parent TableLayout myTable to attach the Rows to.

for (int i=0; i<numRows; i++) {
    /*
     * 1. Make the row and attach it to myTable. For some reason this doesn't seem
     * to return the TableRow as you might expect from the xml, so you need to
     * receive the View it returns and then find the TableRow and other items, as
     * per step 2.
     */
    LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v =  inflater.inflate(R.layout.my_table_row, myTable, true);

    // 2. Get all the things that we need to refer to to alter in any way.
    TableRow    tr        = (TableRow)    v.findViewById(R.id.profileTableRow);
    ImageButton rowButton = (ImageButton) v.findViewById(R.id.rowButton);
    TextView    rowText   = (TextView)    v.findViewById(R.id.rowText);

    // 3. Configure them out as you need to
    rowText.setText("Text for this row");
    rowButton.setId(i); // So that when it is clicked we know which one has been clicked!
    rowButton.setOnClickListener(this); // See note below ...           

    /*
     * To ensure that when finding views by id on the next time round this
     * loop (or later) gie lots of spurious, unique, ids.
     */
    rowText.setId(1000+i);
    tr.setId(3000+i);
}

For a clear simple example on handling rowButton.setOnClickListener(this), see Onclicklistener for a programatically created button.

Get folder name from full file path

Simply use Path.GetFileName

Here - Extract folder name from the full path of a folder:

string folderName = Path.GetFileName(@"c:\projects\root\wsdlproj\devlop\beta2\text");//Return "text"

Here is some extra - Extract folder name from the full path of a file:

string folderName = Path.GetFileName(Path.GetDirectoryName(@"c:\projects\root\wsdlproj\devlop\beta2\text\GTA.exe"));//Return "text"

How can I add a background thread to flask?

In addition to using pure threads or the Celery queue (note that flask-celery is no longer required), you could also have a look at flask-apscheduler:

https://github.com/viniciuschiele/flask-apscheduler

A simple example copied from https://github.com/viniciuschiele/flask-apscheduler/blob/master/examples/jobs.py:

from flask import Flask
from flask_apscheduler import APScheduler


class Config(object):
    JOBS = [
        {
            'id': 'job1',
            'func': 'jobs:job1',
            'args': (1, 2),
            'trigger': 'interval',
            'seconds': 10
        }
    ]

    SCHEDULER_API_ENABLED = True


def job1(a, b):
    print(str(a) + ' ' + str(b))

if __name__ == '__main__':
    app = Flask(__name__)
    app.config.from_object(Config())

    scheduler = APScheduler()
    # it is also possible to enable the API directly
    # scheduler.api_enabled = True
    scheduler.init_app(app)
    scheduler.start()

    app.run()

Set font-weight using Bootstrap classes

EDIT 2 (final) : According to the bootstrap 4 documentation, class="font-weight-bold" is what you are looking for.


EDIT : You can use class="font-weight-bold" as shown here (Bootstrap 4 alpha).

I kept the original answer below for clarity purposes.


I am posting this answer because this thread seems to have a lot of visitors, yet it had no proper solution to solve this issue. But there will be soon now a way with Bootstrap 4 :

As this GitHub pull request shows, you will just have to use the text-weight-normal, text-weight-bold and text-weight-italic classes.

This can maybe change until the official stable release. At this date of writing, this pull request is not merged yet in the alpha branch.

I will update this post once Bootstrap v4 has been released.

Find document with array that contains a specific value

There is no $contains operator in mongodb.

You can use the answer from JohnnyHK as that works. The closest analogy to contains that mongo has is $in, using this your query would look like:

PersonModel.find({ favouriteFoods: { "$in" : ["sushi"]} }, ...);

How to check radio button is checked using JQuery?

Try this:

var count =0;

$('input[name="radioGroup"]').each(function(){
  if (this.checked)
    {
      count++;
    }
});

If any of radio button checked than you will get 1

How do I loop through rows with a data reader in C#?

int count = reader.FieldCount;
while(reader.Read()) {
    for(int i = 0 ; i < count ; i++) {
        Console.WriteLine(reader.GetValue(i));
    }
}

Note; if you have multiple grids, then:

do {
    int count = reader.FieldCount;
    while(reader.Read()) {
        for(int i = 0 ; i < count ; i++) {
            Console.WriteLine(reader.GetValue(i));
        }
    }
} while (reader.NextResult())

How to kill a thread instantly in C#?

thread will be killed when it finish it's work, so if you are using loops or something else you should pass variable to the thread to stop the loop after that the thread will be finished.

Nested objects in javascript, best practices

If you know the settings in advance you can define it in a single statement:

var defaultsettings = {
                        ajaxsettings : { "ak1" : "v1", "ak2" : "v2", etc. },
                        uisettings : { "ui1" : "v1", "ui22" : "v2", etc }
                      };

If you don't know the values in advance you can just define the top level object and then add properties:

var defaultsettings = { };
defaultsettings["ajaxsettings"] = {};
defaultsettings["ajaxsettings"]["somekey"] = "some value";

Or half-way between the two, define the top level with nested empty objects as properties and then add properties to those nested objects:

var defaultsettings = {
                        ajaxsettings : {  },
                        uisettings : {  }
                      };

defaultsettings["ajaxsettings"]["somekey"] = "some value";
defaultsettings["uisettings"]["somekey"] = "some value";

You can nest as deep as you like using the above techniques, and anywhere that you have a string literal in the square brackets you can use a variable:

var keyname = "ajaxsettings";
var defaultsettings = {};
defaultsettings[keyname] = {};
defaultsettings[keyname]["some key"] = "some value";

Note that you can not use variables for key names in the { } literal syntax.

How to create custom spinner like border around the spinner with down triangle on the right side?

To change only "background" (add corners, change color, ....) you can put it into FrameLayout with wanted background drawable, else you need to make nine patch background for to not lose spinner arrow. Spinner background is transparent.

Python Turtle, draw text with on screen with larger font

Use the optional font argument to turtle.write(), from the docs:

turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))
 Parameters:

  • arg – object to be written to the TurtleScreen
  • move – True/False
  • align – one of the strings “left”, “center” or right”
  • font – a triple (fontname, fontsize, fonttype)

So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal")) to change the font size to 16 (default is 8).

Adding System.Web.Script reference in class library

You need to add a reference to System.Web.Extensions.dll in project for System.Web.Script.Serialization error.

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

Here are more code examples that will produce the argument null exception:

List<Myobj> myList = null;
//from this point on, any linq statement you perform on myList will throw an argument null exception
myList.ToList();
myList.GroupBy(m => m.Id);
myList.Count();
myList.Where(m => m.Id == 0);
myList.Select(m => m.Id == 0);
//etc...

How to use sbt from behind proxy?

sbt works in a fairly standard way comparing to the way other JVM-based projects are usually configured.

sbt is in fact two "subsystems" - the launcher and the core. It's usually xsbt.boot.Boot that gets executed before the core starts up with the features we all know (and some even like).

It's therefore a matter of how you execute sbt that says how you could set up a proxy for HTTP, HTTPS and FTP network traffic.

The following is the entire list of the available properties that can be set for any Java application, sbt including, that instruct the Java API to route communication through a proxy:

  • http_proxy
  • http_proxy_user
  • http_proxy_pass
  • http.proxyHost
  • http.proxyPort
  • http.proxyUser
  • http.proxyPassword

Replace http above with https and ftp to get the list of the properties for the services.

Some sbt scripts use JAVA_OPTS to set up the proxy settings with -Dhttp.proxyHost and -Dhttp.proxyPort amongst the others (listed above). See Java Networking and Proxies.

Some scripts come with their own way of setting up proxy configuration using the SBT_OPTS property, .sbtopts or (only on Windows) %SBT_HOME%\conf\sbtconfig.txt. You can use them to specifically set sbt to use proxies while the other JVM-based applications are not affected at all.

From the sbt command line tool:

# jvm options and output control
JAVA_OPTS          environment variable, if unset uses "$java_opts"
SBT_OPTS           environment variable, if unset uses "$default_sbt_opts"
.sbtopts           if this file exists in the current directory, it is
                   prepended to the runner args
/etc/sbt/sbtopts   if this file exists, it is prepended to the runner args
-Dkey=val          pass -Dkey=val directly to the java runtime
-J-X               pass option -X directly to the java runtime 
                   (-J is stripped)
-S-X               add -X to sbt's scalacOptions (-S is stripped)

And here comes an excerpt from sbt.bat:

@REM Envioronment:
@REM JAVA_HOME - location of a JDK home dir (mandatory)
@REM SBT_OPTS  - JVM options (optional)
@REM Configuration:
@REM sbtconfig.txt found in the SBT_HOME.

Be careful with sbtconfig.txt that just works on Windows only. When you use cygwin the file is not consulted and you will have to resort to using the other approaches.

I'm using sbt with the following script:

$JAVA_HOME/bin/java $SBT_OPTS -jar /Users/jacek/.ivy2/local/org.scala-sbt/sbt-launch/$SBT_LAUNCHER_VERSION-SNAPSHOT/jars/sbt-launch.jar "$@"

The point of the script is to use the latest version of sbt built from the sources (that's why I'm using /Users/jacek/.ivy2/local/org.scala-sbt/sbt-launch/$SBT_LAUNCHER_VERSION-SNAPSHOT/jars/sbt-launch.jar) with $SBT_OPTS property as a means of passing JVM properties to the JVM sbt uses.

The script above lets me to set proxy on command line on MacOS X as follows:

SBT_OPTS="-Dhttp.proxyHost=proxyhost -Dhttp.proxyPort=9999" sbt

As you can see, there are many approaches to set proxy for sbt that all pretty much boil down to set a proxy for the JVM sbt uses.

Trying to get property of non-object - CodeIgniter

To access the elements in the array, use array notation: $product['prodname']

$product->prodname is object notation, which can only be used to access object attributes and methods.

Laravel whereIn OR whereIn

$query = DB::table('dms_stakeholder_permissions');
$query->select(DB::raw('group_concat(dms_stakeholder_permissions.fid) as fid'),'dms_stakeholder_permissions.rights');
$query->where('dms_stakeholder_permissions.stakeholder_id','4');
$query->orWhere(function($subquery)  use ($stakeholderId){
            $subquery->where('dms_stakeholder_permissions.stakeholder_id',$stakeholderId);
            $subquery->whereIn('dms_stakeholder_permissions.rights',array('1','2','3'));
    });

 $result = $query->get();

return $result;

// OUTPUT @input $stakeholderId = 1

//select group_concat(dms_stakeholder_permissions.fid) as fid, dms_stakeholder_permissionss.rights from dms_stakeholder_permissions where dms_stakeholder_permissions.stakeholder_id = 4 or (dms_stakeholder_permissions.stakeholder_id = 1 and dms_stakeholder_permissions.rights in (1, 2, 3))

Get the index of a certain value in an array in PHP

This code should do the same as your new routine, working with the correct multi-dimensional array..

 $arr = array(
  'string1' => array('a' => '', 'b' => '', 'c' => ''),
  'string2' => array('a' => '', 'b' => '', 'c' => ''),
  'string3' => array('a' => '', 'b' => '', 'c' => '')
 );

 echo 'Index of "string2" = '. array_search('string2', array_keys($arr));

Using floats with sprintf() in embedded C

Look in the documentation for sprintf for your platform. Its usually %f or %e. The only place you will find a definite answer is the documentation... if its undocumented all you can do then is contact the supplier.

What platform is it? Someone might already know where the docs are... :)

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

just use bootstrap class "btn" in the link it will remove underline on hover

React - clearing an input value after form submit

You are having a controlled component where input value is determined by this.state.city. So once you submit you have to clear your state which will clear your input automatically.

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.setState({
      city: ''
    });
}

BeanFactory not initialized or already closed - call 'refresh' before

This exception come due to you are providing listener ContextLoaderListener

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

but you are not providing context-param for your spring configuration file. like applicationContext.xml You must provide below snippet for your configuration

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>applicationContext.xml</param-value>
</context-param>

If You are providing the java based spring configuration , means you are not using xml file for spring configuration at that time you must provide below code:

<!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext
instead of the default XmlWebApplicationContext -->
<context-param>
    <param-name>contextClass</param-name>
    <param-value>
    org.springframework.web.context.support.AnnotationConfigWebApplicationContext
    </param-value>
</context-param>

<!-- Configuration locations must consist of one or more comma- or space-delimited
fully-qualified @Configuration classes. Fully-qualified packages may also
be specified for component-scanning -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>com.nirav.modi.config.SpringAppConfig</param-value>
</context-param>

You should not use <Link> outside a <Router>

I was getting this error because I was importing a reusable component from an npm library and the versions of react-router-dom did not match.

So make sure you use the same version in both places!

Calling Javascript function from server side

You can call the function from code behind like this :

MyForm.aspx.cs

protected void MyButton_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "AnotherFunction();", true);
}

MyForm.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>My Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function Test() {
        alert("hi");
        $("#ButtonRow").show();
    }
    function AnotherFunction()
    {
        alert("This is another function");
    }
</script>
</head>
<body>
<form id="form2" runat="server">
<table>
    <tr><td>
            <asp:RadioButtonList ID="SearchCategory" runat="server" onchange="Test()"  RepeatDirection="Horizontal"  BorderStyle="Solid">
               <asp:ListItem>Merchant</asp:ListItem>
               <asp:ListItem>Store</asp:ListItem>
               <asp:ListItem>Terminal</asp:ListItem>
            </asp:RadioButtonList>
        </td>
    </tr>
    <tr id="ButtonRow"style="display:none">
         <td>
            <asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
        </td>
    </tr>
    </table> 
</form>

How to Load an Assembly to AppDomain with all references recursively?

You need to invoke CreateInstanceAndUnwrap before your proxy object will execute in the foreign application domain.

 class Program
{
    static void Main(string[] args)
    {
        AppDomainSetup domaininfo = new AppDomainSetup();
        domaininfo.ApplicationBase = System.Environment.CurrentDirectory;
        Evidence adevidence = AppDomain.CurrentDomain.Evidence;
        AppDomain domain = AppDomain.CreateDomain("MyDomain", adevidence, domaininfo);

        Type type = typeof(Proxy);
        var value = (Proxy)domain.CreateInstanceAndUnwrap(
            type.Assembly.FullName,
            type.FullName);

        var assembly = value.GetAssembly(args[0]);
        // AppDomain.Unload(domain);
    }
}

public class Proxy : MarshalByRefObject
{
    public Assembly GetAssembly(string assemblyPath)
    {
        try
        {
            return Assembly.LoadFile(assemblyPath);
        }
        catch (Exception)
        {
            return null;
            // throw new InvalidOperationException(ex);
        }
    }
}

Also, note that if you use LoadFrom you'll likely get a FileNotFound exception because the Assembly resolver will attempt to find the assembly you're loading in the GAC or the current application's bin folder. Use LoadFile to load an arbitrary assembly file instead--but note that if you do this you'll need to load any dependencies yourself.

How to get the number of columns from a JDBC ResultSet?

You can get columns number from ResultSetMetaData:

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();

int columnsNumber = rsmd.getColumnCount();

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

You can view this dump from the UNIX console.

The path for the heap dump will be provided as a variable right after where you have placed the mentioned variable.

E.g.:

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${DOMAIN_HOME}/logs/mps"

You can view the dump from the console on the mentioned path.

Create a hidden field in JavaScript

var input = document.createElement("input");

input.setAttribute("type", "hidden");

input.setAttribute("name", "name_you_want");

input.setAttribute("value", "value_you_want");

//append to form element that you want .
document.getElementById("chells").appendChild(input);

Syntax error near unexpected token 'fi'

As well as having then on a new line, you also need a space before and after the [, which is a special symbol in BASH.

#!/bin/bash
echo "start\n"
for f in *.jpg
do
  fname=$(basename "$f")
  echo "fname is $fname\n"
  fname="${filename%.*}"
  echo "fname is $fname\n"
  if [ $((fname %  2)) -eq 1 ]
  then
    echo "removing $fname\n"
    rm "$f"
  fi
done

disable editing default value of text input

How about disabled=disabled:

<input id="price_from" value="price from " disabled="disabled">????????????

Problem is if you don't want user to edit them, why display them in input? You can hide them even if you want to submit a form. And to display information, just use other tag instead.

java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex

check your dependencies versions, you must have compatible versions put attention specially to com.google packages, must have same version like:

compile 'com.google.android.gms:play-services:8.3.0'
compile 'com.google.android.gms:play-services-maps:8.3.0'

Both are 8.3.0, if you have another version compilation will throw that exception.

Why Anaconda does not recognize conda command?

It's not recommended to add conda.exe path directly into the System Environment Variables at stated by anaconda installer :

enter image description here

For Windows Users, Open Conda Prompt Shortcut and change the Target into the Correct Address :

enter image description here

MVC4 HTTP Error 403.14 - Forbidden

<system.webServer>
   <modules runAllManagedModulesForAllRequests="true"/> 
 </system.webServer>

U can use above code

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

Checkout multiple git repos into same Jenkins workspace

Depending upon the relationships of the repositories, another approach is to add the other repository (repositories) as a git submodules to one of the repositories. A git submodule is creates a reference to the other repos. Those submodule repos are not cloned unless the you specify the --recursive flag when cloning the "superproject" (official term).

Here's the command to add a submodule into the current project:

git submodule add <repository URI path to clone>

We are using Jenkins v1.645 and the git SCM will out-of-the-box do a recursive clone for superprojects. Voila you get the superproject files and all the dependent (submodule) repo files in their own respective directories in the same Jenkins job workspace.

Not vouching that this is the correct approach rather it's an approach.

Instantly detect client disconnection from server socket

I've found quite useful, another workaround for that!

If you use asynchronous methods for reading data from the network socket (I mean, use BeginReceive - EndReceive methods), whenever a connection is terminated; one of these situations appear: Either a message is sent with no data (you can see it with Socket.Available - even though BeginReceive is triggered, its value will be zero) or Socket.Connected value becomes false in this call (don't try to use EndReceive then).

I'm posting the function I used, I think you can see what I meant from it better:


private void OnRecieve(IAsyncResult parameter) 
{
    Socket sock = (Socket)parameter.AsyncState;
    if(!sock.Connected || sock.Available == 0)
    {
        // Connection is terminated, either by force or willingly
        return;
    }

    sock.EndReceive(parameter);
    sock.BeginReceive(..., ... , ... , ..., new AsyncCallback(OnRecieve), sock);

    // To handle further commands sent by client.
    // "..." zones might change in your code.
}

Change <br> height using CSS

Use the content property and style that content. Content behavior is then adjusted using pseudo elements. Pseudo elements ::before and ::after both work in Mac Safari 10.0.3.

Here element br content is used as the element anchor for element br::after content. Element br is where br spacing can be styled. br::after is the place where br::after content can be displayed and styled. Looks pretty, but not a 2px <br>.

br { content: ""; display: block; margin: 1rem 0; }
br::after { content: "› "; /* content: " " space ignored */; float: left; margin-right: 0.5rem; }

The br element line-height property is ignored. If negative values are applied to either or both selectors to give vertical 'lift' to br tags in display, then correct vertical spacing occurs, but display incrementally indents display content following each br tag. The indent is exactly equal to the amount that lift varies from actual typographic line-height. If you guess the right lift, there is no indent but a single pile-up line exactly equal to raw glyph height, jammed between previous and following lines.

Further, a trailing br tag will cause the following html display tag to inherit the br:after content styling. Also, pseudo elements cause <br> <br> to be interpreted as a single <br>. While pseudo-class br:active causes each <br> to be interpreted separately. Finally, using br:active ignores pseudo element br:after and all br:active styling. So, all that's required is this:

br:active { }

which is no help for creating a 2px high <br> display. And here the pseudo class :active is ignored!

br:active { content: ""; display: block; margin: 1.25em 0; }
br { content: ""; display: block; margin: 1rem; }
br::after { content: "› "; /* content: " " space ignored */; float: left; margin-right: 0.5rem; }

This is a partial solution only. Pseudo class and pseudo element may provide solution, if tweaked. This may be part of CSS solution. (I only have Safari, try it in other browsers.)

Learn web development: pseudo classes and pseudo elements

Pay attention to global elements - BR at Mozilla.org

How to create full compressed tar file using Python?

In this tar.gz file compress in open view directory In solve use os.path.basename(file_directory)

with tarfile.open("save.tar.gz","w:gz"):
      for file in ["a.txt","b.log","c.png"]:
           tar.add(os.path.basename(file))

its use in tar.gz file compress in directory

Gaussian filter in MATLAB

@Jacob already showed you how to use the Gaussian filter in Matlab, so I won't repeat that.

I would choose filter size to be about 3*sigma in each direction (round to odd integer). Thus, the filter decays to nearly zero at the edges, and you won't get discontinuities in the filtered image.

The choice of sigma depends a lot on what you want to do. Gaussian smoothing is low-pass filtering, which means that it suppresses high-frequency detail (noise, but also edges), while preserving the low-frequency parts of the image (i.e. those that don't vary so much). In other words, the filter blurs everything that is smaller than the filter.

If you're looking to suppress noise in an image in order to enhance the detection of small features, for example, I suggest to choose a sigma that makes the Gaussian just slightly smaller than the feature.

How to force 'cp' to overwrite directory instead of creating another one inside?

The operation you defined is a "merge" and you cannot do that with cp. However, if you are not looking for merging and ok to lose the folder bar then you can simply rm -rf bar to delete the folder and then mv foo bar to rename it. This will not take any time as both operations are done by file pointers, not file contents.

How to find the socket connection state in C?

For BSD sockets I'd check out Beej's guide. When recv returns 0 you know the other side disconnected.

Now you might actually be asking, what is the easiest way to detect the other side disconnecting? One way of doing it is to have a thread always doing a recv. That thread will be able to instantly tell when the client disconnects.

Programmatically select a row in JTable

You can do it calling setRowSelectionInterval :

table.setRowSelectionInterval(0, 0);

to select the first row.

How to debug external class library projects in visual studio?

I was having a similar issue as my breakpoints in project(B) were not being hit. My solution was to rebuild project(B) then debug project(A) as the dlls needed to be updated.

Visual studio should allow you to debug into an external library.

Execute PHP function with onclick

In javascript, make an ajax function,

function myAjax() {
      $.ajax({
           type: "POST",
           url: 'your_url/ajax.php',
           data:{action:'call_this'},
           success:function(html) {
             alert(html);
           }

      });
 }

Then call from html,

<a href="" onclick="myAjax()" class="deletebtn">Delete</a>

And in your ajax.php,

if($_POST['action'] == 'call_this') {
  // call removeday() here
}

How can I strip HTML tags from a string in ASP.NET?

I've posted this on the asp.net forums, and it still seems to be one of the easiest solutions out there. I won't guarantee it's the fastest or most efficient, but it's pretty reliable. In .NET you can use the HTML Web Control objects themselves. All you really need to do is insert your string into a temporary HTML object such as a DIV, then use the built-in 'InnerText' to grab all text that is not contained within tags. See below for a simple C# example:


System.Web.UI.HtmlControls.HtmlGenericControl htmlDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
htmlDiv.InnerHtml = htmlString;
String plainText = htmlDiv.InnerText;

Remove scrollbars from textarea

Hide scroll bar, but while still being able to scroll using CSS

To hide the scrollbar use -webkit- because it is supported by major browsers (Google Chrome, Safari or newer versions of Opera). There are many other options for the other browsers which are listed below:

    -webkit- (Chrome, Safari, newer versions of Opera):
    .element::-webkit-scrollbar { width: 0 !important }
    -moz- (Firefox):
    .element { overflow: -moz-scrollbars-none; }
    -ms- (Internet Explorer +10):
    .element { -ms-overflow-style: none; }

ref: https://www.geeksforgeeks.org/hide-scroll-bar-but-while-still-being-able-to-scroll-using-css/

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

I ran into this error trying to run the profiler, even though my connection had Trust server certificate checked and I added TrustServerCertificate=True in the Advanced Section. I changed to an instance of SSMS running as administrator and the profiler started with no problem. (I previously had found that when my connections even to local took a long time to connect, running as administrator helped).

An error when I add a variable to a string

This problem also arise when we don't give the single or double quotes to the database value.

Wrong way:

$query ="INSERT INTO tabel_name VALUE ($value1,$value2)";

As database inserting values must be in quotes ' '/" "

Right way:

$query ="INSERT INTO STUDENT VALUE ('$roll_no','$name','$class')";

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Typical Java programs compile into .jar files, which can be executed like .exe files provided the target machine has Java installed and that Java is in its PATH. From Eclipse you use the Export menu item from the File menu.

How can Bash execute a command in a different directory context?

(cd /path/to/your/special/place;/bin/your-special-command ARGS)

Random string generation with upper case letters and digits

I was looking at the different answers and took time to read the documentation of secrets

The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.

In particularly, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.

Looking more into what it has to offer I found a very handy function if you want to mimic an ID like Google Drive IDs:

secrets.token_urlsafe([nbytes=None])
Return a random URL-safe text string, containing nbytes random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters. If nbytes is None or not supplied, a reasonable default is used.

Use it the following way:

import secrets
import math

def id_generator():
    id = secrets.token_urlsafe(math.floor(32 / 1.3))
    return id

print(id_generator())

Output a 32 characters length id:

joXR8dYbBDAHpVs5ci6iD-oIgPhkeQFk

I know this is slightly different from the OP's question but I expect that it would still be helpful to many who were looking for the same use-case that I was looking for.

Find if current time falls in a time range

Using Linq we can simplify this by this

 Enumerable.Range(0, (int)(to - from).TotalHours + 1)
            .Select(i => from.AddHours(i)).Where(date => date.TimeOfDay >= new TimeSpan(8, 0, 0) && date.TimeOfDay <= new TimeSpan(18, 0, 0))

How to set ssh timeout?

Use the -o ConnectTimeout and -o BatchMode=yes -o StrictHostKeyChecking=no .

ConnectTimeout keeps the script from hanging, BatchMode keeps it from hanging with Host unknown, YES to add to known_hosts, and StrictHostKeyChecking adds the fingerprint automatically.

**** NOTE **** The "StrictHostKeyChecking" was only intended for internal networks where you trust you hosts. Depending on the version of the SSH client, the "Are you sure you want to add your fingerprint" can cause the client to hang indefinitely (mainly old versions running on AIX). Most modern versions do not suffer from this issue. If you have to deal with fingerprints with multiple hosts, I recommend maintaining the known_hosts file with some sort of configuration management tool like puppet/ansible/chef/salt/etc.

Open directory dialog

None of these answers worked for me (generally there was a missing reference or something along those lines)

But this quite simply did:

Using FolderBrowserDialog in WPF application

Add a reference to System.Windows.Forms and use this code:

  var dialog = new System.Windows.Forms.FolderBrowserDialog();
  System.Windows.Forms.DialogResult result = dialog.ShowDialog();

No need to track down missing packages. Or add enormous classes

This gives me a modern folder selector that also allows you to create a new folder

I'm yet to see the impact when deployed to other machines

SQL Server - boolean literal?

How to write literal boolean value in SQL Server?
select * from SomeTable where PSEUDO_TRUE

There is no such thing.

You have to compare the value with something using = < > like .... The closest you get a boolean value in SQL Server is the bit. And that is an integer that can have the values null, 0 and 1.

How to strip a specific word from a string?

A bit 'lazy' way to do this is to use startswith- it is easier to understand this rather regexps. However regexps might work faster, I haven't measured.

>>> papa = "papa is a good man"
>>> app = "app is important"
>>> strip_word = 'papa'
>>> papa[len(strip_word):] if papa.startswith(strip_word) else papa
' is a good man'
>>> app[len(strip_word):] if app.startswith(strip_word) else app
'app is important'

How to show all of columns name on pandas dataframe?

In the interactive console, it's easy to do:

data_all2.columns.tolist()

Or this within a script:

print(data_all2.columns.tolist())

Parcelable encountered IOException writing serializable object getactivity()

Need to change all arraylist to Serializable wif in bean class :

public static class PremiumListBean  implements Serializable {
    private List<AddOnValueBean> AddOnValue;

    public List<AddOnValueBean> getAddOnValue() {
        return AddOnValue;
     }

    public void setAddOnValue(List<AddOnValueBean> AddOnValue) {
        this.AddOnValue = AddOnValue;
    }


    public static class AddOnValueBean  implements Serializable{

        @SerializedName("Premium")
        private String Premium;

        public String getPremium() {
            return Premium;
        }

        public void setPremium(String Premium) {
            this.Premium = Premium;
        }
    }
 }

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

Expanding tuples into arguments

Note that you can also expand part of argument list:

myfun(1, *("foo", "bar"))

How to access my localhost from another PC in LAN?

Actualy you don't need an internet connection to use ip address. Each computer in LAN has an internal IP address you can discover by runing

ipconfig /all

in cmd.

You can use the ip address of the server (probabily something like 192.168.0.x or 10.0.0.x) to access the website remotely.

If you found the ip and still cannot access the website, it means WAMP is not configured to respond to that name ( what did you call me? 192.168.0.3? That's not my name. I'm Localhost ) and you have to modify ....../apache/config/httpd.conf

Listen *:80

How to make an image center (vertically & horizontally) inside a bigger div

Vertical-align is one of the most misused css styles. It doesn't work how you might expect on elements that are not td's or css "display: table-cell".

This is a very good post on the matter. http://phrogz.net/CSS/vertical-align/index.html

The most common methods to acheive what you're looking for are:

  • padding top/bottom
  • position absolute
  • line-height

Disable automatic sorting on the first column when using jQuery DataTables

Set the aaSorting option to an empty array. It will disable initial sorting, whilst still allowing manual sorting when you click on a column.

"aaSorting": []

The aaSorting array should contain an array for each column to be sorted initially containing the column's index and a direction string ('asc' or 'desc').

Java stack overflow error - how to increase the stack size in Eclipse?

Look at Morris in-order tree traversal which uses constant space and runs in O(n) (up to 3 times longer than your normal recursive traversal - but you save hugely on space). If the nodes are modifiable, than you could save the calculated result of the sub-tree as you backtrack to its root (by writing directly to the Node).

matplotlib colorbar in each subplot

Specify the ax argument to matplotlib.pyplot.colorbar(), e.g.

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2)
for i in range(2):
    for j in range(2):
         data = np.array([[i, j], [i+0.5, j+0.5]])
         im = ax[i, j].imshow(data)
         plt.colorbar(im, ax=ax[i, j])

plt.show()

enter image description here

Laravel 5 Carbon format datetime

Just use the date() and strtotime() function and save your time

$suborder['payment_date'] = date('d-m-Y', strtotime($item['created_at']));

Don't stress!!!

Load a UIView from nib in Swift

I achieved this with Swift by the following code:

class Dialog: UIView {
    @IBOutlet var view:UIView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.frame = UIScreen.mainScreen().bounds
        NSBundle.mainBundle().loadNibNamed("Dialog", owner: self, options: nil)
        self.view.frame = UIScreen.mainScreen().bounds
        self.addSubview(self.view)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

Don't forget to connect your XIB view outlet to view outlet defined in swift. You can also set First Responder to your custom class name to start connecting any additional outlets.

Hope this helps!

Rounded corner for textview in android

Since your top level view already has android:background property set, you can use a <layer-list> (link) to create a new XML drawable that combines both your old background and your new rounded corners background.

Each <item> element in the list is drawn over the next, so the last item in the list is the one that ends up on top.

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <bitmap android:src="@drawable/mydialogbox" />
    </item>
    <item>
        <shape>
            <stroke
                android:width="1dp"
                android:color="@color/common_border_color" />

            <solid android:color="#ffffff" />

            <padding
                    android:left="1dp"
                    android:right="1dp"
                    android:top="1dp" />

            <corners android:radius="5dp" />
        </shape>
    </item>
</layer-list>

Adding custom HTTP headers using JavaScript

If you're using XHR, then setRequestHeader should work, e.g.

xhr.setRequestHeader('custom-header', 'value');

P.S. You should use Hijax to modify the behavior of your anchors so that it works if for some reason the AJAX isn't working for your clients (like a busted script elsewhere on the page).

Can someone explain __all__ in Python?

Short answer

__all__ affects from <module> import * statements.

Long answer

Consider this example:

foo
+-- bar.py
+-- __init__.py

In foo/__init__.py:

  • (Implicit) If we don't define __all__, then from foo import * will only import names defined in foo/__init__.py.

  • (Explicit) If we define __all__ = [], then from foo import * will import nothing.

  • (Explicit) If we define __all__ = [ <name1>, ... ], then from foo import * will only import those names.

Note that in the implicit case, python won't import names starting with _. However, you can force importing such names using __all__.

You can view the Python document here.

Simple and clean way to convert JSON string to Object in Swift

For Swift 4

I used @Passkit's logic but i had to update as per Swift 4


Step.1 Created extension for String Class

import UIKit


extension String
    {
        var parseJSONString: AnyObject?
        {
            let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false)

            if let jsonData = data
            {
                // Will return an object or nil if JSON decoding fails
                do
                {
                    let message = try JSONSerialization.jsonObject(with: jsonData, options:.mutableContainers)
                    if let jsonResult = message as? NSMutableArray
                    {
                        print(jsonResult)

                        return jsonResult //Will return the json array output
                    }
                    else
                    {
                        return nil
                    }
                }
                catch let error as NSError
                {
                    print("An error occurred: \(error)")
                    return nil
                }
            }
            else
            {
                // Lossless conversion of the string was not possible
                return nil
            }
        }
    }

Step.2 This is how I used in my view controller

var jsonString = "[\n" +
    "{\n" +
    "\"id\":72,\n" +
    "\"name\":\"Batata Cremosa\",\n" +            
    "},\n" +
    "{\n" +
    "\"id\":183,\n" +
    "\"name\":\"Caldeirada de Peixes\",\n" +            
    "},\n" +
    "{\n" +
    "\"id\":76,\n" +
    "\"name\":\"Batata com Cebola e Ervas\",\n" +            
    "},\n" +
    "{\n" +
    "\"id\":56,\n" +
    "\"name\":\"Arroz de forma\",\n" +            
"}]"

 //Convert jsonString to jsonArray

let json: AnyObject? = jsonString.parseJSONString
print("Parsed JSON: \(json!)")
print("json[2]: \(json![2])")

All credit goes to original user, I just updated for latest swift version

lambda expression join multiple tables with select and where clause

I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.

    var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
    .Select (m => new 
    {
        UserName = u.UserProfile.UserName,
        RoleName = u.Roles.RoleName
    });

Comparison between Corona, Phonegap, Titanium

I'm taking a course in Android/iPhone development and we spent 8 weeks with Titanium (not full time) (Version was Titanium 1.4.2 and time was around November 2010). Here is my experience.

iPhone Android dual targetting

Even though the API guides claim that the functionality is available for both the Android and iPhone, this is not the case. Much of the stuff simply don't work on one of the platforms. Some things works differently.

A lot of the people in the class has done iPhone applications, and they can not make them work on Android without major rewrites. I developed a simple childrens app called Animap (see android market / Appstore in Sweden) and started developing under Windows. Once the Android target was working I opened the project on OS X. It does not show any build stuff for iPhone, just for Android. You need to start a dual target project under OS X. (Ok, I copied the relevant files to a new project). Next problem - the animations does not work on iPhone (they work on Android). The scrolling events does not work the same on the iPhone. (i.e on Android you get the untouch event when user stops scrolling and releases their finger from the screen, this does not happen on the iPhone).

Since this is not mentioned somewhere you basicly need to do trial and error programming on first one platform, then on the other platform. By trial and error I mean it will take about two days to get such a simple App as Animap working on the other platform. You will also need to have if (android) then... or if(iphone)... all over your code...

Download and setup

You must follow the instructions to the letter. Do not try to use java 64 bit. It will not compile the KitchenSink 1.4.0 demo application. (1.3 works OK!) You must put files directly on the C drive as long pathnames will make the external program not receiving all command line parameters if they get to long. (Fine for small programs though) 1/3 of the times, the toolchain simply stops and you must press 'launch' again. Then it will probably work... very unreliable. The simulator will not be found on startup and then you must simply kill of adb.exe with Ctrl+Alt+Delete and retry.

Network connection

On a wifi-network you sometimes looses the live connection and Titanium crashes on you (the compile/deploy interface) If you do not have a working internet connection it will not start as it can not log you in to their servers.

API

CSS, HTML and jQuery is a breeze compared to this. Titanium resembles any other old GUI API, and you need to set some properties for every single button/field/etc. Getting a field wrong is just to easy, remembering all the properties that needs to be set? Did you spell it with capital letters at the right place? (as this is not caught by the compiler, but will be seen as a runtime error if you are lucky to test that part)

In Titanium things simply break when you add another view on top of a control or click somewhere else in the GUI.

Documentation

Several API pages carry the Android symbol, but will only return a null when you try to create the control. They are not simply available on the Android platform despite the symbols. Sometimes Android is mention to not support a particular method, but then the whole API is missing.

KitchenSink

The demo application. Did I mention it does not compile if you put it in your Eclipse project folder because the path gets too long? Must be put on your C drive in the root folder. I currently use a symbolik link (mklink /J ...)

Undocumented methods

You must propably use things as label.setText('Hello World') to change a label reliable but this is not documented at all.

Debugging

Titanium.API.info('Printouts are the only way to debug');

Editing

The APIs are not available in any good format so you can not get ordinary code-completion with help etc. in Eclipse. Aptana please help out!

Hardware

It seems that the compiler/tools are not multithreaded so a fast computer with a fast harddrive is a must, as you must do a lot of trial & error. Did I mention the poor documentation? You must try out everything there as you can't trust it!

Some positive things

  • Open Source
  • From previous projects I have promised myself never ever to use closed source again as you can't simply fix things just by throwing hours and manpower at it. Important when you are late in the project and need to deliver for a hard deadline. This is open source and I have been able to see why the tool chain breaks and actually fix it as well.

  • Bugdatabase

  • It's also open. You can simply see that your not alone and do a workaround instead of another 4 hours spent on trial&error.

  • Community

  • Seems to be active on their forums.

Bugs

  • Titanium 1.4 is not threadsafe. That means if you make use of threads (use the url: property in a createWindow call) and program like the threads are working and send events with data back and forth you run into a lot of very, very strange stuff - lost handlers, lost windows, too many events, too few events, etc. etc. This is all dependent on the timing, putting the rows of code in different order might crash or heal your application. Adding a window in another file.js breaks your app.js execution... This also trashes internal datastructures in Titanium, as they sometimes can update internal datastructures in paralell, overwriting a just changed value with something else.

Much of the problems I have had with Titanium comes from my background on realtime systems like OSE who support hundreds of threads, events and message passing. This is supposed to work in Titanium 1.4 but it simply doesn't do it reliably.

  • Javascript (which is new to me) dies silently on runtime errors. This also means that small and common bugs, like misspelling a variable name or reading in a null-pointer does not crash when it should so you can debug it. Instead parts of your program just stop working, for instance an eventhandler, because you misplaced/misstyped a character.

  • Then we have more simple bugs in Titanium, like some parameters not working in the functions (which is quite common on the Android platform at least).

  • Trial and Error debug cycle speed Having run Titnium Developer on several computers, I noticed that the bottleneck is the harddrive. An SSD drive on a laptop makes the build cycle about 3-5 times faster than on a 4200 rpm drive. On a desktop, having dual drives in RAID 1 (striping mode) makes the build about 25 percent faster than on a single drive with a somewhat faster CPU and it also beats the SSD drive laptop.

Summary

  • From the comments in this thread there seems to be a fight for the number of platforms a tool like this can deliver app's for. The number of API seems to be the key selling-point.

This shines through very much when you start using it. If you look at the open bugtracker you see that the number of bugs keeps increasing faster than the number of fixed bugs. This is usually a sign that the developers keep adding more functionality, rather than concentrating on getting the number of bugs down.

As a consultant trying to deliver rather simple apps to multiplatforms for a customer - I'm not sure this is actually faster than doing native app development on two platforms. This is due to the fact that when you are up to speed you are fast with Titanium, but then suddenly you look down and find yourself in a hole so deep you don't know how many hours must be spent for a workaround. You can simply NOT promise a certain functionality for a certain deadline/time/cost.

About myself: Been using Python for two years with wxPython. (that GUI is inconsitent, but never breaks like this. It might be me that have not understood the threading model used by Javascript and Titanium, but I am not alone according to their open discussion forums, GUI objects are suddenly using the wrong context/not updating..???) before that I have a background in C and ASM programming for mobile devices.

[edit - added part with bugs and not being thread safe] [Edit - now having worked with it for a month+, mostly on PC but some on OS X as well. Added iPhone and Android dual targetting. Added Trial and Error debug cycle speed.]

Python: get key of index in dictionary

You could do something like this:

i={'foo':'bar', 'baz':'huh?'}
keys=i.keys()  #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")]  #'foo'

However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.

As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.

Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:

d={'i':1, 'j':1}

In that case, it is impossible to know whether you want i or j and in fact no answer here will be able to tell you which ('i' or 'j') will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.

Java: notify() vs. notifyAll() all over again

I would like to mention what is explained in Java Concurrency in Practice:

First point, whether Notify or NotifyAll?

It will be NotifyAll, and reason is that it will save from signall hijacking.

If two threads A and B are waiting on different condition predicates of same condition queue and notify is called, then it is upto JVM to which thread JVM will notify.

Now if notify was meant for thread A and JVM notified thread B, then thread B will wake up and see that this notification is not useful so it will wait again. And Thread A will never come to know about this missed signal and someone hijacked it's notification.

So, calling notifyAll will resolve this issue, but again it will have performance impact as it will notify all threads and all threads will compete for same lock and it will involve context switch and hence load on CPU. But we should care about performance only if it is behaving correctly, if it's behavior itself is not correct then performance is of no use.

This problem can be solved with using Condition object of explicit locking Lock, provided in jdk 5, as it provides different wait for each condition predicate. Here it will behave correctly and there will not be performance issue as it will call signal and make sure that only one thread is waiting for that condition

LINQ query to select top five

This can also be achieved using the Lambda based approach of Linq;

var list = ctn.Items
.Where(t=> t.DeliverySelection == true && t.Delivery.SentForDelivery == null)
.OrderBy(t => t.Delivery.SubmissionDate)
.Take(5);

Eclipse : Maven search dependencies doesn't work

You can get this result if you are inside a corporate proxy and the new project isn't pointing to the correct settings.xml file with the proxy credentials.

You can also get this if you are using Maven proxy (Nexus, for example) and the index into the proxy is messed up somehow. I don't know a way to describe how to fix this. Fool around with it or call the one who set up the Maven proxy.

You can also get this if the new workspace hasn't yet downloaded the index either from Maven central or from the proxy. (This is the best one as you just have to wait a while and it will work itself out.)

How can I fix MySQL error #1064?

TL;DR

Error #1064 means that MySQL can't understand your command. To fix it:

  • Read the error message. It tells you exactly where in your command MySQL got confused.

  • Examine your command. If you use a programming language to create your command, use echo, console.log(), or its equivalent to show the entire command so you can see it.

  • Check the manual. By comparing against what MySQL expected at that point, the problem is often obvious.

  • Check for reserved words. If the error occurred on an object identifier, check that it isn't a reserved word (and, if it is, ensure that it's properly quoted).

  1. Aaaagh!! What does #1064 mean?

    Error messages may look like gobbledygook, but they're (often) incredibly informative and provide sufficient detail to pinpoint what went wrong. By understanding exactly what MySQL is telling you, you can arm yourself to fix any problem of this sort in the future.

    As in many programs, MySQL errors are coded according to the type of problem that occurred. Error #1064 is a syntax error.

    • What is this "syntax" of which you speak? Is it witchcraft?

      Whilst "syntax" is a word that many programmers only encounter in the context of computers, it is in fact borrowed from wider linguistics. It refers to sentence structure: i.e. the rules of grammar; or, in other words, the rules that define what constitutes a valid sentence within the language.

      For example, the following English sentence contains a syntax error (because the indefinite article "a" must always precede a noun):

      This sentence contains syntax error a.

    • What does that have to do with MySQL?

      Whenever one issues a command to a computer, one of the very first things that it must do is "parse" that command in order to make sense of it. A "syntax error" means that the parser is unable to understand what is being asked because it does not constitute a valid command within the language: in other words, the command violates the grammar of the programming language.

      It's important to note that the computer must understand the command before it can do anything with it. Because there is a syntax error, MySQL has no idea what one is after and therefore gives up before it even looks at the database and therefore the schema or table contents are not relevant.

  2. How do I fix it?

    Obviously, one needs to determine how it is that the command violates MySQL's grammar. This may sound pretty impenetrable, but MySQL is trying really hard to help us here. All we need to do is…

    • Read the message!

      MySQL not only tells us exactly where the parser encountered the syntax error, but also makes a suggestion for fixing it. For example, consider the following SQL command:

      UPDATE my_table WHERE id=101 SET name='foo'
      

      That command yields the following error message:

      ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id=101 SET name='foo'' at line 1

      MySQL is telling us that everything seemed fine up to the word WHERE, but then a problem was encountered. In other words, it wasn't expecting to encounter WHERE at that point.

      Messages that say ...near '' at line... simply mean that the end of command was encountered unexpectedly: that is, something else should appear before the command ends.

    • Examine the actual text of your command!

      Programmers often create SQL commands using a programming language. For example a php program might have a (wrong) line like this:

      $result = $mysqli->query("UPDATE " . $tablename ."SET name='foo' WHERE id=101");
      

      If you write this this in two lines

      $query = "UPDATE " . $tablename ."SET name='foo' WHERE id=101"
      $result = $mysqli->query($query);
      

      then you can add echo $query; or var_dump($query) to see that the query actually says

      UPDATE userSET name='foo' WHERE id=101
      

      Often you'll see your error immediately and be able to fix it.

    • Obey orders!

      MySQL is also recommending that we "check the manual that corresponds to our MySQL version for the right syntax to use". Let's do that.

      I'm using MySQL v5.6, so I'll turn to that version's manual entry for an UPDATE command. The very first thing on the page is the command's grammar (this is true for every command):

      UPDATE [LOW_PRIORITY] [IGNORE] table_reference
          SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
          [WHERE where_condition]
          [ORDER BY ...]
          [LIMIT row_count]
      

      The manual explains how to interpret this syntax under Typographical and Syntax Conventions, but for our purposes it's enough to recognise that: clauses contained within square brackets [ and ] are optional; vertical bars | indicate alternatives; and ellipses ... denote either an omission for brevity, or that the preceding clause may be repeated.

      We already know that the parser believed everything in our command was okay prior to the WHERE keyword, or in other words up to and including the table reference. Looking at the grammar, we see that table_reference must be followed by the SET keyword: whereas in our command it was actually followed by the WHERE keyword. This explains why the parser reports that a problem was encountered at that point.

    A note of reservation

    Of course, this was a simple example. However, by following the two steps outlined above (i.e. observing exactly where in the command the parser found the grammar to be violated and comparing against the manual's description of what was expected at that point), virtually every syntax error can be readily identified.

    I say "virtually all", because there's a small class of problems that aren't quite so easy to spot—and that is where the parser believes that the language element encountered means one thing whereas you intend it to mean another. Take the following example:

    UPDATE my_table SET where='foo'
    

    Again, the parser does not expect to encounter WHERE at this point and so will raise a similar syntax error—but you hadn't intended for that where to be an SQL keyword: you had intended for it to identify a column for updating! However, as documented under Schema Object Names:

    If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.

    [ deletia ]

    The identifier quote character is the backtick (“`”):

    mysql> SELECT * FROM `select` WHERE `select`.id > 100;

    If the ANSI_QUOTES SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks:

    mysql> CREATE TABLE "test" (col INT);
    ERROR 1064: You have an error in your SQL syntax...
    mysql> SET sql_mode='ANSI_QUOTES';
    mysql> CREATE TABLE "test" (col INT);
    Query OK, 0 rows affected (0.00 sec)

How do I count columns of a table

I think you need also to specify the name of the database:

SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = 'SchemaNameHere'
  AND table_name = 'TableNameHere'

if you don't specify the name of your database, chances are it will count all columns as long as it matches the name of your table. For example, you have two database: DBaseA and DbaseB, In DBaseA, it has two tables: TabA(3 fields), TabB(4 fields). And in DBaseB, it has again two tables: TabA(4 fields), TabC(4 fields).

if you run this query:

SELECT count(*)
FROM information_schema.columns
WHERE table_name = 'TabA'

it will return 7 because there are two tables named TabA. But by adding another condition table_schema = 'SchemaNameHere':

SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = 'DBaseA'
  AND table_name = 'TabA'

then it will only return 3.

SQL statement to select all rows from previous day

get today no time:

SELECT dateadd(day,datediff(day,0,GETDATE()),0)

get yestersday no time:

SELECT dateadd(day,datediff(day,1,GETDATE()),0)

query for all of rows from only yesterday:

select 
    * 
    from yourTable
    WHERE YourDate >= dateadd(day,datediff(day,1,GETDATE()),0)
        AND YourDate < dateadd(day,datediff(day,0,GETDATE()),0)

How can I hide or encrypt JavaScript code?

You can obfuscate it, but there's no way of protecting it completely.

example obfuscator: https://obfuscator.io

Select arrow style change

This would work well especially for those using Bootstrap, tested in latest browser versions:

_x000D_
_x000D_
select {_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  appearance: none;_x000D_
  /* Some browsers will not display the caret when using calc, so we put the fallback first */ _x000D_
  background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") white no-repeat 98.5% !important; /* !important used for overriding all other customisations */_x000D_
  background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") white no-repeat calc(100% - 10px) !important; /* Better placement regardless of input width */_x000D_
}_x000D_
/*For IE*/_x000D_
select::-ms-expand { display: none; }
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-xs-6">_x000D_
      <select class="form-control">_x000D_
       <option>Option 1</option>_x000D_
       <option>Option 2</option>_x000D_
       <option>Option 3</option>_x000D_
      </select>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Java Switch Statement - Is "or"/"and" possible?

Above, you mean OR not AND. Example of AND: 110 & 011 == 010 which is neither of the things you're looking for.

For OR, just have 2 cases without the break on the 1st. Eg:

case 'a':
case 'A':
  // do stuff
  break;

Spring @Transactional - isolation, propagation

PROPAGATION_REQUIRED = 0; If DataSourceTransactionObject T1 is already started for Method M1. If for another Method M2 Transaction object is required, no new Transaction object is created. Same object T1 is used for M2.

PROPAGATION_MANDATORY = 2; method must run within a transaction. If no existing transaction is in progress, an exception will be thrown.

PROPAGATION_REQUIRES_NEW = 3; If DataSourceTransactionObject T1 is already started for Method M1 and it is in progress (executing method M1). If another method M2 start executing then T1 is suspended for the duration of method M2 with new DataSourceTransactionObject T2 for M2. M2 run within its own transaction context.

PROPAGATION_NOT_SUPPORTED = 4; If DataSourceTransactionObject T1 is already started for Method M1. If another method M2 is run concurrently. Then M2 should not run within transaction context. T1 is suspended till M2 is finished.

PROPAGATION_NEVER = 5; None of the methods run in transaction context.


An isolation level: It is about how much a transaction may be impacted by the activities of other concurrent transactions. It a supports consistency leaving the data across many tables in a consistent state. It involves locking rows and/or tables in a database.

The problem with multiple transaction

Scenario 1. If T1 transaction reads data from table A1 that was written by another concurrent transaction T2. If on the way T2 is rollback, the data obtained by T1 is invalid one. E.g. a=2 is original data. If T1 read a=1 that was written by T2. If T2 rollback then a=1 will be rollback to a=2 in DB. But, now, T1 has a=1 but in DB table it is changed to a=2.

Scenario2. If T1 transaction reads data from table A1. If another concurrent transaction (T2) update data on table A1. Then the data that T1 has read is different from table A1. Because T2 has updated the data on table A1. E.g. if T1 read a=1 and T2 updated a=2. Then a!=b.

Scenario 3. If T1 transaction reads data from table A1 with certain number of rows. If another concurrent transaction (T2) inserts more rows on table A1. The number of rows read by T1 is different from rows on table A1.

Scenario 1 is called Dirty reads.

Scenario 2 is called Non-repeatable reads.

Scenario 3 is called Phantom reads.

So, isolation level is the extend to which Scenario 1, Scenario 2, Scenario 3 can be prevented. You can obtain complete isolation level by implementing locking. That is preventing concurrent reads and writes to the same data from occurring. But it affects performance. The level of isolation depends upon application to application how much isolation is required.

ISOLATION_READ_UNCOMMITTED: Allows to read changes that haven’t yet been committed. It suffer from Scenario 1, Scenario 2, Scenario 3.

ISOLATION_READ_COMMITTED: Allows reads from concurrent transactions that have been committed. It may suffer from Scenario 2 and Scenario 3. Because other transactions may be updating the data.

ISOLATION_REPEATABLE_READ: Multiple reads of the same field will yield the same results untill it is changed by itself. It may suffer from Scenario 3. Because other transactions may be inserting the data.

ISOLATION_SERIALIZABLE: Scenario 1, Scenario 2, Scenario 3 never happen. It is complete isolation. It involves full locking. It affects performace because of locking.

You can test using:

public class TransactionBehaviour {
   // set is either using xml Or annotation
    DataSourceTransactionManager manager=new DataSourceTransactionManager();
    SimpleTransactionStatus status=new SimpleTransactionStatus();
   ;
  
    
    public void beginTransaction()
    {
        DefaultTransactionDefinition Def = new DefaultTransactionDefinition();
        // overwrite default PROPAGATION_REQUIRED and ISOLATION_DEFAULT
        // set is either using xml Or annotation
        manager.setPropagationBehavior(XX);
        manager.setIsolationLevelName(XX);
       
        status = manager.getTransaction(Def);
    
    }

    public void commitTransaction()
    {
       
      
            if(status.isCompleted()){
                manager.commit(status);
        } 
    }

    public void rollbackTransaction()
    {
       
            if(!status.isCompleted()){
                manager.rollback(status);
        }
    }
    Main method{
        beginTransaction()
        M1();
        If error(){
            rollbackTransaction()
        }
         commitTransaction();
    }
   
}

You can debug and see the result with different values for isolation and propagation.

How do I upgrade to Python 3.6 with conda?

Best method I found:

source activate old_env
conda env export > old_env.yml

Then process it with something like this:

with open('old_env.yml', 'r') as fin, open('new_env.yml', 'w') as fout:
    for line in fin:
        if 'py35' in line:  # replace by the version you want to supersede
            line = line[:line.rfind('=')] + '\n'
        fout.write(line)

then edit manually the first (name: ...) and last line (prefix: ...) to reflect your new environment name and run:

conda env create -f new_env.yml

you might need to remove or change manually the version pin of a few packages for which which the pinned version from old_env is found incompatible or missing for the new python version.

I wish there was a built-in, easier way...

Removing the fragment identifier from AngularJS urls (# symbol)

According to the documentation. You can use:

$locationProvider.html5Mode(true).hashPrefix('!');

NB: If your browser does not support to HTML 5. Dont worry :D it have fallback to hashbang mode. So, you don't need to check with if(window.history && window.history.pushState){ ... } manually

For example: If you click: <a href="/other">Some URL</a>

In HTML5 Browser: angular will automatically redirect to example.com/other

In Not HTML5 Browser: angular will automatically redirect to example.com/#!/other

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.

Count immediate child div elements using jQuery

$("#foo > div") 

selects all divs that are immediate descendants of #foo
once you have the set of children you can either use the size function:

$("#foo > div").size()

or you can use

$("#foo > div").length

Both will return you the same result