Programs & Examples On #Wwan

symbol(s) not found for architecture i386

Sometimes there are source files which are missing from your target.

  1. examine which symbols are missing
  2. target->build phases->compile source
  3. add the missing source files if they are not listed
  4. command+b for bliss

You can select the files that seem to be "missing" and check in the right-hand utility bar that their checkboxes are selected for the Target you are building.

force client disconnect from server with socket.io and nodejs

Edit: This is now possible

You can now simply call socket.disconnect() on the server side.

My original answer:

This is not possible yet.

If you need it as well, vote/comment on this issue.

SQL: how to select a single id ("row") that meets multiple criteria from a single column

brute force (and only tested on an Oracle system, but I think this is pretty standard):

select distinct usr_id from users where user_id in (
    select user_id from (
      Select user_id, Count(User_Id) As Cc
      From users 
      GROUP BY user_id
    ) Where Cc =3
  )
  and ancestry in ('England', 'France', 'Germany')
;

edit: I like @HuckIt's answer even better.

Guid is all 0's (zeros)?

Use the static method Guid.NewGuid() instead of calling the default constructor.

var responseObject = proxy.CallService(new RequestObject
{
    Data = "misc. data",
    Guid = Guid.NewGuid()
});

How can I show/hide component with JSF?

You can actually accomplish this without JavaScript, using only JSF's rendered attribute, by enclosing the elements to be shown/hidden in a component that can itself be re-rendered, such as a panelGroup, at least in JSF2. For example, the following JSF code shows or hides one or both of two dropdown lists depending on the value of a third. An AJAX event is used to update the display:

<h:selectOneMenu value="#{workflowProcEditBean.performedBy}">
    <f:selectItem itemValue="O" itemLabel="Originator" />
    <f:selectItem itemValue="R" itemLabel="Role" />
    <f:selectItem itemValue="E" itemLabel="Employee" />
    <f:ajax event="change" execute="@this" render="perfbyselection" />
</h:selectOneMenu>
<h:panelGroup id="perfbyselection">
    <h:selectOneMenu id="performedbyroleid" value="#{workflowProcEditBean.performedByRoleID}"
                     rendered="#{workflowProcEditBean.performedBy eq 'R'}">
        <f:selectItem itemLabel="- Choose One -" itemValue="" />
        <f:selectItems value="#{workflowProcEditBean.roles}" />
    </h:selectOneMenu>
    <h:selectOneMenu id="performedbyempid" value="#{workflowProcEditBean.performedByEmpID}"
                     rendered="#{workflowProcEditBean.performedBy eq 'E'}">
        <f:selectItem itemLabel="- Choose One -" itemValue="" />
        <f:selectItems value="#{workflowProcEditBean.employees}" />
    </h:selectOneMenu>
</h:panelGroup>

"git rm --cached x" vs "git reset head --? x"?

git rm --cached file will remove the file from the stage. That is, when you commit the file will be removed. git reset HEAD -- file will simply reset file in the staging area to the state where it was on the HEAD commit, i.e. will undo any changes you did to it since last commiting. If that change happens to be newly adding the file, then they will be equivalent.

Access Form - Syntax error (missing operator) in query expression

Guys am facing similar issue here is my full code

Do let me know where am i going wrong. Error message: syntax error (Missing operator) in query expression 'AutoID='

This only hapens when i click on login without entering any txt in either combobox and password field.

    Option Compare Database
Option Explicit

Private Sub Login_Click()

If IsNull(Me.ComboUserSelect.Value) Then
    MsgBox "Please select username", vbInformation, "Login ID Required"
    Me.ComboUserSelect.SetFocus
ElseIf IsNull(Me.txtpassword.Value) Then
    MsgBox "please enter password", vbInformation, "Password is Required"
    Me.txtpassword.SetFocus
End If

'============= Declaring the variables ==========='
Dim passwordindatabase As String
Dim typedpassword As String
Dim useraccesstype As String


passwordindatabase = DLookup("Password", "LoginDB", "AutoID=" & ComboUserSelect.Value)
typedpassword = txtpassword.Value
useraccesstype = DLookup("AccessType", "LoginDB", "AutoID=" & ComboUserSelect.Value)


If typedpassword = passwordindatabase Then
    If useraccesstype = "Admin" Then
    DoCmd.OpenForm ("Cam Infra")
    DoCmd.Close acForm, "Login_Form", acSaveNo
    Else
    If useraccesstype = "user" Then
    DoCmd.OpenForm ("Custom_Search_Form")
    DoCmd.Close acForm, "Login_Form", acSaveNo
    End If
    End If
    End If
    

End Sub

Nexus 5 USB driver

Well @sonida's answer helped me but Here I am posting complete step How I did it.

Change Mobile Device Settings:

  1. Unplug the device from the computer
  2. Go to Mobile Settings -> Storage.
  3. In the ActionBar, click the option menu and choose "USB computer connection".
  4. Check "Camera (PTP)" connection.

enter image description here

enter image description here

Download Google USB Driver:

5 .Now go to http://developer.android.com/sdk/win-usb.html#top and download USB Drivers --> unzip folder.

enter image description here

Install USB Drivers and Get Connected Device:

6.Then Right click on My computer -->Manage --> Device Manager.

enter image description here

7.You should seed Nexus 5 in the list.

8.Right click on Nexus 5 --> Update Driver Software... --> Browse my computer for driver software

enter image description here

9.select the folder we downloaded/unzipped "latest_usb_driver_windows" and Next ...Ok.

enter image description here

10.Now you will see pop-up dialogue asking for Allow device --> Ok.

11 .That's it!! device is connected now, you can see in DDMS.

enter image description here

Hope this will help someone.

Silent installation of a MSI package

You should be able to use the /quiet or /qn options with msiexec to perform a silent install.

MSI packages export public properties, which you can set with the PROPERTY=value syntax on the end of the msiexec parameters.

For example, this command installs a package with no UI and no reboot, with a log and two properties:

msiexec /i c:\path\to\package.msi /quiet /qn /norestart /log c:\path\to\install.log PROPERTY1=value1 PROPERTY2=value2

You can read the options for msiexec by just running it with no options from Start -> Run.

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

Add overflow: auto; to the style and the two finger scroll should work.

SQL Plus change current directory

for me shelling-out does the job because it gives you possibility to run [a|any] command on the shell:

http://www.dba-oracle.com/t_display_current_directory_sqlplus.htm

in short see the current directory:

!pwd

change it

!cd /path/you/want

Where do I put my php files to have Xampp parse them?

I created my project folder 'phpproj' in

...\xampp\htdocs

ex:...\xampp\htdocs\phpproj

and it worked for me. I am using Win 7 & and using xampp-win32-1.8.1

I added a php file with the following code

<?php

// Show all information, defaults to INFO_ALL
phpinfo();

?>

was able to access the file using the following URL

http://localhost/phpproj/copy.php

Make sure you restart your Apache server using the control panel before accessing it using the above URL

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Here is how one can do it. I will give an example with joining so that it becomes super clear to someone.

$products = DB::table('products AS pr')
        ->leftJoin('product_families AS pf', 'pf.id', '=', 'pr.product_family_id')
        ->select('pr.id as id', 'pf.name as product_family_name', 'pf.id as product_family_id')
        ->orderBy('pr.id', 'desc')
        ->get();

Hope this helps.

Iptables setting multiple multiports in one rule

As a workaround to this limitation, I use two rules to cover all the cases.

For example, if I want to allow or deny these 18 ports:

465,110,995,587,143,11025,20,21,22,26,80,443,3000,10000,7080,8080,3000,5666

I use the below rules:

iptables -A INPUT -p tcp -i eth0 -m multiport --dports 465,110,995,587,143,11025,20,21,22,26,80,443 -j ACCEPT

iptables -A INPUT -p tcp -i eth0 -m multiport --dports 3000,10000,7080,8080,3000,5666 -j ACCEPT

The above rules should work for your scenario also. You can create another rule if you hit 15 ports limit on both first and second rule.

Getting an error "fopen': This function or variable may be unsafe." when compling

This is a warning for usual. You can either disable it by

#pragma warning(disable:4996)

or simply use fopen_s like Microsoft has intended.

But be sure to use the pragma before other headers.

illegal use of break statement; javascript

break is to break out of a loop like for, while, switch etc which you don't have here, you need to use return to break the execution flow of the current function and return to the caller.

function loop() {
    if (isPlaying) {
        jet1.draw();
        drawAllEnemies();
        requestAnimFrame(loop);
        if (game == 1) {
           return
        }
    }
}

Note: This does not cover the logic behind the if condition or when to return from the method, for that we need to have more context regarding the drawAllEnemies and requestAnimFrame method as well as how game value is updated

How to make child divs always fit inside parent div?

In your example, you can't: the 5px margin is added to the bounding box of div#two and div#three effectively making their width and height 100% of parent + 5px, which will overflow.

You can use padding on the parent Element to ensure there's 5px of space inside its border:

<style>
    html, body {width:100%;height:100%;margin:0;padding:0;}
    .border {border:1px solid black;}
    #one {padding:5px;width:500px;height:300px;}
    #two {width:100%;height:50px;}
    #three {width:100px;height:100%;}
</style>

EDIT: In testing, removing the width:100% from div#two will actually let it work properly as divs are block-level and will always fill their parents' widths by default. That should clear your first case if you'd like to use margin.

JQuery Calculate Day Difference in 2 date textboxes

This should do the trick

var start = $('#start_date').val();
var end = $('#end_date').val();

// end - start returns difference in milliseconds 
var diff = new Date(end - start);

// get days
var days = diff/1000/60/60/24;

Example

var start = new Date("2010-04-01"),
    end   = new Date(),
    diff  = new Date(end - start),
    days  = diff/1000/60/60/24;

days; //=> 8.525845775462964

Eclipse/Maven error: "No compiler is provided in this environment"

Installed JRE In my case I solved the problem by removing duplicates of names, I kept only one with the name: jdk.1.8.0_101

e.printStackTrace equivalent in python

e.printStackTrace equivalent in python

In Java, this does the following (docs):

public void printStackTrace()

Prints this throwable and its backtrace to the standard error stream...

This is used like this:

try
{ 
// code that may raise an error
}
catch (IOException e)
{
// exception handling
e.printStackTrace();
}

In Java, the Standard Error stream is unbuffered so that output arrives immediately.

The same semantics in Python 2 are:

import traceback
import sys
try: # code that may raise an error
    pass 
except IOError as e: # exception handling
    # in Python 2, stderr is also unbuffered
    print >> sys.stderr, traceback.format_exc()
    # in Python 2, you can also from __future__ import print_function
    print(traceback.format_exc(), file=sys.stderr)
    # or as the top answer here demonstrates, use:
    traceback.print_exc()
    # which also uses stderr.

Python 3

In Python 3, we can get the traceback directly from the exception object (which likely behaves better for threaded code). Also, stderr is line-buffered, but the print function gets a flush argument, so this would be immediately printed to stderr:

    print(traceback.format_exception(None, # <- type(e) by docs, but ignored 
                                     e, e.__traceback__),
          file=sys.stderr, flush=True)

Conclusion:

In Python 3, therefore, traceback.print_exc(), although it uses sys.stderr by default, would buffer the output, and you may possibly lose it. So to get as equivalent semantics as possible, in Python 3, use print with flush=True.

Get the length of a String

As of Swift 4+

It's just:

test1.count

for reasons.

(Thanks to Martin R)

As of Swift 2:

With Swift 2, Apple has changed global functions to protocol extensions, extensions that match any type conforming to a protocol. Thus the new syntax is:

test1.characters.count

(Thanks to JohnDifool for the heads up)

As of Swift 1

Use the count characters method:

let unusualMenagerie = "Koala &#128040;, Snail &#128012;, Penguin &#128039;, Dromedary &#128042;"
println("unusualMenagerie has \(count(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"

right from the Apple Swift Guide

(note, for versions of Swift earlier than 1.2, this would be countElements(unusualMenagerie) instead)

for your variable, it would be

length = count(test1) // was countElements in earlier versions of Swift

Or you can use test1.utf16count

How to move mouse cursor using C#?

Take a look at the Cursor.Position Property. It should get you started.

private void MoveCursor()
{
   // Set the Current cursor, move the cursor's Position,
   // and set its clipping rectangle to the form. 

   this.Cursor = new Cursor(Cursor.Current.Handle);
   Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
   Cursor.Clip = new Rectangle(this.Location, this.Size);
}

Excel VBA Open a Folder

I use this to open a workbook and then copy that workbook's data to the template.

Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
 With Application.FileDialog(msoFileDialogOpen)
    .InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
    .Filters.Clear
    .Title = "Your Title"
    If Not .Show Then
        MsgBox "No file selected.": Exit Sub
    End If
    Workbooks.OpenText .SelectedItems(1)

'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1

    Set myfile = ActiveWorkbook
    ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
    myfile.Close
    Template.Activate
    ActiveSheet.Cells.Select
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Select
    ActiveSheet.Paste

End With

How to check if std::map contains a key without doing insert?

Potatoswatter's answer is all right, but I prefer to use find or lower_bound instead. lower_bound is especially useful because the iterator returned can subsequently be used for a hinted insertion, should you wish to insert something with the same key.

map<K, V>::iterator iter(my_map.lower_bound(key));
if (iter == my_map.end() || key < iter->first) {    // not found
    // ...
    my_map.insert(iter, make_pair(key, value));     // hinted insertion
} else {
    // ... use iter->second here
}

How to use JavaScript source maps (.map files)?

The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.

Same for CSS files. Once you take a SASS or LESS file and compile it to CSS, it looks nothing like its original form. If you enable sourcemaps, then you can see the original state of the file, instead of the modified state.

So, to answer you questions in order:

  • What is it for? To de-reference uglified code
  • How can a developer use it? You use it for debugging a production app. In development mode you can use the full version of Angular. In production, you would use the minified version.
  • Should I care about creating a js.map file? If you care about being able to debug production code easier, then yes, you should do it.
  • How does it get created? It is created at build time. There are build tools that can build your .map file for you as it does other files. https://github.com/gruntjs/grunt-contrib-uglify/issues/71

I hope this makes sense.

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

If you call a ng-repeat within a < ul> tag, you may be able to allow duplicates. See this link for reference. See Todo2.html

Where does VBA Debug.Print log to?

Debug.Print outputs to the "Immediate" window.

Debug.Print outputs to the Immediate window

Also, you can simply type ? and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:

simply type ? and then a statement directly into the immediate window

This can be very handy to quickly output the property of an object...

? myWidget.name

...to set the property of an object...

myWidget.name = "thingy"

...or to even execute a function or line of code, while in debugging mode:

Sheet1.MyFunction()

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

An absolute xpath in HTML DOM starts with /html e.g.

/html/body/div[5]/div[2]/div/div[2]/div[2]/h2[1]

and a relative xpath finds the closed id to the dom element and generates xpath starting from that element e.g.

.//*[@id='answers']/h2[1]/a[1]

You can use firepath (firebug) for generating both types of xpaths

It won't make any difference which xpath you use in selenium, the former may be faster than the later one (but it won't be observable)

Absolute xpaths are prone to more regression as slight change in DOM makes them invalid or refer to a wrong element

Setting new value for an attribute using jQuery

It is working you have to check attr after assigning value

LiveDemo

$('#amount').attr( 'datamin','1000');

alert($('#amount').attr( 'datamin'));?

HttpClient does not exist in .net 4.0: what can I do?

Referring to the answers above, I am only adding this to help clarify things. It is possible to use HttpClient from .Net 4.0, and you have to install the package from here

However, the text is very confusion and contradicts itself.

This package is not supported in Visual Studio 2010, and is only required for projects targeting .NET Framework 4.5, Windows 8, or Windows Phone 8.1 when consuming a library that uses this package.

But underneath it states that these are the supported platforms.

Supported Platforms:

  • .NET Framework 4

  • Windows 8

  • Windows Phone 8.1

  • Windows Phone Silverlight 7.5

  • Silverlight 4

  • Portable Class Libraries

Ignore what it ways about targeting .Net 4.5. This is wrong. The package is all about using HttpClient in .Net 4.0. However, you may need to use VS2012 or higher. Not sure if it works in VS2010, but that may be worth testing.

Unzipping files

If you need to support other formats as well or just need good performance, you can use this WebAssembly library

it's promised based, it uses WebWorkers for threading and API is actually simple ES module

ImportError: No module named tensorflow

you might wanna try this:

$conda install -c conda-forge tensorflow

Make a Bash alias that takes a parameter?

For taking parameters, you should use functions!

However $@ get interpreted when creating the alias instead of during the execution of the alias and escaping the $ doesn’t work either. How do I solve this problem?

You need to use shell function instead of an alias to get rid of this problem. You can define foo as follows:

function foo() { /path/to/command "$@" ;}

OR

foo() { /path/to/command "$@" ;}

Finally, call your foo() using the following syntax:

foo arg1 arg2 argN

Make sure you add your foo() to ~/.bash_profile or ~/.zshrc file.

In your case, this will work

function trash() { mv $@ ~/.Trash; }

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

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

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

Are the days of passing const std::string & as a parameter over?

This highly depends on the compiler's implementation.

However, it also depends on what you use.

Lets consider next functions :

bool foo1( const std::string v )
{
  return v.empty();
}
bool foo2( const std::string & v )
{
  return v.empty();
}

These functions are implemented in a separate compilation unit in order to avoid inlining. Then :
1. If you pass a literal to these two functions, you will not see much difference in performances. In both cases, a string object has to be created
2. If you pass another std::string object, foo2 will outperform foo1, because foo1 will do a deep copy.

On my PC, using g++ 4.6.1, I got these results :

  • variable by reference: 1000000000 iterations -> time elapsed: 2.25912 sec
  • variable by value: 1000000000 iterations -> time elapsed: 27.2259 sec
  • literal by reference: 100000000 iterations -> time elapsed: 9.10319 sec
  • literal by value: 100000000 iterations -> time elapsed: 8.62659 sec

How to run html file on localhost?

You can try installing one of the following localhost softwares:

  1. xampp
  2. wamp
  3. ammps server
  4. laragon

There are many more such softwares but the best among them are the ones mentioned above. they also allow domain names (for example: example.com)

Verify External Script Is Loaded

@jasper's answer is totally correct but with modern browsers, a standard Javascript solution could be:

function isScriptLoaded(src)
{
    return document.querySelector('script[src="' + src + '"]') ? true : false;
}

How to calculate the sum of all columns of a 2D numpy array (efficiently)

Use the axis argument:

>> numpy.sum(a, axis=0)
  array([18, 22, 26])

Add a auto increment primary key to existing table in oracle

Snagged from Oracle OTN forums

Use alter table to add column, for example:

alter table tableName add(columnName NUMBER);

Then create a sequence:

CREATE SEQUENCE SEQ_ID
START WITH 1
INCREMENT BY 1
MAXVALUE 99999999
MINVALUE 1
NOCYCLE;

and, the use update to insert values in column like this

UPDATE tableName SET columnName = seq_test_id.NEXTVAL

How do I set up Android Studio to work completely offline?

For enabling Offline mode Android Studio Version Above 3.6, refer the following answer.

https://stackoverflow.com/a/64180290/4324288

Java - Using Accessor and Mutator methods

You need to remove the static from your accessor methods - these methods need to be instance methods and access the instance variables

public class IDCard {
    public String name, fileName;
    public int id;

    public IDCard(final String name, final String fileName, final int id) {
        this.name = name;
        this.fileName = fileName
        this.id = id;
    }

    public String getName() {
        return name;
    }
}

You can the create an IDCard and use the accessor like this:

final IDCard card = new IDCard();
card.getName();

Each time you call new a new instance of the IDCard will be created and it will have it's own copies of the 3 variables.

If you use the static keyword then those variables are common across every instance of IDCard.

A couple of things to bear in mind:

  1. don't add useless comments - they add code clutter and nothing else.
  2. conform to naming conventions, use lower case of variable names - name not Name.

List the queries running on SQL Server

in 2005 you can right click on a database, go to reports and there's a whole list of reports on transitions and locks etc...

How can I make a button have a rounded border in Swift?

I think this is the simple form

Button1.layer.cornerRadius = 10(Half of the length and width)
Button1.layer.borderWidth = 2

"message failed to fetch from registry" while trying to install any module

I had this issue with npm v1.1.4 (and node v0.6.12), which are the Ubuntu 12.04 repository versions.

It looks like that version of npm isn't supported any more, updating node (and npm with it) resolved the issue.

First, uninstall the outdated version (optional, but I think this fixed an issue I was having with global modules not being pathed in).

sudo apt-get purge nodejs npm

Then enable nodesource's repo and install:

curl -sL https://deb.nodesource.com/setup | sudo bash -
sudo apt-get install -y nodejs

Note - the previous advice was to use Chris Lea's repo, he's now migrated that to nodesource, see:

From: here

Undefined reference to sqrt (or other mathematical functions)

You may find that you have to link with the math libraries on whatever system you're using, something like:

gcc -o myprog myprog.c -L/path/to/libs -lm
                                       ^^^ - this bit here.

Including headers lets a compiler know about function declarations but it does not necessarily automatically link to the code required to perform that function.

Failing that, you'll need to show us your code, your compile command and the platform you're running on (operating system, compiler, etc).

The following code compiles and links fine:

#include <math.h>
int main (void) {
    int max = sqrt (9);
    return 0;
}

Just be aware that some compilation systems depend on the order in which libraries are given on the command line. By that, I mean they may process the libraries in sequence and only use them to satisfy unresolved symbols at that point in the sequence.

So, for example, given the commands:

gcc -o plugh plugh.o -lxyzzy
gcc -o plugh -lxyzzy plugh.o

and plugh.o requires something from the xyzzy library, the second may not work as you expect. At the point where you list the library, there are no unresolved symbols to satisfy.

And when the unresolved symbols from plugh.o do appear, it's too late.

What's the best way to identify hidden characters in the result of a query in SQL Server (Query Analyzer)?

They way I did it was by selecting all of the data

select * from myTable and then right-clicking on the result set and chose "Save results as..." a csv file.

Opening the csv file in Notepad++ I saw the LF characters not visible in SQL Server result set.

How to return an array from an AJAX call?

Have a look at json_encode() in PHP. You can get $.ajax to recognize this with the dataType: "json" parameter.

Uninstall Eclipse under OSX?

Eclipse has no impact on Mac OS beyond it directory, so there is no problem uninstalling.

I think that What you are facing is the result of Eclipse switching the plugin distribution system recently. There are now two redundant and not very compatible means of installing plugins. It's a complete mess. You may be better off (if possible) installing a more recent version of Eclipse (maybe even the 3.5 milestones) as they seem to be more stable in that regard.

Converting Numpy Array to OpenCV Array

This is what worked for me...

import cv2
import numpy as np

#Created an image (really an ndarray) with three channels 
new_image = np.ndarray((3, num_rows, num_cols), dtype=int)

#Did manipulations for my project where my array values went way over 255
#Eventually returned numbers to between 0 and 255

#Converted the datatype to np.uint8
new_image = new_image.astype(np.uint8)

#Separated the channels in my new image
new_image_red, new_image_green, new_image_blue = new_image

#Stacked the channels
new_rgb = np.dstack([new_image_red, new_image_green, new_image_blue])

#Displayed the image
cv2.imshow("WindowNameHere", new_rgbrgb)
cv2.waitKey(0)

Create a git patch from the uncommitted changes in the current working directory

I like:

git format-patch HEAD~<N>

where <N> is number of last commits to save as patches.

The details how to use the command are in the DOC

UPD
Here you can find how to apply them then.

UPD For those who did not get the idea of format-patch
Add alias:

git config --global alias.make-patch '!bash -c "cd ${GIT_PREFIX};git add .;git commit -m ''uncommited''; git format-patch HEAD~1; git reset HEAD~1"'

Then at any directory of your project repository run:

git make-patch

This command will create 0001-uncommited.patch at your current directory. Patch will contain all the changes and untracked files that are visible to next command:

git status .

How to download a branch with git?

you can use :

git clone <url> --branch <branch>

to clone/download only the contents of the branch.

This was helpful to me especially, since the contents of my branch were entirely different from the master branch (though this is not usually the case). Hence, the suggestions listed by others above didn't help me and I would end up getting a copy of the master even after I checked out the branch and did a git pull.

This command would directly give you the contents of the branch. It worked for me.

How can I recover the return value of a function passed to multiprocessing.Process?

Thought I'd simplify the simplest examples copied from above, working for me on Py3.6. Simplest is multiprocessing.Pool:

import multiprocessing
import time

def worker(x):
    time.sleep(1)
    return x

pool = multiprocessing.Pool()
print(pool.map(worker, range(10)))

You can set the number of processes in the pool with, e.g., Pool(processes=5). However it defaults to CPU count, so leave it blank for CPU-bound tasks. (I/O-bound tasks often suit threads anyway, as the threads are mostly waiting so can share a CPU core.) Pool also applies chunking optimization.

(Note that the worker method cannot be nested within a method. I initially defined my worker method inside the method that makes the call to pool.map, to keep it all self-contained, but then the processes couldn't import it, and threw "AttributeError: Can't pickle local object outer_method..inner_method". More here. It can be inside a class.)

(Appreciate the original question specified printing 'represent!' rather than time.sleep(), but without it I thought some code was running concurrently when it wasn't.)


Py3's ProcessPoolExecutor is also two lines (.map returns a generator so you need the list()):

from concurrent.futures import ProcessPoolExecutor
with ProcessPoolExecutor() as executor:
    print(list(executor.map(worker, range(10))))

With plain Processes:

import multiprocessing
import time

def worker(x, queue):
    time.sleep(1)
    queue.put(x)

queue = multiprocessing.SimpleQueue()
tasks = range(10)

for task in tasks:
    multiprocessing.Process(target=worker, args=(task, queue,)).start()

for _ in tasks:
    print(queue.get())

Use SimpleQueue if all you need is put and get. The first loop starts all the processes, before the second makes the blocking queue.get calls. I don't think there's any reason to call p.join() too.

Nexus 7 not visible over USB via "adb devices" from Windows 7 x64

I also have a Nexus 7 and Windows 7 64-bit and got ADB working by stumbling around in this thread and others about a month ago. Then it stopped working. The only thing odd I remember happening before was Windows installing some Bluetooth drivers as I started up (I do not have Bluetooth devices).

I floundered for a day this time. Now it is working again! The last thing I did was to use Device Manager to "disable" the device and reboot.

grabbing first row in a mysql query only

You can get the total number of rows containing a specific name using:

SELECT COUNT(*) FROM tbl_foo WHERE name = 'sarmen'

Given the count, you can now get the nth row using:

SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT (n - 1), 1

Where 1 <= n <= COUNT(*) from the first query.

Example:

getting the 3rd row

SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT 2, 1

Have a reloadData for a UITableView animate when changing

I can't comment on the top answer, but a swift implementation would be:

self.tableView.reloadSections([0], with: UITableViewRowAnimation.fade)

you could include as many sections as you want to update in the first argument for reloadSections.

Other animations available from the docs: https://developer.apple.com/reference/uikit/uitableviewrowanimation

fade The inserted or deleted row or rows fade into or out of the table view.

right The inserted row or rows slide in from the right; the deleted row or rows slide out to the right.

left The inserted row or rows slide in from the left; the deleted row or rows slide out to the left.

top The inserted row or rows slide in from the top; the deleted row or rows slide out toward the top.

bottom The inserted row or rows slide in from the bottom; the deleted row or rows slide out toward the bottom.

case none The inserted or deleted rows use the default animations.

middle The table view attempts to keep the old and new cells centered in the space they did or will occupy. Available in iPhone 3.2.

automatic The table view chooses an appropriate animation style for you. (Introduced in iOS 5.0.)

nginx upload client_max_body_size issue

Does your upload die at the very end? 99% before crashing? Client body and buffers are key because nginx must buffer incoming data. The body configs (data of the request body) specify how nginx handles the bulk flow of binary data from multi-part-form clients into your app's logic.

The clean setting frees up memory and consumption limits by instructing nginx to store incoming buffer in a file and then clean this file later from disk by deleting it.

Set body_in_file_only to clean and adjust buffers for the client_max_body_size. The original question's config already had sendfile on, increase timeouts too. I use the settings below to fix this, appropriate across your local config, server, & http contexts.

client_body_in_file_only clean;
client_body_buffer_size 32K;

client_max_body_size 300M;

sendfile on;
send_timeout 300s;

Switch statement for greater-than/less-than

This is another option:

     switch (true) {
         case (value > 100):
             //do stuff
             break;
         case (value <= 100)&&(value > 75):
             //do stuff
             break;
         case (value < 50):
            //do stuff
             break;
     }

Swift - Split string over multiple lines

Adding to @Connor answer, there needs to be \n also. Here is revised code:

var text:String = "This is some text \n" +
                  "over multiple lines"

How to filter rows containing a string pattern from a Pandas dataframe

In [3]: df[df['ids'].str.contains("ball")]
Out[3]:
     ids  vals
0  aball     1
1  bball     2
3  fball     4

How to declare or mark a Java method as deprecated?

There are two things you can do:

  1. Add the @Deprecated annotation to the method, and
  2. Add a @deprecated tag to the javadoc of the method

You should do both!

Quoting the java documentation on this subject:

Starting with J2SE 5.0, you deprecate a class, method, or field by using the @Deprecated annotation. Additionally, you can use the @deprecated Javadoc tag tell developers what to use instead.

Using the annotation causes the Java compiler to generate warnings when the deprecated class, method, or field is used. The compiler suppresses deprecation warnings if a deprecated compilation unit uses a deprecated class, method, or field. This enables you to build legacy APIs without generating warnings.

You are strongly recommended to use the Javadoc @deprecated tag with appropriate comments explaining how to use the new API. This ensures developers will have a workable migration path from the old API to the new API

Difference between DTO, VO, POJO, JavaBeans?

JavaBeans

A JavaBean is a class that follows the JavaBeans conventions as defined by Sun. Wikipedia has a pretty good summary of what JavaBeans are:

JavaBeans are reusable software components for Java that can be manipulated visually in a builder tool. Practically, they are classes written in the Java programming language conforming to a particular convention. They are used to encapsulate many objects into a single object (the bean), so that they can be passed around as a single bean object instead of as multiple individual objects. A JavaBean is a Java Object that is serializable, has a nullary constructor, and allows access to properties using getter and setter methods.

In order to function as a JavaBean class, an object class must obey certain conventions about method naming, construction, and behavior. These conventions make it possible to have tools that can use, reuse, replace, and connect JavaBeans.

The required conventions are:

  • The class must have a public default constructor. This allows easy instantiation within editing and activation frameworks.
  • The class properties must be accessible using get, set, and other methods (so-called accessor methods and mutator methods), following a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties.
  • The class should be serializable. This allows applications and frameworks to reliably save, store, and restore the bean's state in a fashion that is independent of the VM and platform.

Because these requirements are largely expressed as conventions rather than by implementing interfaces, some developers view JavaBeans as Plain Old Java Objects that follow specific naming conventions.

POJO

A Plain Old Java Object or POJO is a term initially introduced to designate a simple lightweight Java object, not implementing any javax.ejb interface, as opposed to heavyweight EJB 2.x (especially Entity Beans, Stateless Session Beans are not that bad IMO). Today, the term is used for any simple object with no extra stuff. Again, Wikipedia does a good job at defining POJO:

POJO is an acronym for Plain Old Java Object. The name is used to emphasize that the object in question is an ordinary Java Object, not a special object, and in particular not an Enterprise JavaBean (especially before EJB 3). The term was coined by Martin Fowler, Rebecca Parsons and Josh MacKenzie in September 2000:

"We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it's caught on very nicely."

The term continues the pattern of older terms for technologies that do not use fancy new features, such as POTS (Plain Old Telephone Service) in telephony, and PODS (Plain Old Data Structures) that are defined in C++ but use only C language features, and POD (Plain Old Documentation) in Perl.

The term has most likely gained widespread acceptance because of the need for a common and easily understood term that contrasts with complicated object frameworks. A JavaBean is a POJO that is serializable, has a no-argument constructor, and allows access to properties using getter and setter methods. An Enterprise JavaBean is not a single class but an entire component model (again, EJB 3 reduces the complexity of Enterprise JavaBeans).

As designs using POJOs have become more commonly-used, systems have arisen that give POJOs some of the functionality used in frameworks and more choice about which areas of functionality are actually needed. Hibernate and Spring are examples.

Value Object

A Value Object or VO is an object such as java.lang.Integer that hold values (hence value objects). For a more formal definition, I often refer to Martin Fowler's description of Value Object:

In Patterns of Enterprise Application Architecture I described Value Object as a small object such as a Money or date range object. Their key property is that they follow value semantics rather than reference semantics.

You can usually tell them because their notion of equality isn't based on identity, instead two value objects are equal if all their fields are equal. Although all fields are equal, you don't need to compare all fields if a subset is unique - for example currency codes for currency objects are enough to test equality.

A general heuristic is that value objects should be entirely immutable. If you want to change a value object you should replace the object with a new one and not be allowed to update the values of the value object itself - updatable value objects lead to aliasing problems.

Early J2EE literature used the term value object to describe a different notion, what I call a Data Transfer Object. They have since changed their usage and use the term Transfer Object instead.

You can find some more good material on value objects on the wiki and by Dirk Riehle.

Data Transfer Object

Data Transfer Object or DTO is a (anti) pattern introduced with EJB. Instead of performing many remote calls on EJBs, the idea was to encapsulate data in a value object that could be transfered over the network: a Data Transfer Object. Wikipedia has a decent definition of Data Transfer Object:

Data transfer object (DTO), formerly known as value objects or VO, is a design pattern used to transfer data between software application subsystems. DTOs are often used in conjunction with data access objects to retrieve data from a database.

The difference between data transfer objects and business objects or data access objects is that a DTO does not have any behaviour except for storage and retrieval of its own data (accessors and mutators).

In a traditional EJB architecture, DTOs serve dual purposes: first, they work around the problem that entity beans are not serializable; second, they implicitly define an assembly phase where all data to be used by the view is fetched and marshalled into the DTOs before returning control to the presentation tier.


So, for many people, DTOs and VOs are the same thing (but Fowler uses VOs to mean something else as we saw). Most of time, they follow the JavaBeans conventions and are thus JavaBeans too. And all are POJOs.

ActiveMQ connection refused

I encountered a similar problem when I was using the below to obtain connection factory ConnectionFactory factory = new
ActiveMQConnectionFactory("admin","admin","tcp://:61616");

Its resolved when I changed it to the below

ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://:61616");

The below then showed that my Q size was increasing.. http://:8161/admin/queues.jsp

Serialize and Deserialize Json and Json Array in Unity

you have to add [System.Serializable] to PlayerItem class ,like this:

using System;
[System.Serializable]
public class PlayerItem   {
    public string playerId;
    public string playerLoc;
    public string playerNick;
}

How to see what privileges are granted to schema of another user

Use example with from the post of Szilágyi Donát.

I use two querys, one to know what roles I have, excluding connect grant:

SELECT * FROM USER_ROLE_PRIVS WHERE GRANTED_ROLE != 'CONNECT'; -- Roles of the actual Oracle Schema

Know I like to find what privileges/roles my schema/user have; examples of my roles ROLE_VIEW_PAYMENTS & ROLE_OPS_CUSTOMERS. But to find the tables/objecst of an specific role I used:

SELECT * FROM ALL_TAB_PRIVS WHERE GRANTEE='ROLE_OPS_CUSTOMERS'; -- Objects granted at role.

The owner schema for this example could be PRD_CUSTOMERS_OWNER (or the role/schema inself).

Regards.

calling Jquery function from javascript

var jqueryFunction;

$().ready(function(){
    //jQuery function
    jqueryFunction = function( _msg )
    {
        alert( _msg );
    }
})

//javascript function
function jsFunction()
{
    //Invoke jQuery Function
    jqueryFunction("Call from js to jQuery");
}

http://www.designscripting.com/2012/08/call-jquery-function-from-javascript/

Javascript/DOM: How to remove all events of a DOM object?

You can add a helper function that clears event listener for example

function clearEventListener(element) {
 const clonedElement = element.cloneNode(true);
element.replaceWith(clonedElement);
return clonedElement;
}

just pass in the element to the function and that's it...

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

There's a far more simpler solution to tackle this.

The reason why you get ValueError: Index contains duplicate entries, cannot reshape is because, once you unstack "Location", then the remaining index columns "id" and "date" combinations are no longer unique.

You can avoid this by retaining the default index column (row #) and while setting the index using "id", "date" and "location", add it in "append" mode instead of the default overwrite mode.

So use,

e.set_index(['id', 'date', 'location'], append=True)

Once this is done, your index columns will still have the default index along with the set indexes. And unstack will work.

Let me know how it works out.

POST data in JSON format

Another example is available here:

Sending a JSON to server and retrieving a JSON in return, without JQuery

Which is the same as jans answer, but also checks the servers response by setting a onreadystatechange callback on the XMLHttpRequest.

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)

To quote the most relevant bits:

[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.

The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”

Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.

The full post explains this in more detail. At RTM, the MSDN docs on this should be better.

ActiveRecord: size vs count

Sometimes size "picks the wrong one" and returns a hash (which is what count would do)

In that case, use length to get an integer instead of hash.

INSERT INTO TABLE from comma separated varchar-list

Since there's no way to just pass this "comma-separated list of varchars", I assume some other system is generating them. If you can modify your generator slightly, it should be workable. Rather than separating by commas, you separate by union all select, and need to prepend a select also to the list. Finally, you need to provide aliases for the table and column in you subselect:

Create Table #IMEIS(
    imei varchar(15)
)
INSERT INTO #IMEIS(imei)
    SELECT * FROM (select '012251000362843' union all select '012251001084784' union all select '012251001168744' union all
                   select '012273007269862' union all select '012291000080227' union all select '012291000383084' union all
                   select '012291000448515') t(Col)
SELECT * from #IMEIS
DROP TABLE #IMEIS;

But noting your comment to another answer, about having 5000 entries to add. I believe the 256 tables per select limitation may kick in with the above "union all" pattern, so you'll still need to do some splitting of these values into separate statements.

How do I create a folder in VB if it doesn't exist?

Just do this:

        Dim sPath As String = "Folder path here"
    If (My.Computer.FileSystem.DirectoryExists(sPath) = False) Then
        My.Computer.FileSystem.CreateDirectory(sPath + "/<Folder name>")
    Else
        'Something else happens, because the folder exists
    End If

I declared the folder path as a String (sPath) so that way if you do use it multiple times it can be changed easily but also it can be changed through the program itself.

Hope it helps!

-nfell2009

Difference between frontend, backend, and middleware in web development

Here is one breakdown:

Front-end tier -> User Interface layer usually consisting of a mix of HTML, Javascript, CSS, Flash, and various server-side code like ASP.Net, classic ASP, PHP, etc. Think of this as being closest to the user in terms of code.

Middleware, middle-tier -> One tier back, generally referred to as the "plumbing" part of a system. Java and C# are common languages for writing this part that could be viewed as the glue between the UI and the data and can be webservices or WCF components or other SOA components possibly.

Back-end tier -> Databases and other data stores are generally at this level. Oracle, MS-SQL, MySQL, SAP, and various off-the-shelf pieces of software come to mind for this piece of software that is the final processing of the data.

Overlap can exist between any of these as you could have everything poured into one layer like an ASP.Net website that uses the built-in AJAX functionality that generates Javascript while the code behind may contain database commands making the code behind contain both middle and back-end tiers. Alternatively, one could use VBScript to act as all the layers using ADO objects and merging all three tiers into one.

Similarly, taking middleware and either front or back-end can be combined in some cases.

Bottlenecks generally have a few different levels to them:

1) Database or back-end processing -> This can vary from payroll or sales or other tasks where the throughput to the database is bogging things down.

2) Middleware bottlenecks -> This would be where some web service may be hitting capacity but the front and back ends have bandwidth to handle more traffic. Alternatively, there may be some server that is part of a system that isn't quite the UI part or the raw data that can be a bottleneck using something like Biztalk or MSMQ.

3) Front-end bottlenecks -> This could client or server-side issues. For example, if you took a low-end PC and had it load a web page that consisted of a lot of data being downloaded, the client could be where the bottleneck is. Similarly, the server could be queuing up requests if it is getting hammered with requests like what Amazon.com or other high-traffic websites may get at times.

Some of this is subject to interpretation, so it isn't perfect by any means and YMMV.


EDIT: Something to consider is that some systems can have multiple front-ends or back-ends. For example, a content management system will likely have a way for site visitors to view the content that is a front-end but what about how content editors are able to change the data on the site? The ability to pull up this data could be seen as front-end since it is a UI component or it could be seen as a back-end since it is used by internal users rather than the general public viewing the site. Thus, there is something to be said for context here.

How to display HTML in TextView?

If you are trying to show HTML from a string resource id, the formatting may not show up on screen. If that is happening to you, try using CDATA tags instead:

strings.xml:
<string name="sample_string"><![CDATA[<h2>Title</h2><br><p>Description here</p>]]></string>

...

MainActivity.java:
text.setText(Html.fromHtml(getString(R.string.sample_string));

See this post for further details.

How to share data between different threads In C# using AOP?

When you start a thread you are executing a method of some chosen class. All attributes of that class are visible.

  Worker myWorker = new Worker( /* arguments */ );

  Thread myThread = new Thread(new ThreadStart(myWorker.doWork));

  myThread.Start();

Your thread is now in the doWork() method and can see any atrributes of myWorker, which may themselves be other objects. Now you just need to be careful to deal with the cases of having several threads all hitting those attributes at the same time.

Insert PHP code In WordPress Page and Post

Description:

there are 3 steps to run PHP code inside post or page.

  1. In functions.php file (in your theme) add new function

  2. In functions.php file (in your theme) register new shortcode which call your function:

add_shortcode( 'SHORCODE_NAME', 'FUNCTION_NAME' );
  1. use your new shortcode

Example #1: just display text.

In functions:

function simple_function_1() {
    return "Hello World!";
}

add_shortcode( 'own_shortcode1', 'simple_function_1' );

In post/page:

[own_shortcode1]

Effect:

Hello World!

Example #2: use for loop.

In functions:

function simple_function_2() {
    $output = "";
    
    for ($number = 1; $number < 10; $number++) {    
        // Append numbers to the string
        $output .= "$number<br>";
    } 
    
    return "$output";
}

add_shortcode( 'own_shortcode2', 'simple_function_2' );

In post/page:

[own_shortcode2]

Effect:

1
2
3
4
5
6
7
8
9

Example #3: use shortcode with arguments

In functions:

function simple_function_3($name) {
    return "Hello $name";
}

add_shortcode( 'own_shortcode3', 'simple_function_3' );

In post/page:

[own_shortcode3 name="John"]

Effect:

Hello John

Example #3 - without passing arguments

In post/page:

[own_shortcode3]

Effect:

Hello 

SQLite table constraint - unique on multiple columns

Be careful how you define the table for you will get different results on insert. Consider the following



CREATE TABLE IF NOT EXISTS t1 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT);
INSERT INTO t1 (a, b) VALUES
    ('Alice', 'Some title'),
    ('Bob', 'Palindromic guy'),
    ('Charles', 'chucky cheese'),
    ('Alice', 'Some other title') 
    ON CONFLICT(a) DO UPDATE SET b=excluded.b;
CREATE TABLE IF NOT EXISTS t2 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT, UNIQUE(a) ON CONFLICT REPLACE);
INSERT INTO t2 (a, b) VALUES
    ('Alice', 'Some title'),
    ('Bob', 'Palindromic guy'),
    ('Charles', 'chucky cheese'),
    ('Alice', 'Some other title');

$ sqlite3 test.sqlite
SQLite version 3.28.0 2019-04-16 19:49:53
Enter ".help" for usage hints.
sqlite> CREATE TABLE IF NOT EXISTS t1 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT);
sqlite> INSERT INTO t1 (a, b) VALUES
   ...>     ('Alice', 'Some title'),
   ...>     ('Bob', 'Palindromic guy'),
   ...>     ('Charles', 'chucky cheese'),
   ...>     ('Alice', 'Some other title') 
   ...>     ON CONFLICT(a) DO UPDATE SET b=excluded.b;
sqlite> CREATE TABLE IF NOT EXISTS t2 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT, UNIQUE(a) ON CONFLICT REPLACE);
sqlite> INSERT INTO t2 (a, b) VALUES
   ...>     ('Alice', 'Some title'),
   ...>     ('Bob', 'Palindromic guy'),
   ...>     ('Charles', 'chucky cheese'),
   ...>     ('Alice', 'Some other title');
sqlite> .mode col
sqlite> .headers on
sqlite> select * from t1;
id          a           b               
----------  ----------  ----------------
1           Alice       Some other title
2           Bob         Palindromic guy 
3           Charles     chucky cheese   
sqlite> select * from t2;
id          a           b              
----------  ----------  ---------------
2           Bob         Palindromic guy
3           Charles     chucky cheese  
4           Alice       Some other titl
sqlite> 

While the insert/update effect is the same, the id changes based on the table definition type (see the second table where 'Alice' now has id = 4; the first table is doing more of what I expect it to do, keep the PRIMARY KEY the same). Be aware of this effect.

How to add elements of a string array to a string array list?

You already have built-in method for that: -

List<String> species = Arrays.asList(speciesArr);

NOTE: - You should use List<String> species not ArrayList<String> species.

Arrays.asList returns a different ArrayList -> java.util.Arrays.ArrayList which cannot be typecasted to java.util.ArrayList.

Then you would have to use addAll method, which is not so good. So just use List<String>

NOTE: - The list returned by Arrays.asList is a fixed size list. If you want to add something to the list, you would need to create another list, and use addAll to add elements to it. So, then you would better go with the 2nd way as below: -

    String[] arr = new String[1];
    arr[0] = "rohit";
    List<String> newList = Arrays.asList(arr);

    // Will throw `UnsupportedOperationException
    // newList.add("jain"); // Can't do this.

    ArrayList<String> updatableList = new ArrayList<String>();

    updatableList.addAll(newList); 

    updatableList.add("jain"); // OK this is fine. 

    System.out.println(newList);       // Prints [rohit]
    System.out.println(updatableList); //Prints [rohit, jain]

'Property does not exist on type 'never'

Because you are assigning instance to null. The compiler infers that it can never be anything other than null. So it assumes that the else block should never be executed so instance is typed as never in the else block.

Now if you don't declare it as the literal value null, and get it by any other means (ex: let instance: Foo | null = getFoo();), you will see that instance will be null inside the if block and Foo inside the else block.

Never type documentation: https://www.typescriptlang.org/docs/handbook/basic-types.html#never

Edit:

The issue in the updated example is actually an open issue with the compiler. See:

https://github.com/Microsoft/TypeScript/issues/11498 https://github.com/Microsoft/TypeScript/issues/12176

How to get share counts using graph API

You can use the https://graph.facebook.com/v3.0/{Place_your_Page_ID here}/feed?fields=id,shares,share_count&access_token={Place_your_access_token_here} to get the shares count.

How to create a thread?

The following ways work.

// The old way of using ParameterizedThreadStart. This requires a
// method which takes ONE object as the parameter so you need to
// encapsulate the parameters inside one object.
Thread t = new Thread(new ParameterizedThreadStart(StartupA));
t.Start(new MyThreadParams(path, port));

// You can also use an anonymous delegate to do this.
Thread t2 = new Thread(delegate()
{
    StartupB(port, path);
});
t2.Start();

// Or lambda expressions if you are using C# 3.0
Thread t3 = new Thread(() => StartupB(port, path));
t3.Start();

The Startup methods have following signature for these examples.

public void StartupA(object parameters);

public void StartupB(int port, string path);

MVC Calling a view from a different controller

It is explained pretty well here: Display a view from another controller in ASP.NET MVC

To quote @Womp:
By default, ASP.NET MVC checks first in \Views\[Controller_Dir]\, but after that, if it doesn't find the view, it checks in \Views\Shared.

ASP MVC's idea is "convention over configuration" which means moving the view to the shared folder is the way to go in such cases.

C++ trying to swap values in a vector

after passing the vector by reference

swap(vector[position],vector[otherPosition]);

will produce the expected result.

How to connect android emulator to the internet

I think some of the answers may have addressed this, however obliquely, but here's what worked for me.

Assuming your problem is occurring when you're on a wireless network and you have a LAN card installed, the issue is that the emulator tries to obtain its DNS settings from that LAN card. Not a problem when you're connected via that LAN, but utterly useless if you're on a wireless connection. I noticed this when I was on my laptop.

So, how to fix? Simple: Disable your LAN card. Really. Just go to your Network connections, find your LAN card, right click it and choose disable. Now try your emulator. If you're like me, it suddenly ... works!

String index out of range: 4

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

Binning column with python pandas

Using numba module for speed up.

On big datasets (500k >) pd.cut can be quite slow for binning data.

I wrote my own function in numba with just in time compilation, which is roughly 16x faster:

from numba import njit

@njit
def cut(arr):
    bins = np.empty(arr.shape[0])
    for idx, x in enumerate(arr):
        if (x >= 0) & (x < 1):
            bins[idx] = 1
        elif (x >= 1) & (x < 5):
            bins[idx] = 2
        elif (x >= 5) & (x < 10):
            bins[idx] = 3
        elif (x >= 10) & (x < 25):
            bins[idx] = 4
        elif (x >= 25) & (x < 50):
            bins[idx] = 5
        elif (x >= 50) & (x < 100):
            bins[idx] = 6
        else:
            bins[idx] = 7

    return bins
cut(df['percentage'].to_numpy())

# array([5., 5., 7., 5.])

Optional: you can also map it to bins as strings:

a = cut(df['percentage'].to_numpy())

conversion_dict = {1: 'bin1',
                   2: 'bin2',
                   3: 'bin3',
                   4: 'bin4',
                   5: 'bin5',
                   6: 'bin6',
                   7: 'bin7'}

bins = list(map(conversion_dict.get, a))

# ['bin5', 'bin5', 'bin7', 'bin5']

Speed comparison:

# create dataframe of 8 million rows for testing
dfbig = pd.concat([df]*2000000, ignore_index=True)

dfbig.shape

# (8000000, 1)
%%timeit
cut(dfbig['percentage'].to_numpy())

# 38 ms ± 616 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
pd.cut(dfbig['percentage'], bins=bins, labels=labels)

# 215 ms ± 9.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

how to add values to an array of objects dynamically in javascript?

In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently

data = [...data, {"label": 2, "value": 13}]

Examples

_x000D_
_x000D_
var data = [_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
    ];_x000D_
    _x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

For your case (i know it was in 2011), we can do it with map() & forEach() like below

_x000D_
_x000D_
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
   data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
 ({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
_x000D_
_x000D_

Should I write script in the body or the head of the html?

Head, or before closure of body tag. When DOM loads JS is then executed, that is exactly what jQuery document.ready does.

How to stop the task scheduled in java.util.Timer class

Terminate the Timer once after awake at a specific time in milliseconds.

Timer t = new Timer();
t.schedule(new TimerTask() {
            @Override
             public void run() {
             System.out.println(" Run spcific task at given time.");
             t.cancel();
             }
 }, 10000);

How to automatically select all text on focus in WPF TextBox?

The simplist and perfect solution, is to use a timer to select all text 20ms after textbox got focus:

Dim WithEvents Timer As New DispatcherTimer()

Set the interval: Timer.Interval = TimeSpan.FromMilliseconds(20)

respond to events (I am inheriting the TextBox control here, so I am overriding its events:

Protected Overrides Sub OnGotFocus(e As RoutedEventArgs)
        Timer.Start()
        MyBase.OnGotFocus(e)
    End Sub


    Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
        Timer.Stop()
        Me.SelectAll()
    End Sub

And that is all!

Filling a List with all enum values in Java

This is a bit more readable:

Object[] allValues = all.getDeclaringClass().getEnumConstants();

python max function using 'key' and lambda expression

Strongly simplified version of max:

def max(items, key=lambda x: x):
    current = item[0]
    for item in items:
        if key(item) > key(current):
            current = item
    return current

Regarding lambda:

>>> ident = lambda x: x
>>> ident(3)
3
>>> ident(5)
5

>>> times_two = lambda x: 2*x
>>> times_two(2)
4

How can you find out which process is listening on a TCP or UDP port on Windows?

Using PowerShell... ...this would be your friend (replace 8080 with your port number):

 netstat -abno | Select-String -Context 0,1 -Pattern 8080

Sample output

>   TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING         2920
   [tnslsnr.exe]
>   TCP    [::]:8080              [::]:0                 LISTENING         2920
   [tnslsnr.exe]

So in this example tnslsnr.exe (OracleXE database) is listening on port 8080.

Quick explanation

  • Select-String is used to filter the lengthy output of netstat for the relevant lines.
  • -Pattern tests each line against a regular expression.
  • -Context 0,1 will output 0 leading lines and 1 trailing line for each pattern match.

"query function not defined for Select2 undefined error"

For me this issue boiled down to setting the correct data-ui-select2 attribute:

<input type="text" data-ui-select2="select2Options.projectManagers" placeholder="Project Manager" ng-model="selectedProjectManager">


$scope.projectManagers = { 
  data: []  //Must have data property 
}

$scope.selectedProjectManager = {};

If I take off the data property on $scope.projectManagers I get this error.

How to compute the similarity between two text documents?

Generally a cosine similarity between two documents is used as a similarity measure of documents. In Java, you can use Lucene (if your collection is pretty large) or LingPipe to do this. The basic concept would be to count the terms in every document and calculate the dot product of the term vectors. The libraries do provide several improvements over this general approach, e.g. using inverse document frequencies and calculating tf-idf vectors. If you are looking to do something copmlex, LingPipe also provides methods to calculate LSA similarity between documents which gives better results than cosine similarity. For Python, you can use NLTK.

How to parse JSON using Node.js?

As mentioned in the above answers, We can use JSON.parse() to parse the strings to JSON But before parsing, be sure to parse the correct data or else it might bring your whole application down

it is safe to use it like this

let parsedObj = {}
try {
    parsedObj = JSON.parse(data);
} catch(e) {
    console.log("Cannot parse because data is not is proper json format")
}

How to drop columns by name in a data frame

df2 <- df[!names(df) %in% c("c1", "c2")]

check if a file is open in Python

You could use with open("path") as file: so that it automatically closes, else if it's open in another process you can maybe try as in Tims example you should use except IOError to not ignore any other problem with your code :)

try:
   with open("path", "r") as file: # or just open
       # Code here
except IOError:
   # raise error or print

javascript cell number validation

<script>
    function validate() {
        var phone=document.getElementById("phone").value;
        if(isNaN(phone))
        {
            alert("please enter digits only");
        }

        else if(phone.length!=10)
        {
            alert("invalid mobile number");
        }
        else
        {
            confirm("hello your mobile number is" +" "+phone);
        }
</script>

Android - How to achieve setOnClickListener in Kotlin?

You use like that onclickListener in kotlin

val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener {  
...
}

Get a Div Value in JQuery

myDivObj = document.getElementById("myDiv");
if ( myDivObj ) {
   alert ( myDivObj.innerHTML ); 
}else{
   alert ( "Alien Found" );
}

Above code will show the innerHTML, i.e if you have used html tags inside div then it will show even those too. probably this is not what you expected. So another solution is to use: innerText / textContent property [ thanx to bobince, see his comment ]

function showDivText(){
            divObj = document.getElementById("myDiv");
            if ( divObj ){
                if ( divObj.textContent ){ // FF
                    alert ( divObj.textContent );
                }else{  // IE           
                    alert ( divObj.innerText );  //alert ( divObj.innerHTML );
                } 
            }  
        }

Calling Python in Java?

Hey I thought I would enter my answer to this even though its late. I think there are some important things to consider first with how strong you wish to have the linking between java and python.

Firstly Do you only want to call functions or do you actually want python code to change the data in your java objects? This is very important. If you only want to call some python code with or without arguments, then that is not very difficult. If your arguments are primitives it makes it even more easy. However if you want to have java class implement member functions in python, which change the data of the java object, then this is not so easy or straight forward.

Secondly are we talking cpython or will jython do? I would say cpython is where its at! I would advocate this is why python is so kool! Having such high abstractions however access to c,c++ when needed. Imagine if you could have that in java. This question is not even worth asking if jython is ok because then it is easy anyway.

So I have played with the following methods, and listed them from easy to difficult:

Java to Jython

Advantages: Trivially easy. Have actual references to java objects

Disadvantages: No CPython, Extremely Slow!

Jython from java is so easy, and if this is really enough then great. However it is very slow and no cpython! Is life worth living without cpython I don't think so! You can easily have python code implementing your member functions for you java objects.

Java to Jython to CPython via Pyro

Pyro is the remote object module for python. You have some object on a cpython interpreter, and you can send it objects which are transferred via serialization and it can also return objects via this method. Note that if you send a serialized python object from jython and then call some functions which change the data in its members, then you will not see those changes in java. You just need to remember to send back the data which you want from pyro. This I believe is the easiest way to get to cpython! You do not need any jni or jna or swig or .... You don't need to know any c, or c++. kool huh?

Advantages: Access to cpython, not as difficult as following methods

Disadvantages: Cannot change the member data of java objects directly from python. Is somewhat indirect, (jython is middle man).

Java to C/C++ via JNI/JNA/SWIG to Python via Embedded interpreter (maybe using BOOST Libraries?)

OMG this method is not for the faint of heart. And I can tell you it has taken me very long to achieve this in with a decent method. Main reason you would want to do this is so that you can run cpython code which as full rein over you java object. There are major major things to consider before deciding to try and bread java (which is like a chimp) with python (which is like a horse). Firstly if you crash the interpreter that's lights out for you program! And don't get me started on concurrency issues! In addition, there is allot allot of boiler, I believe I have found the best configuration to minimize this boiler but still it is allot! So how to go about this: Consider that C++ is your middle man, your objects are actually c++ objects! Good that you know that now. Just write your object as if your program as in cpp not java, with the data you want to access from both worlds. Then you can use the wrapper generator called swig (http://www.swig.org/Doc1.3/Java.html) to make this accessible to java and compile a dll which you call System.load(dll name here) in java. Get this working first, then move on to the hard part! To get to python you need to embed an interpreter. Firstly I suggest doing some hello interpreter programs or this tutorial Embedding python in C/C. Once you have that working, its time to make the horse and the monkey dance! You can send you c++ object to python via [boost][3] . I know I have not given you the fish, merely told you where to find the fish. Some pointers to note for this when compiling.

When you compile boost you will need to compile a shared library. And you need to include and link to the stuff you need from jdk, ie jawt.lib, jvm.lib, (you will also need the client jvm.dll in your path when launching the application) As well as the python27.lib or whatever and the boost_python-vc100-mt-1_55.lib. Then include Python/include, jdk/include, boost and only use shared libraries (dlls) otherwise boost has a teary. And yeah full on I know. There are so many ways in which this can go sour. So make sure you get each thing done block by block. Then put them together.

How do I find duplicates across multiple columns?

You have to self join stuff and match name and city. Then group by count.

select 
   s.id, s.name, s.city 
from stuff s join stuff p ON (
   s.name = p.city OR s.city = p.name
)
group by s.name having count(s.name) > 1

Regular Expressions: Search in list

To do so without compiling the Regex first, use a lambda function - for example:

from re import match

values = ['123', '234', 'foobar']
filtered_values = list(filter(lambda v: match('^\d+$', v), values))

print(filtered_values)

Returns:

['123', '234']

filter() just takes a callable as it's first argument, and returns a list where that callable returned a 'truthy' value.

Which is better, return value or out parameter?

I would prefer the following instead of either of those in this simple example.

public int Value
{
    get;
    private set;
}

But, they are all very much the same. Usually, one would only use 'out' if they need to pass multiple values back from the method. If you want to send a value in and out of the method, one would choose 'ref'. My method is best, if you are only returning a value, but if you want to pass a parameter and get a value back one would likely choose your first choice.

What is the maximum number of characters that nvarchar(MAX) will hold?

2^31-1 bytes. So, a little less than 2^31-1 characters for varchar(max) and half that for nvarchar(max).

nchar and nvarchar

error: strcpy was not declared in this scope

This error sometimes occurs in a situation like this:

#ifndef NAN
#include <stdlib.h>
#define NAN (strtod("NAN",NULL))
#endif

static void init_random(uint32_t initseed=0)
{
    if (initseed==0)
    {
        struct timeval tv;
        gettimeofday(&tv, NULL);
        seed=(uint32_t) (4223517*getpid()*tv.tv_sec*tv.tv_usec);
    }
    else
        seed=initseed;
#if !defined(CYGWIN) && !defined(__INTERIX)
    //seed=42
    //SG_SPRINT("initializing random number generator with %d (seed size %d)\n", seed, RNG_SEED_SIZE)
    initstate(seed, CMath::rand_state, RNG_SEED_SIZE);
#endif
}

If the following code lines not run in the run-time:

#ifndef NAN
#include <stdlib.h>
#define NAN (strtod("NAN",NULL))
#endif

you will face with an error in your code like something as follows; because initstate is placed in the stdlib.h file and it's not included:

In file included from ../../shogun/features/SubsetStack.h:14:0, 
                 from ../../shogun/features/Features.h:21, 
                 from ../../shogun/ui/SGInterface.h:7, 
                 from MatlabInterface.h:15, 
                 from matlabInterface.cpp:7: 
../../shogun/mathematics/Math.h: In static member function 'static void shogun::CMath::init_random(uint32_t)': 
../../shogun/mathematics/Math.h:459:52: error: 'initstate' was not declared in this scope

How do I create an average from a Ruby array?

I was hoping for Math.average(values), but no such luck.

values = [0,4,8,2,5,0,2,6]
average = values.sum / values.size.to_f

How do you concatenate Lists in C#?

I know this is old but I came upon this post quickly thinking Concat would be my answer. Union worked great for me. Note, it returns only unique values but knowing that I was getting unique values anyway this solution worked for me.

namespace TestProject
{
    public partial class Form1 :Form
    {
        public Form1()
        {
            InitializeComponent();

            List<string> FirstList = new List<string>();
            FirstList.Add("1234");
            FirstList.Add("4567");

            // In my code, I know I would not have this here but I put it in as a demonstration that it will not be in the secondList twice
            FirstList.Add("Three");  

            List<string> secondList = GetList(FirstList);            
            foreach (string item in secondList)
                Console.WriteLine(item);
        }

        private List<String> GetList(List<string> SortBy)
        {
            List<string> list = new List<string>();
            list.Add("One");
            list.Add("Two");
            list.Add("Three");

            list = list.Union(SortBy).ToList();

            return list;
        }
    }
}

The output is:

One
Two
Three
1234
4567

Highlight all occurrence of a selected word?

to highlight word without moving cursor, plop

" highlight reg. ex. in @/ register
set hlsearch
" remap `*`/`#` to search forwards/backwards (resp.)
" w/o moving cursor
nnoremap <silent> * :execute "normal! *N"<cr>
nnoremap <silent> # :execute "normal! #n"<cr>

into your vimrc.

What's nice about this is g* and g# will still work like "normal" * and #.


To set hlsearch off, you can use "short-form" (unless you have another function that starts with "noh" in command mode): :noh. Or you can use long version: :nohlsearch

For extreme convenience (I find myself toggling hlsearch maybe 20 times per day), you can map something to toggle hlsearch like so:

" search highlight toggle
nnoremap <silent> <leader>st :set hlsearch!<cr>

.:. if your <leader> is \ (it is by default), you can press \st (quickly) in normal mode to toggle hlsearch.

Or maybe you just want to have :noh mapped:

" search clear
nnoremap <silent> <leader>sc :nohlsearch<cr>

The above simply runs :nohlsearch so (unlike :set hlsearch!) it will still highlight word next time you press * or # in normal mode.

cheers

Open application after clicking on Notification

public static void notifyUser(Activity activity, String header,
        String message) {
    NotificationManager notificationManager = (NotificationManager) activity
            .getSystemService(Activity.NOTIFICATION_SERVICE);
    Intent notificationIntent = new Intent(
            activity.getApplicationContext(), YourActivityToLaunch.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(activity);
    stackBuilder.addParentStack(YourActivityToLaunch.class);
    stackBuilder.addNextIntent(notificationIntent);
    PendingIntent pIntent = stackBuilder.getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new Notification.Builder(activity)
            .setContentTitle(header)
            .setContentText(message)
            .setDefaults(
                    Notification.DEFAULT_SOUND
                            | Notification.DEFAULT_VIBRATE)
            .setContentIntent(pIntent).setAutoCancel(true)
            .setSmallIcon(drawable.notification_icon).build();
    notificationManager.notify(2, notification);
}

Windows Batch: How to add Host-Entries?

I am adding this answer in case someone else would like to store the host entry set in a txt file formatted like the normal host file. This looks for a TAB delimiter. This is based off of the answers from @Rashy and @that0n3guy. The differences can be noticed around the FOR command.

@echo off
TITLE Modifying your HOSTS file
ECHO.

:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"="
    echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"

IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%

ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop


:REJECTED
ECHO Your HOSTS file was left unchanged.
ECHO Finished.
GOTO END


:ACCEPTED
setlocal enabledelayedexpansion
::Create your list of host domains
for /F "tokens=1,2 delims=  " %%A in (%WINDIR%\System32\drivers\etc\storedhosts.txt) do (
    SET _host=%%B
    SET _ip=%%A
    SET NEWLINE=^& echo.
    ECHO Adding !_ip!       !_host!
    REM REM ::strip out this specific line and store in tmp file
    type %WINDIR%\System32\drivers\etc\hosts | findstr /v !_host! > tmp.txt
    REM REM ::re-add the line to it
    ECHO %NEWLINE%^!_ip!        !_host! >> tmp.txt
    REM ::overwrite host file
    copy /b/v/y tmp.txt %WINDIR%\System32\drivers\etc\hosts
    del tmp.txt 
)

ipconfig /flushdns
ECHO.
ECHO.
ECHO Finished, you may close this window now.
GOTO END

:END
ECHO.
PAUSE
EXIT

Example "storedhosts.txt" (tab delimited)

127.0.0.1   mysite.com
168.1.64.2  yoursite.com
192.1.0.1   internalsite.com

JSLint says "missing radix parameter"

Prior to ECMAScript 5, parseInt() also autodetected octal literals, which caused problems because many developers assumed a leading 0 would be ignored.

So Instead of :

var num = parseInt("071");      // 57

Do this:

var num = parseInt("071", 10);  // 71

var num = parseInt("071", 8);

var num = parseFloat(someValue); 

Reference

What is the fastest way to create a checksum for large files in C#

You can have a look to XxHash.Net ( https://github.com/wilhelmliao/xxHash.NET )
The xxHash algorythm seems to be faster than all other.
Some benchmark on the xxHash site : https://github.com/Cyan4973/xxHash

PS: I've not yet used it.

Where is the documentation for the values() method of Enum?

The method is implicitly defined (i.e. generated by the compiler).

From the JLS:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);

Creating a .p12 file

The openssl documentation says that file supplied as the -in argument must be in PEM format.

Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer is not PEM format rather it is PKCS7.

In order to create my .p12, I had to first convert the certificate to PEM:

openssl pkcs7 -in myCert.cer -print_certs -out certs.pem

and then execute

openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem

Is there a way for non-root processes to bind to "privileged" ports on Linux?

Port redirect made the most sense for us, but we ran into an issue where our application would resolve a url locally that also needed to be re-routed; (that means you shindig).

This will also allow you to be redirected when accessing the url on the local machine.

iptables -A PREROUTING -t nat -p tcp --dport 80 -j REDIRECT --to-port 8080
iptables -A OUTPUT -t nat -p tcp --dport 80 -j REDIRECT --to-port 8080

How do I find a particular value in an array and return its index?

The syntax you have there for your function doesn't make sense (why would the return value have a member called arr?).

To find the index, use std::distance and std::find from the <algorithm> header.

int x = std::distance(arr, std::find(arr, arr + 5, 3));

Or you can make it into a more generic function:

template <typename Iter>
size_t index_of(Iter first, Iter last, typename const std::iterator_traits<Iter>::value_type& x)
{
    size_t i = 0;
    while (first != last && *first != x)
      ++first, ++i;
    return i;
}

Here, I'm returning the length of the sequence if the value is not found (which is consistent with the way the STL algorithms return the last iterator). Depending on your taste, you may wish to use some other form of failure reporting.

In your case, you would use it like so:

size_t x = index_of(arr, arr + 5, 3);

How to determine if binary tree is balanced?

Bonus exercise response. The simple solution. Obviously in a real implementation one might wrap this or something to avoid requiring the user to include height in their response.

IsHeightBalanced(tree, out height)
    if (tree is empty)
        height = 0
        return true
    balance = IsHeightBalanced(tree.left, heightleft) and IsHeightBalanced(tree.right, heightright)
    height = max(heightleft, heightright)+1
    return balance and abs(heightleft - heightright) <= 1     

adb command for getting ip address assigned by operator

Try this command, it will help you to get ipaddress

adb shell ifconfig tiwlan0

tiwlan0 is the name of the wi-fi network interface on the device. This is generic command for getting ipaddress,

 adb shell netcfg

It will output like this

usb0     DOWN  0.0.0.0         0.0.0.0         0×00001002
sit0     DOWN  0.0.0.0         0.0.0.0         0×00000080
ip6tnl0  DOWN  0.0.0.0         0.0.0.0         0×00000080
gannet0  DOWN  0.0.0.0         0.0.0.0         0×00001082
rmnet0   UP    112.79.87.220   255.0.0.0       0x000000c1
rmnet1   DOWN  0.0.0.0         0.0.0.0         0×00000080
rmnet2   DOWN  0.0.0.0         0.0.0.0         0×00000080

How to simulate a mouse click using JavaScript?

JavaScript Code

   //this function is used to fire click event
    function eventFire(el, etype){
      if (el.fireEvent) {
        el.fireEvent('on' + etype);
      } else {
        var evObj = document.createEvent('Events');
        evObj.initEvent(etype, true, false);
        el.dispatchEvent(evObj);
      }
    }

function showPdf(){
  eventFire(document.getElementById('picToClick'), 'click');
}

HTML Code

<img id="picToClick" data-toggle="modal" data-target="#pdfModal" src="img/Adobe-icon.png" ng-hide="1===1">
  <button onclick="showPdf()">Click me</button>

Gradle - Could not find or load main class

I just ran into this problem and decided to debug it myself since i couldn't find a solution on the internet. All i did is change the mainClassName to it's whole path(with the correct subdirectories in the project ofc)

    mainClassName = 'main.java.hello.HelloWorld'

I know it's been almost one year since the post has been made, but i think someone will find this information useful.

Happy coding.

CSS Input field text color of inputted text

replace:

input, select, textarea{
    color: #000;
}

with:

input, select, textarea{
    color: #f00;
}

or color: #ff0000;

How to attach source or JavaDoc in eclipse for any jar file e.g. JavaFX?

To attach the Java source code with Eclipse,

When you install the JDK, you must have selected the option to install the Java source files too. This will copy the src.zip file in the installation directory. In Eclipse, go to Window -> Preferences -> Java -> Installed JREs -> Add and choose the JDK you have in your system. Eclipse will now list the JARs found in the dialog box. There, select the rt.jar and choose Source Attachment. By default, this will be pointing to the correct src.zip. If not, choose the src.zip file which you have in your java installation directory. java source attach in eclipse Similarly, if you have the javadoc downloaded in your machine, you can configure that too in this dialog box.

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

You can use this magic Spring Test annotation :

@TestPropertySource(properties = { "my.spring.property=20" }) 

see org.springframework.test.context.TestPropertySource

For example, this is the test class :

@ContextConfiguration(classes = { MyTestClass.Config.class })
@TestPropertySource(properties = { "my.spring.property=20" })
public class MyTestClass {

  public static class Config {
    @Bean
    MyClass getMyClass() {
      return new MyClass ();
    }
  }

  @Resource
  private MyClass myClass ;

  @Test
  public void myTest() {
   ...

And this is the class with the property :

@Component
public class MyClass {

  @Value("${my.spring.property}")
  private int mySpringProperty;
   ...

How can apply multiple background color to one div

Sorry for misunderstanding, from what I understood you want your DIV to have three different colors with different heights. This is the output of my code:

output,

If this is what you want try this code:

_x000D_
_x000D_
div {_x000D_
    height: 100px;_x000D_
    width:400px;_x000D_
    position: relative;_x000D_
}_x000D_
.c {_x000D_
    background: blue; /* Old browsers */_x000D_
}_x000D_
_x000D_
.c:after{_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width:20%;_x000D_
    left:0;_x000D_
    height:110%;_x000D_
    background: yellow;_x000D_
}_x000D_
.c:before{_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width:40%;_x000D_
    left:60%;_x000D_
    height:140%;_x000D_
    background: green;_x000D_
}
_x000D_
<div class="c"></div>
_x000D_
_x000D_
_x000D_

Python Socket Multiple Clients

accept can continuously provide new client connections. However, note that it, and other socket calls are usually blocking. Therefore you have a few options at this point:

  • Open new threads to handle clients, while the main thread goes back to accepting new clients
  • As above but with processes, instead of threads
  • Use asynchronous socket frameworks like Twisted, or a plethora of others

Test if something is not undefined in JavaScript

I know i went here 7 months late, but I found this questions and it looks interesting. I tried this on my browser console.

try{x,true}catch(e){false}

If variable x is undefined, error is catched and it will be false, if not, it will return true. So you can use eval function to set the value to a variable

var isxdefined = eval('try{x,true}catch(e){false}')

Is it possible to run selenium (Firefox) web driver without a GUI?

Yes, you can run test scripts without a browser, But you should run them in headless mode.

What certificates are trusted in truststore?

Trust store generally (actually should only contain root CAs but this rule is violated in general) contains the certificates that of the root CAs (public CAs or private CAs). You can verify the list of certs in trust store using

keytool -list -v -keystore truststore.jks

Delimiter must not be alphanumeric or backslash and preg_match

You need a delimiter for your pattern. It should be added at the start and end of the pattern like so:

$pattern = "/My name is '(.*)' and im fine/";  // With / as a delimeter 

FIFO class in Java

You can use LinkedBlockingQueue I use it in my projects. It's part of standard java and quite easy to use

How to get status code from webclient?

Tried it out. ResponseHeaders do not include status code.

If I'm not mistaken, WebClient is capable of abstracting away multiple distinct requests in a single method call (e.g. correctly handling 100 Continue responses, redirects, and the like). I suspect that without using HttpWebRequest and HttpWebResponse, a distinct status code may not be available.

It occurs to me that, if you are not interested in intermediate status codes, you can safely assume the final status code is in the 2xx (successful) range, otherwise, the call would not be successful.

The status code unfortunately isn't present in the ResponseHeaders dictionary.

Assign variable in if condition statement, good practice or not?

I would consider this more of an old-school C style; it is not really good practice in JavaScript so you should avoid it.

Sum columns with null values in oracle

The top-rated answer with NVL is totally valid. If you have any interest in making your SQL code more portable, you might want to use CASE, which is supported with the same syntax in both Oracle and SQL Server:

select 
  type,craft,
  SUM(
    case when regular is null
         then 0
         else regular
    end
    +
    case when overtime is null
         then 0
         else overtime
    end
  ) as total_hours
from 
  hours_t
group by
  type
 ,craft
order by
  type
 ,craft

Finding the length of a Character Array in C

You can use strlen

strlen(urarray);

You can code it yourself so you understand how it works

size_t my_strlen(const char *str)
{
  size_t i;

  for (i = 0; str[i]; i++);
  return i;
}

if you want the size of the array then you use sizeof

char urarray[255];
printf("%zu", sizeof(urarray));

Fastest way to serialize and deserialize .NET objects

Here's your model (with invented CT and TE) using protobuf-net (yet retaining the ability to use XmlSerializer, which can be useful - in particular for migration); I humbly submit (with lots of evidence if you need it) that this is the fastest (or certainly one of the fastest) general purpose serializer in .NET.

If you need strings, just base-64 encode the binary.

[XmlType]
public class CT {
    [XmlElement(Order = 1)]
    public int Foo { get; set; }
}
[XmlType]
public class TE {
    [XmlElement(Order = 1)]
    public int Bar { get; set; }
}
[XmlType]
public class TD {
    [XmlElement(Order=1)]
    public List<CT> CTs { get; set; }
    [XmlElement(Order=2)]
    public List<TE> TEs { get; set; }
    [XmlElement(Order = 3)]
    public string Code { get; set; }
    [XmlElement(Order = 4)]
    public string Message { get; set; }
    [XmlElement(Order = 5)]
    public DateTime StartDate { get; set; }
    [XmlElement(Order = 6)]
    public DateTime EndDate { get; set; }

    public static byte[] Serialize(List<TD> tData) {
        using (var ms = new MemoryStream()) {
            ProtoBuf.Serializer.Serialize(ms, tData);
            return ms.ToArray();
        }            
    }

    public static List<TD> Deserialize(byte[] tData) {
        using (var ms = new MemoryStream(tData)) {
            return ProtoBuf.Serializer.Deserialize<List<TD>>(ms);
        }
    }
}

show loading icon until the page is load?

HTML, CSS, JS are all good as given in above answers. However they won't stop user from clicking the loader and visiting page. And if page time is large, it looks broken and defeats the purpose.

So in CSS consider adding

pointer-events: none;
cursor: default;

Also, instead of using gif files, if you are using fontawesome which everybody uses now a days, consider using in your html

<i class="fa fa-spinner fa-spin">

HTML5 and frameborder

As per the other posting here, the best solution is to use the CSS entry of

style="border:0;"

Bootstrap dropdown not working

Try this in the head section

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

proper name for python * operator?

I call it "positional expansion", as opposed to ** which I call "keyword expansion".

typeof operator in C

It's not exactly an operator, rather a keyword. And no, it doesn't do any runtime-magic.

jquery find closest previous sibling with class

Using prevUntil() will allow us to get a distant sibling without having to get all. I had a particularly long set that was too CPU intensive using prevAll().

var category = $('li.current_sub').prev('li.par_cat');
if (category.length == 0){
  category = $('li.current_sub').prevUntil('li.par_cat').last().prev();
}
category.show();

This gets the first preceding sibling if it matches, otherwise it gets the sibling preceding the one that matches, so we just back up one more with prev() to get the desired element.

How do I restart a service on a remote machine in Windows?

One way would be to enable telnet server on the machin you want to control services on (add/remove windows components)

Open dos prompt
Type telnet yourmachineip/name
Log on
type net start &serviceName* e.g. w3svc

This will start IIS or you can use net stop to stop a service.

Depending on your setup you need to look at a way of securing the telnet connection as I think its unencrypted.

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

I was able to fix this issue by matching my build version to the .NET version on the server.

I double clicked the .exe just to see what would happen and it told me to install 4.5....

So I downgraded to 4.0 and it worked!

So make sure your versions match. It ran on my dev box fine, but server had older .NET version.

How can I pass parameters to a partial view in mvc 4

Your question is hard to understand, but if I'm getting the gist, you simply have some value in your main view that you want to access in a partial being rendered in that view.

If you just render a partial with just the partial name:

@Html.Partial("_SomePartial")

It will actually pass your model as an implicit parameter, the same as if you were to call:

@Html.Partial("_SomePartial", Model)

Now, in order for your partial to actually be able to use this, though, it too needs to have a defined model, for example:

@model Namespace.To.Your.Model

@Html.Action("MemberProfile", "Member", new { id = Model.Id })

Alternatively, if you're dealing with a value that's not on your view's model (it's in the ViewBag or a value generated in the view itself somehow, then you can pass a ViewDataDictionary

@Html.Partial("_SomePartial", new ViewDataDictionary { { "id", someInteger } });

And then:

@Html.Action("MemberProfile", "Member", new { id = ViewData["id"] })

As with the model, Razor will implicitly pass your partial the view's ViewData by default, so if you had ViewBag.Id in your view, then you can reference the same thing in your partial.

Appending values to dictionary in Python

vowels = ("a","e","i","o","u") #create a list of vowels  
my_str = ("this is my dog and a cat") # sample string to get the vowel count
count = {}.fromkeys(vowels,0) #create dict initializing the count to each vowel to 0                                                                    
for char in my_str :  
    if char in count:  
       count[char] += 1  

print(count)  

Set height 100% on absolute div

Another solution without using any height but still fills 100% available height. Checkout this e.g on the codepen. http://codepen.io/gauravshankar/pen/PqoLLZ

For this html and body should have 100% height. This height is equal to the viewport height.

Make inner div position absolute and give top and bottom 0. This fills the div to available height. (height equal to body.)

html code:

<head></head>

<body>
  <div></div>
</body>

</html>

css code:

* {
  margin: 0;
  padding: 0;
}

html,
body {
  height: 100%;
  position: relative;
}

html {
  background-color: red;
}

body {
  background-color: green;
}

body> div {
  position: absolute;
  background-color: teal;
  width: 300px;
  top: 0;
  bottom: 0;
}

Is it possible to decompile an Android .apk file?

I may also add, that nowadays it is possible to decompile Android application online, no software needed!

Here are 2 options for you:

function to return a string in java

In Java, a String is a reference to heap-allocated storage. Returning "ans" only returns the reference so there is no need for stack-allocated storage. In fact, there is no way in Java to allocate objects in stack storage.

I would change to this, though. You don't need "ans" at all.

return String.format("%d:%d", mins, secs);

JQuery Number Formatting

I would recommend looking at this article on how to use javascript to handle basic formatting:

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

source: http://www.mredkj.com/javascript/numberFormat.html

While jQuery can make your life easier in a million different ways I would say it's overkill for this. Keep in mind that jQuery can be fairly large and your user's browser needs to download it when you use it on a page.

When ever using jQuery you should step back and ask if it contributes enough to justify the extra overhead of downloading the library.

If you need some sort of advanced formatting (like the localization stuff in the plugin you linked), or you are already including jQuery it might be worth looking at a jQuery plugin.

Side note - check this out if you want to get a chuckle about the over use of jQuery.

How to redirect 'print' output to a file using python?

The most obvious way to do this would be to print to a file object:

with open('out.txt', 'w') as f:
    print >> f, 'Filename:', filename     # Python 2.x
    print('Filename:', filename, file=f)  # Python 3.x

However, redirecting stdout also works for me. It is probably fine for a one-off script such as this:

import sys

orig_stdout = sys.stdout
f = open('out.txt', 'w')
sys.stdout = f

for i in range(2):
    print('i = ', i)

sys.stdout = orig_stdout
f.close()

Since Python 3.4 there's a simple context manager available to do this in the standard library:

from contextlib import redirect_stdout

with open('out.txt', 'w') as f:
    with redirect_stdout(f):
        print('data')

Redirecting externally from the shell itself is another option, and often preferable:

./script.py > out.txt

Other questions:

What is the first filename in your script? I don't see it initialized.

My first guess is that glob doesn't find any bamfiles, and therefore the for loop doesn't run. Check that the folder exists, and print out bamfiles in your script.

Also, use os.path.join and os.path.basename to manipulate paths and filenames.

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

In my case I found that I have an aggressive plugin for Vim, just restarted it.

Convert to absolute value in Objective-C

You can use this function to get the absolute value:

+(NSNumber *)absoluteValue:(NSNumber *)input {
  return [NSNumber numberWithDouble:fabs([input doubleValue])];
}

Rails 3.1 and Image Assets

For what it's worth, when I did this I found that no folder should be include in the path in the css file. For instance if I have app/assets/images/example.png, and I put this in my css file...

div.example { background: url('example.png'); }

... then somehow it magically works. I figured this out by running the rake assets:precompile task, which just sucks everything out of all your load paths and dumps it in a junk drawer folder: public/assets. That's ironic, IMO...

In any case this means you don't need to put any folder paths, everything in your assets folders will all end up living in one huge directory. How this system resolves file name conflicts is unclear, you may need to be careful about that.

Kind of frustrating there aren't better docs out there for this big of a change.

Mercurial undo last commit

One way would be hg rollback (deprecated as of Hg2.7, August 2013)

Please use hg commit --amend instead of rollback to correct mistakes in the last commit.

Roll back the last transaction in a repository.

When committing or merging, Mercurial adds the changeset entry last.
Mercurial keeps a transaction log of the name of each file touched and its length prior to the transaction. On abort, it truncates each file to its prior length. This simplicity is one benefit of making revlogs append-only. The transaction journal also allows an undo operation.

See TortoiseHg Recovery section:

alt text

This thread also details the difference between hg rollback and hg strip:
(written by Martin Geisler who also contributes on SO)

  • 'hg rollback' will remove the last transaction. Transactions are a concept often found in databases. In Mercurial we start a transaction when certain operations are run, such as commit, push, pull...
    When the operation finishes succesfully, the transaction is marked as complete. If an error occurs, the transaction is "rolled back" and the repository is left in the same state as before.
    You can manually trigger a rollback with 'hg rollback'. This will undo the last transactional command. If a pull command brought 10 new changesets into the repository on different branches, then 'hg rollback' will remove them all. Please note: there is no backup when you rollback a transaction!

  • 'hg strip' will remove a changeset and all its descendants. The changesets are saved as a bundle, which you can apply again if you need them back.

ForeverWintr suggests in the comments (in 2016, 5 years later)

You can 'un-commit' files by first hg forgetting them, e.g.: hg forget filea; hg commit --amend, but that seems unintuitive.
hg strip --keep is probably a better solution for modern hg.

How to define constants in Visual C# like #define in C?

In C#, per MSDN library, we have the "const" keyword that does the work of the "#define" keyword in other languages.

"...when the compiler encounters a constant identifier in C# source code (for example, months), it substitutes the literal value directly into the intermediate language (IL) code that it produces." ( https://msdn.microsoft.com/en-us/library/ms173119.aspx )

Initialize constants at time of declaration since there is no changing them.

public const int cMonths = 12;

How to clear Flutter's Build cache?

Same issue with mine.

New to Flutter. I'm using VS build-in terminal to do flutter run, to run the app in iPhone. It gives me error Error when reading 'lib/student_model.dart': No such file..., which is an old code version in my code. I have changed it to lib/model/student_model.dart.

And I search this line 'lib/student_model.dart'in the project, it appears filekernel_snapshot.d` containing it. So, it build the project with old code version.

For me, Flutter clean is not working. Restart VS fix the issue, not sure the problem is due to Flutter or VS?

And I'm wondering if there is some command to just build flutter project without run?

Entity Framework and Connection Pooling

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

9.3 Context per request

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

Configure DataSource programmatically in Spring Boot

My project of spring-boot has run normally according to your assistance. The yaml datasource configuration is:

spring:
  # (DataSourceAutoConfiguration & DataSourceProperties)
  datasource:
    name: ds-h2
    url: jdbc:h2:D:/work/workspace/fdata;DATABASE_TO_UPPER=false
    username: h2
    password: h2
    driver-class: org.h2.Driver

Custom DataSource

@Configuration
@Component
public class DataSourceBean {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    @Primary
    public DataSource getDataSource() {
        return DataSourceBuilder
                .create()
//                .url("jdbc:h2:D:/work/workspace/fork/gs-serving-web-content/initial/data/fdata;DATABASE_TO_UPPER=false")
//                .username("h2")
//                .password("h2")
//                .driverClassName("org.h2.Driver")
                .build();
    }
}

How to make JavaScript execute after page load?

Here's a script based on deferred js loading after the page is loaded,

<script type="text/javascript">
  function downloadJSAtOnload() {
      var element = document.createElement("script");
      element.src = "deferredfunctions.js";
      document.body.appendChild(element);
  }

  if (window.addEventListener)
      window.addEventListener("load", downloadJSAtOnload, false);
  else if (window.attachEvent)
      window.attachEvent("onload", downloadJSAtOnload);
  else window.onload = downloadJSAtOnload;
</script>

Where do I place this?

Paste code in your HTML just before the </body> tag (near the bottom of your HTML file).

What does it do?

This code says wait for the entire document to load, then load the external file deferredfunctions.js.

Here's an example of the above code - Defer Rendering of JS

I wrote this based on defered loading of javascript pagespeed google concept and also sourced from this article Defer loading javascript

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

What does ON [PRIMARY] mean?

ON [PRIMARY] will create the structures on the "Primary" filegroup. In this case the primary key index and the table will be placed on the "Primary" filegroup within the database.

jQuery/Javascript function to clear all the fields of a form

I use following solution:

1) Setup Jquery Validation Plugin

2) Then:

$('your form's selector').resetForm();

Detecting value change of input[type=text] in jQuery

Use this: https://github.com/gilamran/JQuery-Plugin-AnyChange

It handles all the ways to change the input, including content menu (Using the mouse)

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

I solved this simply:

<div ng-repeat="Object in List | filter: (FilterObj.FilterProperty1 ? {'ObjectProperty1': FilterObj.FilterProperty1} : '') | filter:(FilterObj.FilterProperty2 ? {'ObjectProperty2': FilterObj.FilterProperty2} : '')">

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

Make sure you include the Places library &libraries=places parameter when you first load the API.

For example:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

C# guid and SQL uniqueidentifier

SQL is expecting the GUID as a string. The following in C# returns a string Sql is expecting.

"'" + Guid.NewGuid().ToString() + "'"

Something like

INSERT INTO TABLE (GuidID) VALUE ('4b5e95a7-745a-462f-ae53-709a8583700a')

is what it should look like in SQL.

convert a JavaScript string variable to decimal/money

An easy short hand way would be to use +x It keeps the sign intact as well as the decimal numbers. The other alternative is to use parseFloat(x). Difference between parseFloat(x) and +x is for a blank string +x returns 0 where as parseFloat(x) returns NaN.

Expand a div to fill the remaining width

You can try CSS Grid Layout.

_x000D_
_x000D_
dl {_x000D_
  display: grid;_x000D_
  grid-template-columns: max-content auto;_x000D_
}_x000D_
_x000D_
dt {_x000D_
  grid-column: 1;_x000D_
}_x000D_
_x000D_
dd {_x000D_
  grid-column: 2;_x000D_
  margin: 0;_x000D_
  background-color: #ccc;_x000D_
}
_x000D_
<dl>_x000D_
  <dt>lorem ipsum</dt>_x000D_
  <dd>dolor sit amet</dd>_x000D_
  <dt>carpe</dt>_x000D_
  <dd>diem</dd>_x000D_
</dl>
_x000D_
_x000D_
_x000D_

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

Try to use the argument: -sysdir <Your_SDK_DIR> and then check whether the error message displayed.

See also: https://android.googlesource.com/platform/external/qemu/+/1a15692cded92d66dea1a51389a3c4b9e3b3631a/android/emulator/main-emulator.cpp

Check out these clip you will find out the reason:

// Sanity checks.
if (avdName) {
    if (!isCpuArchSupportedByRanchu(avdArch)) {
        APANIC("CPU Architecture '%s' is not supported by the QEMU2 emulator, (the classic engine is deprecated!)",
               avdArch);
    }
    std::string systemPath = getAvdSystemPath(avdName, sysDir);
    if (systemPath.empty()) {
        const char* env = getenv("ANDROID_SDK_ROOT");
        if (!env || !env[0]) {
            APANIC("Cannot find AVD system path. Please define "
                   "ANDROID_SDK_ROOT\n");
        } else {
            APANIC("Broken AVD system path. Check your ANDROID_SDK_ROOT "
                   "value [%s]!\n",
                   env);
        }
    }
}

Then if you see emulator: ERROR: can't find SDK installation directory, please check this solution. Android emulator errors with "emulator: ERROR: can't find SDK installation directory"

How to set proper codeigniter base url?

Base url set in CodeIgniter for all url

$config['base_url'] = "http://".$_SERVER['HTTP_HOST']."/";

Custom ImageView with drop shadow

I've built upon the answer above - https://stackoverflow.com/a/11155031/2060486 - to create a shadow around ALL sides..

 private static final int GRAY_COLOR_FOR_SHADE = Color.argb(50, 79, 79, 79);

// this method takes a bitmap and draws around it 4 rectangles with gradient to create a
// shadow effect.
public static Bitmap addShadowToBitmap(Bitmap origBitmap) {
    int shadowThickness = 13; // can be adjusted as needed
    int bmpOriginalWidth = origBitmap.getWidth();
    int bmpOriginalHeight = origBitmap.getHeight();
    int bigW = bmpOriginalWidth + shadowThickness * 2; // getting dimensions for a bigger bitmap with margins
    int bigH = bmpOriginalHeight + shadowThickness * 2;
    Bitmap containerBitmap = Bitmap.createBitmap(bigW, bigH, Bitmap.Config.ARGB_8888);
    Bitmap copyOfOrigBitmap = Bitmap.createScaledBitmap(origBitmap, bmpOriginalWidth, bmpOriginalHeight, false);
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Canvas canvas = new Canvas(containerBitmap); // drawing the shades on the bigger bitmap
    //right shade - direction of gradient is positive x (width)
    Shader rightShader = new LinearGradient(bmpOriginalWidth, 0, bigW, 0, GRAY_COLOR_FOR_SHADE,
            Color.TRANSPARENT, Shader.TileMode.CLAMP);
    paint.setShader(rightShader);
    canvas.drawRect(bigW - shadowThickness, shadowThickness, bigW, bigH - shadowThickness, paint);
    //bottom shade - direction is positive y (height)
    Shader bottomShader = new LinearGradient(0, bmpOriginalHeight, 0, bigH, GRAY_COLOR_FOR_SHADE,
            Color.TRANSPARENT, Shader.TileMode.CLAMP);
    paint.setShader(bottomShader);
    canvas.drawRect(shadowThickness, bigH - shadowThickness, bigW - shadowThickness, bigH, paint);
    //left shade - direction is negative x
    Shader leftShader = new LinearGradient(shadowThickness, 0, 0, 0, GRAY_COLOR_FOR_SHADE,
            Color.TRANSPARENT, Shader.TileMode.CLAMP);
    paint.setShader(leftShader);
    canvas.drawRect(0, shadowThickness, shadowThickness, bigH - shadowThickness, paint);
    //top shade - direction is negative y
    Shader topShader = new LinearGradient(0, shadowThickness, 0, 0, GRAY_COLOR_FOR_SHADE,
            Color.TRANSPARENT, Shader.TileMode.CLAMP);
    paint.setShader(topShader);
    canvas.drawRect(shadowThickness, 0, bigW - shadowThickness, shadowThickness, paint);
    // starting to draw bitmap not from 0,0 to get margins for shade rectangles
    canvas.drawBitmap(copyOfOrigBitmap, shadowThickness, shadowThickness, null);
    return containerBitmap;
}

Change the color in the const as you see fit.

Add disabled attribute to input element using Javascript

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

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

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

What Content-Type value should I send for my XML sitemap?

As a rule of thumb, the safest bet towards making your document be treated properly by all web servers, proxies, and client browsers, is probably the following:

  1. Use the application/xml content type
  2. Include a character encoding in the content type, probably UTF-8
  3. Include a matching character encoding in the encoding attribute of the XML document itself.

In terms of the RFC 3023 spec, which some browsers fail to implement properly, the major difference in the content types is in how clients are supposed to treat the character encoding, as follows:

For application/xml, application/xml-dtd, application/xml-external-parsed-entity, or any one of the subtypes of application/xml such as application/atom+xml, application/rss+xml or application/rdf+xml, the character encoding is determined in this order:

  1. the encoding given in the charset parameter of the Content-Type HTTP header
  2. the encoding given in the encoding attribute of the XML declaration within the document,
  3. utf-8.

For text/xml, text/xml-external-parsed-entity, or a subtype like text/foo+xml, the encoding attribute of the XML declaration within the document is ignored, and the character encoding is:

  1. the encoding given in the charset parameter of the Content-Type HTTP header, or
  2. us-ascii.

Most parsers don't implement the spec; they ignore the HTTP Context-Type and just use the encoding in the document. With so many ill-formed documents out there, that's unlikely to change any time soon.

Excel: VLOOKUP that returns true or false?

ISNA is the best function to use. I just did. I wanted all cells whose value was NOT in an array to conditionally format to a certain color.

=ISNA(VLOOKUP($A2,Sheet1!$A:$D,2,FALSE))

SQLite in Android How to update a specific row

For updates, need to call setTransactionSuccessfull for changes to get committed like so:

db.beginTransaction();
try {
    db.update(...) 
    db.setTransactionSuccessfull(); // changes get rolled back if this not called
} finally {
   db.endTransaction(); // commit or rollback
}

Is there any way to set environment variables in Visual Studio Code?

Assuming you mean for a debugging session(?) then you can include a env property in your launch configuration.

If you open the .vscode/launch.json file in your workspace or select Debug > Open Configurations then you should see a set of launch configurations for debugging your code. You can then add to it an env property with a dictionary of string:string.

Here is an example for an ASP.NET Core app from their standard web template setting the ASPNETCORE_ENVIRONMENT to Development :

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": ".NET Core Launch (web)",
      "type": "coreclr",
      "request": "launch",
      "preLaunchTask": "build",
      // If you have changed target frameworks, make sure to update the program path.
      "program": "${workspaceFolder}/bin/Debug/netcoreapp2.0/vscode-env.dll",
      "args": [],
      "cwd": "${workspaceFolder}",
      "stopAtEntry": false,
      "internalConsoleOptions": "openOnSessionStart",
      "launchBrowser": {
        "enabled": true,
        "args": "${auto-detect-url}",
        "windows": {
          "command": "cmd.exe",
          "args": "/C start ${auto-detect-url}"
        },
        "osx": {
          "command": "open"
        },
        "linux": {
          "command": "xdg-open"
        }
      },
      "env": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "sourceFileMap": {
        "/Views": "${workspaceFolder}/Views"
      }
    },
    {
      "name": ".NET Core Attach",
      "type": "coreclr",
      "request": "attach",
      "processId": "${command:pickProcess}"
    }
  ]
}

Using an index to get an item, Python

What you show, ('A','B','C','D','E'), is not a list, it's a tuple (the round parentheses instead of square brackets show that). Nevertheless, whether it to index a list or a tuple (for getting one item at an index), in either case you append the index in square brackets.

So:

thetuple = ('A','B','C','D','E')
print thetuple[0]

prints A, and so forth.

Tuples (differently from lists) are immutable, so you couldn't assign to thetuple[0] etc (as you could assign to an indexing of a list). However you can definitely just access ("get") the item by indexing in either case.

When do I need to use a semicolon vs a slash in Oracle SQL?

I wanted to clarify some more use between the ; and the /

In SQLPLUS:

  1. ; means "terminate the current statement, execute it and store it to the SQLPLUS buffer"
  2. <newline> after a D.M.L. (SELECT, UPDATE, INSERT,...) statement or some types of D.D.L (Creating Tables and Views) statements (that contain no ;), it means, store the statement to the buffer but do not run it.
  3. / after entering a statement into the buffer (with a blank <newline>) means "run the D.M.L. or D.D.L. or PL/SQL in the buffer.
  4. RUN or R is a sqlsplus command to show/output the SQL in the buffer and run it. It will not terminate a SQL Statement.
  5. / during the entering of a D.M.L. or D.D.L. or PL/SQL means "terminate the current statement, execute it and store it to the SQLPLUS buffer"

NOTE: Because ; are used for PL/SQL to end a statement ; cannot be used by SQLPLUS to mean "terminate the current statement, execute it and store it to the SQLPLUS buffer" because we want the whole PL/SQL block to be completely in the buffer, then execute it. PL/SQL blocks must end with:

END;
/

How to run a program without an operating system?

Operating System as the inspiration

The operating system is also a program, so we can also create our own program by creating from scratch or changing (limiting or adding) features of one of the small operating systems, and then run it during the boot process (using an ISO image).

For example, this page can be used as a starting point:

How to write a simple operating system

Here, the entire Operating System fit entirely in a 512-byte boot sector (MBR)!

Such or similar simple OS can be used to create a simple framework that will allow us:

make the bootloader load subsequent sectors on the disk into RAM, and jump to that point to continue execution. Or you could read up on FAT12, the filesystem used on floppy drives, and implement that.

There are many possibilities, however. For for example to see a bigger x86 assembly language OS we can explore the MykeOS, x86 operating system which is a learning tool to show the simple 16-bit, real-mode OSes work, with well-commented code and extensive documentation.

Boot Loader as the inspiration

Other common type of programs that run without the operating system are also Boot Loaders. We can create a program inspired by such a concept for example using this site:

How to develop your own Boot Loader

The above article presents also the basic architecture of such a programs:

  1. Correct loading to the memory by 0000:7C00 address.
  2. Calling the BootMain function that is developed in the high-level language.
  3. Show “”Hello, world…”, from low-level” message on the display.

As we can see, this architecture is very flexible and allows us to implement any program, not necessarily a boot loader.

In particular, it shows how to use the "mixed code" technique thanks to which it is possible to combine high-level constructions (from C or C++) with low-level commands (from Assembler). This is a very useful method, but we have to remember that:

to build the program and obtain executable file you will need the compiler and linker of Assembler for 16-bit mode. For C/C++ you will need only the compiler that can create object files for 16-bit mode.

The article shows also how to see the created program in action and how to perform its testing and debug.

UEFI applications as the inspiration

The above examples used the fact of loading the sector MBR on the data medium. However, we can go deeper into the depths by plaing for example with the UEFI applications:

Beyond loading an OS, UEFI can run UEFI applications, which reside as files on the EFI System Partition. They can be executed from the UEFI command shell, by the firmware's boot manager, or by other UEFI applications. UEFI applications can be developed and installed independently of the system manufacturer.

A type of UEFI application is an OS loader such as GRUB, rEFInd, Gummiboot, and Windows Boot Manager; which loads an OS file into memory and executes it. Also, an OS loader can provide a user interface to allow the selection of another UEFI application to run. Utilities like the UEFI shell are also UEFI applications.

If we would like to start creating such programs, we can, for example, start with these websites:

Programming for EFI: Creating a "Hello, World" Program / UEFI Programming - First Steps

Exploring security issues as the inspiration

It is well known that there is a whole group of malicious software (which are programs) that are running before the operating system starts.

A huge group of them operate on the MBR sector or UEFI applications, just like the all above solutions, but there are also those that use another entry point such as the Volume Boot Record (VBR) or the BIOS:

There are at least four known BIOS attack viruses, two of which were for demonstration purposes.

or perhaps another one too.

Attacks before system startup

Bootkits have evolved from Proof-of-Concept development to mass distribution and have now effectively become open-source software.

Different ways to boot

I also think that in this context it is also worth mentioning that there are various forms of booting the operating system (or the executable program intended for this). There are many, but I would like to pay attention to loading the code from the network using Network Boot option (PXE), which allows us to run the program on the computer regardless of its operating system and even regardless of any storage medium that is directly connected to the computer:

What Is Network Booting (PXE) and How Can You Use It?

type object 'datetime.datetime' has no attribute 'datetime'

If you have used:

from datetime import datetime

Then simply write the code as:

date = datetime(int(year), int(month), 1)

But if you have used:

import datetime

then only you can write:

date = datetime.datetime(int(2005), int(5), 1)

Conditional Replace Pandas

.ix indexer works okay for pandas version prior to 0.20.0, but since pandas 0.20.0, the .ix indexer is deprecated, so you should avoid using it. Instead, you can use .loc or iloc indexers. You can solve this problem by:

mask = df.my_channel > 20000
column_name = 'my_channel'
df.loc[mask, column_name] = 0

Or, in one line,

df.loc[df.my_channel > 20000, 'my_channel'] = 0

mask helps you to select the rows in which df.my_channel > 20000 is True, while df.loc[mask, column_name] = 0 sets the value 0 to the selected rows where maskholds in the column which name is column_name.

Update: In this case, you should use loc because if you use iloc, you will get a NotImplementedError telling you that iLocation based boolean indexing on an integer type is not available.

SQL Error: ORA-00922: missing or invalid option

The error you're getting appears to be the result of the fact that there is no underscore between "chartered" and "flight" in the table name. I assume you want something like this where the name of the table is chartered_flight.

CREATE TABLE chartered_flight(flight_no NUMBER(4) PRIMARY KEY
, customer_id NUMBER(6) REFERENCES customer(customer_id)
, aircraft_no NUMBER(4) REFERENCES aircraft(aircraft_no)
, flight_type VARCHAR2 (12)
, flight_date DATE NOT NULL
, flight_time INTERVAL DAY TO SECOND NOT NULL
, takeoff_at CHAR (3) NOT NULL
, destination CHAR (3) NOT NULL)

Generally, there is no benefit to declaring a column as CHAR(3) rather than VARCHAR2(3). Declaring a column as CHAR(3) doesn't force there to be three characters of (useful) data. It just tells Oracle to space-pad data with fewer than three characters to three characters. That is unlikely to be helpful if someone inadvertently enters an incorrect code. Potentially, you could declare the column as VARCHAR2(3) and then add a CHECK constraint that LENGTH(takeoff_at) = 3.

CREATE TABLE chartered_flight(flight_no NUMBER(4) PRIMARY KEY
, customer_id NUMBER(6) REFERENCES customer(customer_id)
, aircraft_no NUMBER(4) REFERENCES aircraft(aircraft_no)
, flight_type VARCHAR2 (12)
, flight_date DATE NOT NULL
, flight_time INTERVAL DAY TO SECOND NOT NULL
, takeoff_at CHAR (3) NOT NULL CHECK( length( takeoff_at ) = 3 )
, destination CHAR (3) NOT NULL CHECK( length( destination ) = 3 )
)

Since both takeoff_at and destination are airport codes, you really ought to have a separate table of valid airport codes and define foreign key constraints between the chartered_flight table and this new airport_code table. That ensures that only valid airport codes are added and makes it much easier in the future if an airport code changes.

And from a naming convention standpoint, since both takeoff_at and destination are airport codes, I would suggest that the names be complementary and indicate that fact. Something like departure_airport_code and arrival_airport_code, for example, would be much more meaningful.

How to convert int to float in python?

Other than John's answer, you could also make one of the variable float, and the result will yield float.

>>> 144 / 314.0
0.4585987261146497

How can I remove 3 characters at the end of a string in php?

Just do:

echo substr($string, 0, -3);

You don't need to use a strlen call, since, as noted in the substr docs:

If length is given and is negative, then that many characters will be omitted from the end of string

How to declare a global variable in a .js file

As mentioned above, there are issues with using the top-most scope in your script file. Here is another issue: The script file might be run from a context that is not the global context in some run-time environment.

It has been proposed to assign the global to window directly. But that is also run-time dependent and does not work in Node etc. It goes to show that portable global variable management needs some careful consideration and extra effort. Maybe they will fix it in future ECMS versions!

For now, I would recommend something like this to support proper global management for all run-time environments:

/**
 * Exports the given object into the global context.
 */
var exportGlobal = function(name, object) {
    if (typeof(global) !== "undefined")  {
        // Node.js
        global[name] = object;
    }
    else if (typeof(window) !== "undefined") {
        // JS with GUI (usually browser)
        window[name] = object;
    }
    else {
        throw new Error("Unkown run-time environment. Currently only browsers and Node.js are supported.");
    }
};


// export exportGlobal itself
exportGlobal("exportGlobal", exportGlobal);

// create a new global namespace
exportGlobal("someothernamespace", {});

It's a bit more typing, but it makes your global variable management future-proof.

Disclaimer: Part of this idea came to me when looking at previous versions of stacktrace.js.

I reckon, one can also use Webpack or other tools to get more reliable and less hackish detection of the run-time environment.

Convert .pfx to .cer

If you're working in PowerShell you can use something like the following, given a pfx file InputBundle.pfx, to produce a DER encoded (binary) certificate file OutputCert.der:

Get-PfxCertificate -FilePath InputBundle.pfx | 
Export-Certificate -FilePath OutputCert.der -Type CERT

Newline added for clarity, but you can of course have this all on a single line.

If you need the certificate in ASCII/Base64 encoded PEM format, you can take extra steps to do so as documented elsewhere, such as here: https://superuser.com/questions/351548/windows-integrated-utility-to-convert-der-to-pem

If you need to export to a different format than DER encoded, you can change the -Type parameter for Export-Certificate to use the types supported by .NET, as seen in help Export-Certificate -Detailed:

-Type <CertType>
    Specifies the type of output file for the certificate export as follows. 
     -- SST: A Microsoft serialized certificate store (.sst) file format which can contain one or more certificates. This is the default value for multiple certificates. 
     -- CERT: A .cer file format which contains a single DER-encoded certificate. This is the default value for one certificate. 
     -- P7B: A PKCS#7 file format which can contain one or more certificates.

How can I specify the required Node.js version in package.json?

.nvmrc

If you are using NVM like this, which you likely should, then you can indicate the nodejs version required for given project in a git-tracked .nvmrc file:

echo v10.15.1 > .nvmrc

This does not take effect automatically on cd, which is sane: the user must then do a:

nvm use

and now that version of node will be used for the current shell.

You can list the versions of node that you have with:

nvm list

.nvmrc is documented at: https://github.com/creationix/nvm/tree/02997b0753f66c9790c6016ed022ed2072c22603#nvmrc

How to automatically select that node version on cd was asked at: Automatically switch to correct version of Node based on project

Tested with NVM 0.33.11.

Requested registry access is not allowed

If you don't need admin privs for the entire app, or only for a few infrequent changes you can do the changes in a new process and launch it using:

Process.StartInfo.UseShellExecute = true;
Process.StartInfo.Verb = "runas";

which will run the process as admin to do whatever you need with the registry, but return to your app with the normal priviledges. This way it doesn't prompt the user with a UAC dialog every time it launches.

CSS media queries for screen sizes

Unless you have more style sheets than that, you've messed up your break points:

#1 (max-width: 700px)
#2 (min-width: 701px) and (max-width: 900px)
#3 (max-width: 901px)

The 3rd media query is probably meant to be min-width: 901px. Right now, it overlaps #1 and #2, and only controls the page layout by itself when the screen is exactly 901px wide.

Edit for updated question:

(max-width: 640px)
(max-width: 800px)
(max-width: 1024px)
(max-width: 1280px)

Media queries aren't like catch or if/else statements. If any of the conditions match, then it will apply all of the styles from each media query it matched. If you only specify a min-width for all of your media queries, it's possible that some or all of the media queries are matched. In your case, a device that's 640px wide matches all 4 of your media queries, so all for style sheets are loaded. What you are most likely looking for is this:

(max-width: 640px)
(min-width: 641px) and (max-width: 800px)
(min-width: 801px) and (max-width: 1024px)
(min-width: 1025px)

Now there's no overlap. The styles will only apply if the device's width falls between the widths specified.

How to call two methods on button's onclick method in HTML or JavaScript?

Hi,

You can also do as like below... In this way, your both functions should call and if both functions return true then it will return true else return false.

<input type="button" 
     onclick="var valFunc1 = func1(); var valFunc2 = func2(); if(valFunc1 == true && valFunc2 ==true) {return true;} else{return false;}" 
     value="Call2Functions" />

Thank you, Vishal Patel

How does one reorder columns in a data frame?

data.table::setcolorder(table, c("Out", "in", "files"))

Most efficient way to find mode in numpy array

Expanding on this method, applied to finding the mode of the data where you may need the index of the actual array to see how far away the value is from the center of the distribution.

(_, idx, counts) = np.unique(a, return_index=True, return_counts=True)
index = idx[np.argmax(counts)]
mode = a[index]

Remember to discard the mode when len(np.argmax(counts)) > 1, also to validate if it is actually representative of the central distribution of your data you may check whether it falls inside your standard deviation interval.

How to get the onclick calling object?

pass in this in the inline click handler

<a href="123.com" onclick="click123(this);">link</a>

or use event.target in the function (according to the W3C DOM Level 2 Event model)

function click123(event)
{
    var a = event.target;
}

But of course, IE is different, so the vanilla JavaScript way of handling this is

function doSomething(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
}

or less verbose

function doSomething(e) {

    e = e || window.event;
    var targ = e.target || e.srcElement || e;
    if (targ.nodeType == 3) targ = targ.parentNode; // defeat Safari bug
}

where e is the event object that is passed to the function in browsers other than IE.

If you're using jQuery though, I would strongly encourage unobtrusive JavaScript and use jQuery to bind event handlers to elements.

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

This works with me :
1- select the cells which shall be be affected by the drop down list .
2- home -> conditional formating -> new rule .
3- format only cells that contain .
4- in format only cells with ... select specific text , in formatting rule "= select Elementary from your drop down list"
if drop list in another sheet then when select Elementary we see "=Sheet3!$F$2" in the new rule , with your own sheet and cell number.
5- format -> fill -> select color -> ok.
6-ok .
do the same for each element in drop down list then you will see the magic !

Checking if a field contains a string

You can do it with the following code.

db.users.findOne({"username" : {$regex : ".*son.*"}});

jQuery: How to get the HTTP status code from within the $.ajax.error method?

If you're using jQuery 1.5, then statusCode will work.

If you're using jQuery 1.4, try this:

error: function(jqXHR, textStatus, errorThrown) {
    alert(jqXHR.status);
    alert(textStatus);
    alert(errorThrown);
}

You should see the status code from the first alert.

Mercurial — revert back to old version and continue from there

Here's the cheat sheet on the commands:

  • hg update changes your working copy parent revision and also changes the file content to match this new parent revision. This means that new commits will carry on from the revision you update to.

  • hg revert changes the file content only and leaves the working copy parent revision alone. You typically use hg revert when you decide that you don't want to keep the uncommited changes you've made to a file in your working copy.

  • hg branch starts a new named branch. Think of a named branch as a label you assign to the changesets. So if you do hg branch red, then the following changesets will be marked as belonging on the "red" branch. This can be a nice way to organize changesets, especially when different people work on different branches and you later want to see where a changeset originated from. But you don't want to use it in your situation.

If you use hg update --rev 38, then changesets 39–45 will be left as a dead end — a dangling head as we call it. You'll get a warning when you push since you will be creating "multiple heads" in the repository you push to. The warning is there since it's kind of impolite to leave such heads around since they suggest that someone needs to do a merge. But in your case you can just go ahead and hg push --force since you really do want to leave it hanging.

If you have not yet pushed revision 39-45 somewhere else, then you can keep them private. It's very simple: with hg clone --rev 38 foo foo-38 you will get a new local clone that only contains up to revision 38. You can continue working in foo-38 and push the new (good) changesets you create. You'll still have the old (bad) revisions in your foo clone. (You are free to rename the clones however you want, e.g., foo to foo-bad and foo-38 to foo.)

Finally, you can also use hg revert --all --rev 38 and then commit. This will create a revision 46 which looks identical to revision 38. You'll then continue working from revision 46. This wont create a fork in the history in the same explicit way as hg update did, but on the other hand you wont get complains about having multiple heads. I would use hg revert if I were collaborating with others who have already made their own work based on revision 45. Otherwise, hg update is more explicit.