Programs & Examples On #Oracle9i

Oracle is a relational database management system (RDBMS) product. Specific releases of the product are known as Oracle9i, Oracle 10g and Oracle 11g. Generally there are two releases within each major version. Questions tagged "oracle9i" are assumed to be specific to this version or features introduced in this version.

Oracle PL/SQL - How to create a simple array variable?

You could just declare a DBMS_SQL.VARCHAR2_TABLE to hold an in-memory variable length array indexed by a BINARY_INTEGER:

   name_array dbms_sql.varchar2_table;
   name_array(1) := 'Tim';
   name_array(2) := 'Daisy';
   name_array(3) := 'Mike';
   name_array(4) := 'Marsha';
   FOR i IN name_array.FIRST .. name_array.LAST
      -- Do something

You could use an associative array (used to be called PL/SQL tables) as they are an in-memory array.

   TYPE employee_arraytype IS TABLE OF employee%ROWTYPE
   employee_array employee_arraytype;
     BULK COLLECT INTO employee_array
     FROM employee
    WHERE department = 10;
   FOR i IN employee_array.FIRST .. employee_array.LAST
      -- Do something

The associative array can hold any make up of record types.

Hope it helps, Ollie.

UTL_FILE.FOPEN() procedure not accepting path for directory?

You need to register the directory with Oracle. fopen takes the name of a directory object, not the path. For example:

(you may need to login as SYS to execute these)



Then, you can refer to it in the call to fopen:

execute sal_status('MY_DIR','vin1.txt');

ORA-01017 Invalid Username/Password when connecting to 11g database from 9i client

If all else fails, try resetting the password to the same thing. I encountered this error and was unable to work around it, but simply resetting the password to the same value resolved the problem.

Get a list of all functions and procedures in an Oracle database

 and owner = 'Schema_name' order by object_name

here 'Schema_name' is a name of schema, example i have a schema named PMIS, so the example will be

and owner = 'PMIS' order by object_name

enter image description here


Best way to do multi-row insert in Oracle?

If you have the values that you want to insert in another table already, then you can Insert from a select statement.

INSERT INTO a_table (column_a, column_b) SELECT column_a, column_b FROM b_table;

Otherwise, you can list a bunch of single row insert statements and submit several queries in bulk to save the time for something that works in both Oracle and MySQL.

@Espo's solution is also a good one that will work in both Oracle and MySQL if your data isn't already in a table.

How to select only 1 row from oracle sql?

"FirstRow" Is a restriction and therefor it's place in the where clause not in the select clause. And it's called rownum

select * from dual where rownum = 1;

ORA-00942: table or view does not exist (works when a separate sql, but does not work inside a oracle function)

Either u dont have permission to that schema/table OR table does exist. Mostly this issue occurred if you are using other schema tables in your stored procedures. Eg. If you are running Stored Procedure from user/schema ABC and in the same PL/SQL there are tables which is from user/schema XYZ. In this case ABC should have GRANT i.e. privileges of XYZ tables

Grant All On To ABC;

Select * From Dba_Tab_Privs Where Owner = 'XYZ'and Table_Name = <Table_Name>;

ORA-12560: TNS:protocol adaptor error

If none the above work, then try this : Modify the LISTENER.ora (mine is found in : oracle\product\11.2.0\dbhome_1\NETWORK\ADMIN\listener.ora) ==> add a custom listener that points to your database(SID), example my SID is XZ0301, so :

## Base XZ03001

E:\oracle\product\11.2.0\dbhome_1)(SID_NAME= XZ03001)))

TCP)(HOST=MyComputerName)(PORT= 1521)))



Restart your machine

For Windows 7, use the following to modify the LISTENER.ora: - Go to Start > All Programs > Accessories - Right click Notepad and then click Run as Administrator . - File>open and navigate to the tnsnames.ora file. - Make the changes then it should allow you to save

@import vs #import - iOS 7

It seems that since XCode 7.x a lot of warnings are coming out when enabling clang module with CLANG_ENABLE_MODULES

Take a look at Lots of warnings when building with Xcode 7 with 3rd party libraries

How do I use raw_input in Python 3

This works in Python 3.x and 2.x:

# Fix Python 2.x.
try: input = raw_input
except NameError: pass
print("Hi " + input("Say something: "))

Insert a row to pandas dataframe

concat() seems to be a bit faster than last row insertion and reindexing. In case someone would wonder about the speed of two top approaches:

In [x]: %%timeit
     ...: df = pd.DataFrame(columns=['a','b'])
     ...: for i in range(10000):
     ...:     df.loc[-1] = [1,2]
     ...:     df.index = df.index + 1
     ...:     df = df.sort_index()

17.1 s ± 705 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [y]: %%timeit
     ...: df = pd.DataFrame(columns=['a', 'b'])
     ...: for i in range(10000):
     ...:     df = pd.concat([pd.DataFrame([[1,2]], columns=df.columns), df])

6.53 s ± 127 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Handling identity columns in an "Insert Into TABLE Values()" statement?

The best practice is to explicitly list the columns:

Insert Into TableName(col1, col2,col2) Values(?, ?, ?)

Otherwise, your original insert will break if you add another column to your table.

Error: Selection does not contain a main type

I am running eclipse from Ubuntu. Had this same problem and was able run the program through terminal. So I just moved the existing public static void main(String[] args) { just below the class declaration (it got automatically formatted by eclipse) and the next launch was successful. Then moved the main method back to where it was before and it worked fine this time.

Pandas split DataFrame by column value

You can use boolean indexing:

df = pd.DataFrame({'Sales':[10,20,30,40,50], 'A':[3,4,7,6,1]})
print (df)
   A  Sales
0  3     10
1  4     20
2  7     30
3  6     40
4  1     50

s = 30

df1 = df[df['Sales'] >= s]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

df2 = df[df['Sales'] < s]
print (df2)
   A  Sales
0  3     10
1  4     20

It's also possible to invert mask by ~:

mask = df['Sales'] >= s
df1 = df[mask]
df2 = df[~mask]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

print (df2)
   A  Sales
0  3     10
1  4     20

print (mask)
0    False
1    False
2     True
3     True
4     True
Name: Sales, dtype: bool

print (~mask)
0     True
1     True
2    False
3    False
4    False
Name: Sales, dtype: bool

"Keep Me Logged In" - the best approach

Implementing a "Keep Me Logged In" feature means you need to define exactly what that will mean to the user. In the simplest case, I would use that to mean the session has a much longer timeout: 2 days (say) instead of 2 hours. To do that, you will need your own session storage, probably in a database, so you can set custom expiry times for the session data. Then you need to make sure you set a cookie that will stick around for a few days (or longer), rather than expire when they close the browser.

I can hear you asking "why 2 days? why not 2 weeks?". This is because using a session in PHP will automatically push the expiry back. This is because a session's expiry in PHP is actually an idle timeout.

Now, having said that, I'd probably implement a harder timeout value that I store in the session itself, and out at 2 weeks or so, and add code to see that and to forcibly invalidate the session. Or at least to log them out. This will mean that the user will be asked to login periodically. Yahoo! does this.

Get table name by constraint name

ALL_CONSTRAINTS describes constraint definitions on tables accessible to the current user.

DBA_CONSTRAINTS describes all constraint definitions in the database.

USER_CONSTRAINTS describes constraint definitions on tables in the current user's schema


What is the path that Django uses for locating and loading templates?

In django 3.1, go to setting of your project and import os

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [

Benefits of inline functions in C++?

Inline function is the optimization technique used by the compilers. One can simply prepend inline keyword to function prototype to make a function inline. Inline function instruct compiler to insert complete body of the function wherever that function got used in code.

Advantages :-

  1. It does not require function calling overhead.

  2. It also save overhead of variables push/pop on the stack, while function calling.

  3. It also save overhead of return call from a function.

  4. It increases locality of reference by utilizing instruction cache.

  5. After in-lining compiler can also apply intra-procedural optimization if specified. This is the most important one, in this way compiler can now focus on dead code elimination, can give more stress on branch prediction, induction variable elimination etc..

To check more about it one can follow this link

How to check Oracle patches are installed?

Maybe you need "sys." before:

select * from sys.registry$history;

Spring Boot - How to get the running port

Just so others who have configured their apps like mine benefit from what I went through...

None of the above solutions worked for me because I have a ./config directory just under my project base with 2 files:

In I have: = dev  # set my default profile to 'dev'

In I have:

server_host = localhost
server_port = 8080

This is so when I run my fat jar from the CLI the *.properties files will be read from the ./config dir and all is good.

Well, it turns out that these properties files completely override the webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT setting in @SpringBootTest in my Spock specs. No matter what I tried, even with webEnvironment set to RANDOM_PORT Spring would always startup the embedded Tomcat container on port 8080 (or whatever value I'd set in my ./config/*.properties files).

The ONLY way I was able to overcome this was by adding an explicit properties = "server_port=0" to the @SpringBootTest annotation in my Spock integration specs:

@SpringBootTest (webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = "server_port=0")

Then, and only then did Spring finally start to spin up Tomcat on a random port. IMHO this is a Spring testing framework bug, but I'm sure they'll have their own opinion on this.

Hope this helped someone.

Is there a way to delete all the data from a topic or delete the topic before every run?

Tested with kafka 0.10

1. stop zookeeper & Kafka server,
2. then go to 'kafka-logs' folder , there you will see list of kafka topic folders, delete folder with topic name
3. go to 'zookeeper-data' folder , delete data inside that.
4. start zookeeper & kafka server again.

Note : if you are deleting topic folder/s inside kafka-logs but not from zookeeper-data folder, then you will see topics are still there.

Export P7b file with all the certificate chain into CER file

The only problem is that any additional certificates in resulted file will not be recognized, as tools don't expect more than one certificate per PEM/DER encoded file. Even openssl itself. Try

openssl x509 -outform DER -in certificate.cer | openssl x509 -inform DER -outform PEM

and see for yourself.

Converting char[] to byte[]

Convert without creating String object:

import java.nio.CharBuffer;
import java.nio.ByteBuffer;
import java.util.Arrays;

byte[] toBytes(char[] chars) {
  CharBuffer charBuffer = CharBuffer.wrap(chars);
  ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
  byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
            byteBuffer.position(), byteBuffer.limit());
  Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
  return bytes;


char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
byte[] bytes = toBytes(chars);
/* do something with chars/bytes */
Arrays.fill(chars, '\u0000'); // clear sensitive data
Arrays.fill(bytes, (byte) 0); // clear sensitive data

Solution is inspired from Swing recommendation to store passwords in char[]. (See Why is char[] preferred over String for passwords?)

Remember not to write sensitive data to logs and ensure that JVM won't hold any references to it.

The code above is correct but not effective. If you don't need performance but want security you can use it. If security also not a goal then do simply String.getBytes. Code above is not effective if you look down of implementation of encode in JDK. Besides you need to copy arrays and create buffers. Another way to convert is inline all code behind encode (example for UTF-8):

val xs: Array[Char] = "A ß € ?  ".toArray
val len = xs.length
val ys: Array[Byte] = new Array(3 * len) // worst case
var i = 0; var j = 0 // i for chars; j for bytes
while (i < len) { // fill ys with bytes
  val c = xs(i)
  if (c < 0x80) {
    ys(j) = c.toByte
    i = i + 1
    j = j + 1
  } else if (c < 0x800) {
    ys(j) = (0xc0 | (c >> 6)).toByte
    ys(j + 1) = (0x80 | (c & 0x3f)).toByte
    i = i + 1
    j = j + 2
  } else if (Character.isHighSurrogate(c)) {
    if (len - i < 2) throw new Exception("overflow")
    val d = xs(i + 1)
    val uc: Int = 
      if (Character.isLowSurrogate(d)) {
        Character.toCodePoint(c, d)
      } else {
        throw new Exception("malformed")
    ys(j) = (0xf0 | ((uc >> 18))).toByte
    ys(j + 1) = (0x80 | ((uc >> 12) & 0x3f)).toByte
    ys(j + 2) = (0x80 | ((uc >>  6) & 0x3f)).toByte
    ys(j + 3) = (0x80 | (uc & 0x3f)).toByte
    i = i + 2 // 2 chars
    j = j + 4
  } else if (Character.isLowSurrogate(c)) {
    throw new Exception("malformed")
  } else {
    ys(j) = (0xe0 | (c >> 12)).toByte
    ys(j + 1) = (0x80 | ((c >> 6) & 0x3f)).toByte
    ys(j + 2) = (0x80 | (c & 0x3f)).toByte
    i = i + 1
    j = j + 3
// check
println(new String(ys, 0, j, "UTF-8"))

Excuse me for using Scala language. If you have problems with converting this code to Java I can rewrite it. What about performance always check on real data (with JMH for example). This code looks very similar to what you can see in JDK[2] and Protobuf[3].

How to parse XML using shellscript?

A rather new project is the xml-coreutils package featuring xml-cat, xml-cp, xml-cut, xml-grep, ...

plotting different colors in matplotlib

for color in ['r', 'b', 'g', 'k', 'm']:
    plot(x, y, color=color)

sql how to cast a select query

You just CAST() this way

SELECT cast(yourNumber as varchar(10))
FROM yourTable

Then if you want to JOIN based on it, you can use:

FROM yourTable t1
INNER JOIN yourOtherTable t2
    on cast(t1.yourNumber as varchar(10)) = t2.yourString

MetadataException when using Entity Framework Entity Connection

I had this problem when moving my .edmx database first model from one project to another.

I simply did the following:

  1. Deleted the connection strings in the app.config or web.config
  2. Deleted the 'Model.edmx'
  3. Re-added the model to the project.

How do I clear a search box with an 'x' in bootstrap 3?

Do not bind to element id, just use the 'previous' input element to clear.


.clear-input > span {
    position: absolute;
    right: 24px;
    top: 10px;
    height: 14px;
    margin: auto;
    font-size: 14px;
    cursor: pointer;
    color: #AAA;


function $(document).ready(function() {
        // Clear the input field before this clear button
        // and give it focus.


HTML Markup, use as much as you like:

<div class="clear-input">
    Pizza: <input type="text" class="form-control">
    <span class="glyphicon glyphicon-remove-circle"></span>

<div class="clear-input">
    Pasta: <input type="text" class="form-control">
    <span class="glyphicon glyphicon-remove-circle"></span>

Python dictionary replace values

You cannot select on specific values (or types of values). You'd either make a reverse index (map numbers back to (lists of) keys) or you have to loop through all values every time.

If you are processing numbers in arbitrary order anyway, you may as well loop through all items:

for key, value in inputdict.items():
    # do something with value
    inputdict[key] = newvalue

otherwise I'd go with the reverse index:

from collections import defaultdict

reverse = defaultdict(list)
for key, value in inputdict.items():

Now you can look up keys by value:

for key in reverse[value]:
    inputdict[key] = newvalue

How do I get sed to read from standard input?

  1. Open the file using vi myfile.csv
  2. Press Escape
  3. Type :%s/replaceme/withthis/
  4. Type :wq and press Enter

Now you will have the new pattern in your file.

How to stop tracking and ignore changes to a file in Git?

after search a long time , find a way do this . alias a git command in in android studio project,before checkout branch revert config file and then skip it ,after checkout branch use sed change config file to my local config. checkoutandmodifylocalproperties = !git update-index --no-skip-worktree && git checkout && git checkout $1 && git update-index --skip-worktree && sed -i '' 's/.*sdk.dir.*/sdk.dir=\\/Users\\/run\\/Library\\/Android\\/sdk/g' && :

Android – Listen For Incoming SMS Messages

If someone referring how to do the same feature (reading OTP using received SMS) on Xamarin Android like me :

  1. Add this code to your AndroidManifest.xml file :

    <receiver android:name=".listener.BroadcastReveiverOTP">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.BROADCAST_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
  2. Then create your BroadcastReveiver class in your Android Project.

    [BroadcastReceiver(Enabled = true)] [IntentFilter(new[] { "android.provider.Telephony.SMS_RECEIVED" }, Priority = (int)IntentFilterPriority.HighPriority)] 
    public class BroadcastReveiverOTP : BroadcastReceiver {
            public static readonly string INTENT_ACTION = "android.provider.Telephony.SMS_RECEIVED";
            protected string message, address = string.Empty;
            public override void OnReceive(Context context, Intent intent)
                if (intent.HasExtra("pdus"))
                    var smsArray = (Java.Lang.Object[])intent.Extras.Get("pdus");
                    foreach (var item in smsArray)
                        var sms = SmsMessage.CreateFromPdu((byte[])item);
                        address = sms.OriginatingAddress;
                        if (address.Equals("NotifyDEMO"))
                            message = sms.MessageBody;
                            string[] pin = message.Split(' ');
                            if (!string.IsNullOrWhiteSpace(pin[0]))
                                    // NOTE : Here I'm passing received OTP to Portable Project using MessagingCenter. So I can display the OTP in the relevant entry field.
                                    MessagingCenter.Send<object, string>(this,MessengerKeys.OnBroadcastReceived, pin[0]);
  3. Register this BroadcastReceiver class in your MainActivity class on Android Project:

    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity {
            // Initialize your class
            private BroadcastReveiverOTP _receiver = new BroadcastReveiverOTP ();
            protected override void OnCreate(Bundle bundle) { 
                    global::Xamarin.Forms.Forms.Init(this, bundle);
                    LoadApplication(new App());
                    // Register your receiver :  RegisterReceiver(_receiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));

How an 'if (A && B)' statement is evaluated?

for logical && both the parameters must be true , then it ll be entered in if {} clock otherwise it ll execute else {}. for logical || one of parameter or condition is true is sufficient to execute if {}.

if( (A) && (B) ){
     //if A and B both are true
if( (A) ||(B) ){
     //if A or B is true 

Using Docker-Compose, how to execute multiple commands

Alpine-based images actually seem to have no bash installed, but you can use sh or ash which link to /bin/busybox.

Example docker-compose.yml:

version: "3"

    restart: unless-stopped
    command: ash -c "flask models init && flask run"

Unable to open debugger port in IntelliJ

You must set CHMOD +x (execute for *.sh or *.bat files). For example, I am using macOS

cd /Users/donhuvy/Documents/tools/apache-tomcat-9.0.12/bin
sudo chmod +x *.sh

Then IntelliJ IDEA, and Apache Tomcat running or debugging just good.


try this:

select convert(varchar, dob2, 101)
select convert(varchar, dob2, 102)
select convert(varchar, dob2, 103)
select convert(varchar, dob2, 104)
select convert(varchar, dob2, 105)
select convert(varchar, dob2, 106)
select convert(varchar, dob2, 107)
select convert(varchar, dob2, 108)
select convert(varchar, dob2, 109)
select convert(varchar, dob2, 110)
select convert(varchar, dob2, 111)
select convert(varchar, dob2, 112)
select convert(varchar, dob2, 113)


Exit a Script On Error

exit 1 is all you need. The 1 is a return code, so you can change it if you want, say, 1 to mean a successful run and -1 to mean a failure or something like that.

Bootstrap col-md-offset-* not working

Changing col-md-offset-* to offset-md-* worked for me

Setting a minimum/maximum character count for any character using a regular expression

Like this: .

The . means any character except newline (which sometimes is but often isn't included, check your regex flavour).

You can rewrite your expression as ^.{1,35}$, which should match any line of length 1-35.

Pandas DataFrame to List of Lists

I don't know if it will fit your needs, but you can also do:

>>> lol = df.values
>>> lol
array([[1, 2, 3],
       [3, 4, 5]])

This is just a numpy array from the ndarray module, which lets you do all the usual numpy array things.

How can I check if the current date/time is past a set date/time?

There's also the DateTime class which implements a function for comparison operators.

// $now = new DateTime();
$dtA = new DateTime('05/14/2010 3:00PM');
$dtB = new DateTime('05/14/2010 4:00PM');

if ( $dtA > $dtB ) {
  echo 'dtA > dtB';
else {
  echo 'dtA <= dtB';

Why does using an Underscore character in a LIKE filter give me all the results?

You can write the query as below:

WHERE managerid LIKE '\_%' escape '\'
AND managername LIKE '%\_%' escape '\';

it will solve your problem.

Altering a column: null to not null

For Oracle 11g, I was able to change the column attribute as follows:

ALTER TABLE tablename MODIFY columnname datatype NOT NULL;

Otherwise abatichev's answer seemed good. You can't repeat the alter - it complains (at least in SQL Developer) that the column is already not null.

How to get selenium to wait for ajax response?

Here's a groovy version based on Morten Christiansen's answer.

void waitForAjaxCallsToComplete() {
            { return getJavaScriptFunction(driver, "return (window.jQuery || {active : false}).active") },
            "Ajax calls did not complete before timeout."

static void repeatUntil(Closure runUntilTrue, String errorMessage, int pollFrequencyMS = 250, int timeOutSeconds = 10) {
    def today = new Date()
    def end = today.time + timeOutSeconds
    def complete = false;

    while (today.time < end) {
        if (runUntilTrue()) {
            complete = true;

    if (!complete)
        throw new TimeoutException(errorMessage);

static String getJavaScriptFunction(WebDriver driver, String jsFunction) {
    def jsDriver = driver as JavascriptExecutor

What is the most efficient way to get first and last line of a text file?

Nobody mentioned using reversed:

last_line_of_file =

This certificate has an invalid issuer Apple Push Services

You need to search the World from the top right search bar and delete the expired certificate. Make sure you selected Login and All items.

Enter image description here

How can I check if a background image is loaded?

    finished: function() {
       // ...
    each: function() {
       // ...
    waitForAll: true

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

If you want to use valueChangeListener, you need to submit the form every time a new option is chosen. Something like this:

<p:selectOneMenu value="#{mymb.employee}" onchange="submit()"
                 valueChangeListener="#{mymb.handleChange}" >
    <f:selectItems value="#{mymb.employeesList}" var="emp"
                   itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeID}" />

public void handleChange(ValueChangeEvent event){  
    System.out.println("New value: " + event.getNewValue());

Or else, if you want to use <p:ajax>, it should look like this:

<p:selectOneMenu value="#{mymb.employee}" >
    <p:ajax listener="#{mymb.handleChange}" />
    <f:selectItems value="#{mymb.employeesList}" var="emp"
                   itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeID}" />

private String employeeID;

public void handleChange(){  
    System.out.println("New value: " + employee);

One thing to note is that in your example code, I saw that the value attribute of your <p:selectOneMenu> is #{mymb.employeesList} which is the same as the value of <f:selectItems>. The value of your <p:selectOneMenu> should be similar to my examples above which point to a single employee, not a list of employees.

Filtering a data frame by values in a column

Try this:

subset(studentdata, Drink=='water')

that should do it.

How to commit changes to a new branch

git checkout -b your-new-branch

git add <files>

git commit -m <message>

First, checkout your new branch. Then add all the files you want to commit to staging. Lastly, commit all the files you just added. You might want to do a git push origin your-new-branch afterward so your changes show up on the remote.

Regular expression to extract text between square brackets

Just in case, you might have had unbalanced brackets, you can likely design some expression with recursion similar to,


which of course, it would relate to the language or RegEx engine that you might be using.

RegEx Demo 1

Other than that,


RegEx Demo 2



RegEx Demo 3

are good options to explore.

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

RegEx Circuit visualizes regular expressions:

enter image description here


const regex = /\[([^\]\[\r\n]*)\]/gm;_x000D_
const str = `This is a [sample] string with [some] special words. [another one]_x000D_
This is a [sample string with [some special words. [another one_x000D_
This is a [sample[sample]] string with [[some][some]] special words. [[another one]]`;_x000D_
let m;_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
    // This is necessary to avoid infinite loops with zero-width matches_x000D_
    if (m.index === regex.lastIndex) {_x000D_
    // The result can be accessed through the `m`-variable._x000D_
    m.forEach((match, groupIndex) => {_x000D_
        console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_


Regular expression to match balanced parentheses

How to zoom div content using jquery?

@Gadde - your answer was very helpful. Thank you! I needed a "Maps"-like zoom for a div and was able to produce the feel I needed with your post. My criteria included the need to have the click repeat and continue to zoom out/in with each click. Below is my final result.

    var currentZoom = 1.0;

    $(document).ready(function () {
            function () {
                $('#divName').animate({ 'zoom': currentZoom += .1 }, 'slow');
            function () {
                $('#divName').animate({ 'zoom': currentZoom -= .1 }, 'slow');
            function () {
                currentZoom = 1.0
                $('#divName').animate({ 'zoom': 1 }, 'slow');

Remove an entire column from a data.frame in R

With this you can remove the column and store variable into another variable.

df = subset(data, select = -c(genome) )

How Best to Compare Two Collections in Java and Act on Them?

I'd move to lists and solve it this way:

  1. Sort both lists by id ascending using custom Comparator if objects in lists aren't Comparable
  2. Iterate over elements in both lists like in merge phase in merge sort algorithm, but instead of merging lists, you check your logic.

The code would be more or less like this:

/* Main method */
private void execute(Collection<Foo> oldSet, Collection<Foo> newSet) {
  List<Foo> oldList = asSortedList(oldSet);
  List<Foo> newList = asSortedList(newSet);

  int oldIndex = 0;
  int newIndex = 0;
  // Iterate over both collections but not always in the same pace
  while( oldIndex < oldList.size() 
      && newIndex < newIndex.size())  {
    Foo oldObject = oldList.get(oldIndex);
    Foo newObject = newList.get(newIndex);

    // Your logic here
    if(oldObject.getId() < newObject.getId()) {
    } else if( oldObject.getId() > newObject.getId() ) {
    } else if( oldObject.getId() == newObject.getId() 
            && isModified(oldObject, newObject) ) {
      doUpdate(oldObject, newObject);
    } else {
  }// while

  // Check if there are any objects left in *oldList* or *newList*

  for(; oldIndex < oldList.size(); oldIndex++ ) {
    doRemove( oldList.get(oldIndex) );  
  }// for( oldIndex )

  for(; newIndex < newList.size(); newIndex++ ) {
    doAdd( newList.get(newIndex) );
  }// for( newIndex ) 
}// execute( oldSet, newSet )

/** Create sorted list from collection 
    If you actually perform any actions on input collections than you should 
    always return new instance of list to keep algorithm simple.
private List<Foo> asSortedList(Collection<Foo> data) {
  List<Foo> resultList;
  if(data instanceof List) {
     resultList = (List<Foo>)data;
  } else {
     resultList = new ArrayList<Foo>(data);
  return resultList;

What is the right way to write my script 'src' url for a local development environment?

This is an old post but...

You can reference the working directory (the folder the .html file is located in) with ./, and the directory above that with ../

Example directory structure:

- index.html
- script2.js
- js/
   - script.js

To load script.js from inside index.html:

<script type="text/javascript" src="./js/script.js">

This goes to the current working directory (location of index.html) and then to the js folder, and then finds the script.

You could also specify ../ to go one directory above the working directory, to load things from there. But that is unusual.

Selecting Values from Oracle Table Variable / Array?

In Oracle, the PL/SQL and SQL engines maintain some separation. When you execute a SQL statement within PL/SQL, it is handed off to the SQL engine, which has no knowledge of PL/SQL-specific structures like INDEX BY tables.

So, instead of declaring the type in the PL/SQL block, you need to create an equivalent collection type within the database schema:

CREATE OR REPLACE TYPE array is table of number;

Then you can use it as in these two examples within PL/SQL:

SQL> l
  1  declare
  2    p  array := array();
  3  begin
  4    for i in (select level from dual connect by level < 10) loop
  5      p.extend;
  6      p(p.count) := i.level;
  7    end loop;
  8    for x in (select column_value from table(cast(p as array))) loop
  9       dbms_output.put_line(x.column_value);
 10    end loop;
 11* end;
SQL> /

PL/SQL procedure successfully completed.

SQL> l
  1  declare
  2    p  array := array();
  3  begin
  4    select level bulk collect into p from dual connect by level < 10;
  5    for x in (select column_value from table(cast(p as array))) loop
  6       dbms_output.put_line(x.column_value);
  7    end loop;
  8* end;
SQL> /

PL/SQL procedure successfully completed.

Additional example based on comments

Based on your comment on my answer and on the question itself, I think this is how I would implement it. Use a package so the records can be fetched from the actual table once and stored in a private package global; and have a function that returns an open ref cursor.

  FUNCTION get_p_cursor RETURN sys_refcursor;
END p_cache;


  cache_array  array;

  FUNCTION get_p_cursor RETURN sys_refcursor IS
    pCursor  sys_refcursor;
    OPEN pCursor FOR SELECT * from TABLE(CAST(cache_array AS array));
    RETURN pCursor;
  END get_p_cursor;

  -- Package initialization runs once in each session that references the package
    SELECT level BULK COLLECT INTO cache_array FROM dual CONNECT BY LEVEL < 10;
  END p_cache;

Escape quote in web.config connection string

if &quot; isn't working then try &#34; instead.

SELECT CONVERT(VARCHAR(10), GETDATE(), 110) what is the meaning of 110 here?

That number indicates Date and Time Styles

You need to look at CAST and CONVERT (Transact-SQL). Here you can find the meaning of all these Date and Time Styles.

Styles with century (e.g. 100, 101 etc) means year will come in yyyy format. While styles without century (e.g. 1,7,10) means year will come in yy format.

You can also refer to SQL Server Date Formats. Here you can find all date formats with examples.

Show which git tag you are on?

When you check out a tag, you have what's called a "detached head". Normally, Git's HEAD commit is a pointer to the branch that you currently have checked out. However, if you check out something other than a local branch (a tag or a remote branch, for example) you have a "detached head" -- you're not really on any branch. You should not make any commits while on a detached head.

It's okay to check out a tag if you don't want to make any edits. If you're just examining the contents of files, or you want to build your project from a tag, it's okay to git checkout my_tag and work with the files, as long as you don't make any commits. If you want to start modifying files, you should create a branch based on the tag:

$ git checkout -b my_tag_branch my_tag

will create a new branch called my_tag_branch starting from my_tag. It's safe to commit changes on this branch.

Triggering a checkbox value changed event in DataGridView

Using the .EditedFormattedValue property solves the problem

To be notified each time a checkbox in a cell toggles a value when clicked, you can use the CellContentClick event and access the preliminary cell value .EditedFormattedValue.

As the event is fired the .EditedFormattedValue is not yet applied visually to the checkbox and not yet committed to the .Value property.

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
   var checkbox = dataGridView1.CurrentCell as DataGridViewCheckBoxCell;

   bool isChecked = (bool)checkbox.EditedFormattedValue;


The event fires on each Click and the .EditedFormattedValue toggles

Parse date string and change format

>>> from_date="Mon Feb 15 2010"
>>> import time                
>>> conv=time.strptime(from_date,"%a %b %d %Y")
>>> time.strftime("%d/%m/%Y",conv)

Working with dictionaries/lists in R

You do not even need lists if your "number" values are all of the same mode. If I take Dirk Eddelbuettel's example:

> foo <- c(12, 22, 33)
> names(foo) <- c("tic", "tac", "toe")
> foo
tic tac toe
 12  22  33
> names(foo)
[1] "tic" "tac" "toe"

Lists are only required if your values are either of mixed mode (for example characters and numbers) or vectors.

For both lists and vectors, an individual element can be subsetted by name:

> foo["tac"]

Or for a list:

> foo[["tac"]]
[1] 22

What is the difference between properties and attributes in HTML?

Difference HTML properties and attributes:

Let's first look at the definitions of these words before evaluating what the difference is in HTML:

English definition:

  • Attributes are referring to additional information of an object.
  • Properties are describing the characteristics of an object.

In HTML context:

When the browser parses the HTML, it creates a tree data structure wich basically is an in memory representation of the HTML. It the tree data structure contains nodes which are HTML elements and text. Attributes and properties relate to this is the following manner:

  • Attributes are additional information which we can put in the HTML to initialize certain DOM properties.
  • Properties are formed when the browser parses the HTML and generates the DOM. Each of the elements in the DOM have their own set of properties which are all set by the browser. Some of these properties can have their initial value set by HTML attributes. Whenever a DOM property changes which has influence on the rendered page, the page will be immediately re rendered

It is also important to realize that the mapping of these properties is not 1 to 1. In other words, not every attribute which we give on an HTML element will have a similar named DOM property.

Furthermore have different DOM elements different properties. For example, an <input> element has a value property which is not present on a <div> property.


Let's take the following HTML document:

 <!DOCTYPE html>
  <meta charset="utf-8">  <!-- charset is a attribute -->
  <meta name="viewport" content="width=device-width"> <!-- name and content are attributes -->
  <title>JS Bin</title>
<div id="foo" class="bar foobar">hi</div> <!-- id and class are attributes -->

Then we inspect the <div>, in the JS console:


We see the following DOM properties (chrome devtools, not all properties shown):

html properties and attributes

  • We can see that the attribute id in the HTML is now also a id property in the DOM. The id has been initialized by the HTML (although we could change it with javascript).
  • We can see that the class attribute in the HTML has no corresponding class property (class is reserved keyword in JS). But actually 2 properties, classList and className.

Force SSL/https using .htaccess and mod_rewrite

I'd just like to point out that Apache has the worst inheritance rules when using multiple .htaccess files across directory depths. Two key pitfalls:

  • Only the rules contained in the deepest .htaccess file will be performed by default. You must specify the RewriteOptions InheritDownBefore directive (or similar) to change this. (see question)
  • The pattern is applied to the file path relative to the subdirectory and not the upper directory containing the .htaccess file with the given rule. (see discussion)

This means the suggested global solution on the Apache Wiki does not work if you use any other .htaccess files in subdirectories. I wrote a modified version that does:

RewriteEngine On
# This will enable the Rewrite capabilities

RewriteOptions InheritDownBefore
# This prevents the rule from being overrided by .htaccess files in subdirectories.

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [QSA,R,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.
# i.e. to

VB.NET Connection string (Web.Config, App.Config)

Connection in APPConfig

  <add name="ConnectionString" connectionString="Data Source=;Initial Catalog=Login;Persist Security Info=True;User ID=sa;"   providerName="System.Data.SqlClient" />

In Class.Cs

public string ConnectionString
        return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

How to connect to mysql with laravel?

You probably only forgot to create database. Enter your PHPMyAdmin and do it from there.

Edit: Definitely don't go with Maulik's answer. Not only it is using mysql_ extenstion (which is commonly recognized bad practice), Laravel is also taking care of your connections using PDO.

Simulating Key Press C#

Here's an example...

static class Program
    public static extern int SetForegroundWindow(IntPtr hWnd);

    static void Main()
            Process [] processes = Process.GetProcessesByName("iexplore");

            foreach(Process proc in processes)


a better one... less anoying...

static class Program
    const UInt32 WM_KEYDOWN = 0x0100;
    const int VK_F5 = 0x74;

    static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);

    static void Main()
            Process [] processes = Process.GetProcessesByName("iexplore");

            foreach(Process proc in processes)
                PostMessage(proc.MainWindowHandle, WM_KEYDOWN, VK_F5, 0);


Setting up a JavaScript variable from Spring model by using Thymeleaf

Another way to do it is to create a dynamic javascript returned by a java controller like it is written here in the thymeleaf forum:

One way to handle this is to create a dynamic javascript file with the URLs embedded in it. Here are the steps (if you are using Spring MVC)

@RequestMapping(path = {"/dynamic.js"}, method = RequestMethod.GET, produces = "application/javascript")
@ResponseStatus(value = HttpStatus.OK)
public String dynamicJS(HttpServletRequest request) {

        return "Your javascript code....";



How to get the date 7 days earlier date from current date in Java

You can use Calendar class :

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -7);
System.out.println("Date = "+ cal.getTime());

But as @Sean Patrick Floyd mentioned , Joda-time is the best Java library for Date.

How to print a groupby object

I found a tricky way, just for brainstorm, see the code:

df['a'] = df['A']  # create a shadow column for MultiIndexing
df.sort_values('A', inplace=True)
df.set_index(["A","a"], inplace=True)

the output:

A     a
one   one    0
      one    1
      one    5
three three  3
      three  4
two   two    2

The pros is so easy to print, as it returns a dataframe, instead of Groupby Object. And the output looks nice. While the con is that it create a series of redundant data.

Can I pass an argument to a VBScript (vbs file launched with cscript)?

You can use WScript.Arguments to access the arguments passed to your script.

Calling the script:

cscript.exe test.vbs "C:\temp\"

Inside your script:

Set File = FSO.OpenTextFile(WScript.Arguments(0) &"\test.txt", 2, True)

Don't forget to check if there actually has been an argument passed to your script. You can do so by checking the Count property:

if WScript.Arguments.Count = 0 then
    WScript.Echo "Missing parameters"
end if

If your script is over after you close the file then there is no need to set the variables to Nothing. The resources will be cleaned up automatically when the cscript.exe process terminates. Setting a variable to Nothing usually is only necessary if you explicitly want to free resources during the execution of your script. In that case, you would set variables which contain a reference to a COM object to Nothing, which would release the COM object before your script terminates. This is just a short answer to your bonus question, you will find more information in these related questions:

Is there a need to set Objects to Nothing inside VBA Functions

When must I set a variable to “Nothing” in VB6?

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

A reference to an element will never look "falsy", so leaving off the explicit null check is safe.

Javascript will treat references to some values in a boolean context as false: undefined, null, numeric zero and NaN, and empty strings. But what getElementById returns will either be an element reference, or null. Thus if the element is in the DOM, the return value will be an object reference, and all object references are true in an if () test. If the element is not in the DOM, the return value would be null, and null is always false in an if () test.

It's harmless to include the comparison, but personally I prefer to keep out bits of code that don't do anything because I figure every time my finger hits the keyboard I might be introducing a bug :)

Note that those using jQuery should not do this:

if ($('#something')) { /* ... */ }

because the jQuery function will always return something "truthy" — even if no element is found, jQuery returns an object reference. Instead:

if ($('#something').length) { /* ... */ }

edit — as to checking the value of an element, no, you can't do that at the same time as you're checking for the existence of the element itself directly with DOM methods. Again, most frameworks make that relatively simple and clean, as others have noted in their answers.

Quoting backslashes in Python string literals

What Harley said, except the last point - it's not actually necessary to change the '/'s into '\'s before calling open. Windows is quite happy to accept paths with forward slashes.

infile = open('c:/folder/subfolder/file.txt')

The only time you're likely to need the string normpathed is if you're passing to to another program via the shell (using os.system or the subprocess module).

What is the iPad user agent?

From Simulator 3.2 final:

Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B367 Safari/531.21.10

Changing nav-bar color after scrolling?

I use WordPress which comes with Underscore. So when you register your theme scripts, you would use 'jquery' and 'underscore' as the handle for the array of the dependancies. If you are not using WordPress, then make sure that you load both the jQuery framework and Underscore before your scripts.


To make this demo (remember it requires both jQuery and Underscore).


<header class="site-header">
  <div class="logo">

  Content with a forced height for scrolling.  Content with a forced height for scrolling. Content with a forced height for scrolling. Content with a forced height for scrolling. Content with a forced height for scrolling. Content with a forced height for scrolling. Content with a forced height for scrolling


html {
    margin: 0;
    padding: 0;
    font: 100%/180% sans-serif;
    background: #eee;

html {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;

*::after {
    box-sizing: inherit;

article {
    height: 2000px;
    padding: 5%;
    background: #fff;
    margin: 2% auto;
    max-width: 900px;
    box-shadow: 0px 0px 30px 0px rgba(0, 0, 0, 0.10);

.site-header {
    background: #fff;
    padding: 20px 5%;
    box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.23);
    transition: all .5s ease-in-out;
    -web-kit-position: sticky;
    position: sticky;
    top: 0;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-direction: row;
    flex-direction: row;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;


.logo {
    background-image: url('the-path-to-the-logo.svg');
    background-repeat: no-repeat;
    background-position: center center;
    width: 200px;
    height: 60px;
    background-size: contain;
    transition: width .5s ease-in-out, height .5s ease-in-out;

.site-header nav {
    text-align: right;
    -webkit-box-flex: 1;
    -ms-flex-positive: 1;
    flex-grow: 1;
    -ms-flex-preferred-size: 0;
    flex-basis: 0;
} {
    opacity: .8;
    background: tomato;
    padding: 10px 5%;
} .logo {
    height: 40px;
    width: 100px;


( function( window, $, undefined ) {

    'use strict';

    ////////////// Begin jQuery and grab the $ ////////////////////////////////////////

    $(document).ready(function() {

      function is_scrolling() {

        var $element = $('.site-header'),
            $nav_height = $element.outerHeight( true );

        if ($(this).scrollTop() >= $nav_height ) { //if scrolling is equal to or greater than the nav height add a class

          $element.addClass( 'is-scrolling');

        } else { //is back at the top again, remove the class

          $element.removeClass( 'is-scrolling');

      }//end is_scrolling();

    $(window).scroll(_.throttle(is_scrolling, 200));

  }); //* end ready

})(this, jQuery);

Android: keep Service running when app is killed

The reason for this is that you are trying to use an IntentService. Here is the line from the API Docs

The IntentService does the following:

Stops the service after all start requests have been handled, so you never have to call stopSelf().

Thus if you want your service to run indefinitely i suggest you extend the Service class instead. However this does not guarantee your service will run indefinitely. Your service will still have a chance of being killed by the kernel in a state of low memory if it is low priority.So you have two options:
1)Keep it running in the foreground by calling the startForeground() method.
2)Restart the service if it gets killed. Here is a part of the example from the docs where they talk about restarting the service after it is killed

 public int onStartCommand(Intent intent, int flags, int startId) {
      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

      // For each start request, send a message to start a job and deliver the 
      // start ID so we know which request we're stopping when we finish the job 
      Message msg = mServiceHandler.obtainMessage();
      msg.arg1 = startId;

      // If we get killed, after returning from here, restart 
      return START_STICKY;

Regex matching in a Bash if statement

In case someone wanted an example using variables...


# Only continue for 'develop' or 'release/*' branches

if [[ $BRANCH =~ $BRANCH_REGEX ]];

How do I add a ToolTip to a control?

Drag a tooltip control from the toolbox onto your form. You don't really need to give it any properties other than a name. Then, in the properties of the control you wish to have a tooltip on, look for a new property with the name of the tooltip control you just added. It will by default give you a tooltip when the cursor hovers the control.

How to change font size on part of the page in LaTeX?

        % how to set font size here to 10 px ?  

Access files stored on Amazon S3 through web browser

I found this related question: Directory Listing in S3 Static Website

As it turns out, if you enable public read for the whole bucket, S3 can serve directory listings. Problem is they are in XML instead of HTML, so not very user-friendly.

There are three ways you could go for generating listings:

  • Generate index.html files for each directory on your own computer, upload them to s3, and update them whenever you add new files to a directory. Very low-tech. Since you're saying you're uploading build files straight from Travis, this may not be that practical since it would require doing extra work there.

  • Use a client-side S3 browser tool.

  • Use a server-side browser tool.

    • s3browser (PHP)
    • s3index Scala. Going by the existence of a Procfile, it may be readily deployable to Heroku. Not sure since I don't have any experience with Scala.

from unix timestamp to datetime

If using react:

import Moment from 'react-moment';
Moment.globalFormat = 'D MMM YYYY';


<td><Moment unix>{1370001284}</Moment></td>

How can I disable a specific LI element inside a UL?

I usualy use <li> to include <a> link. I disabled click action writing like this; You may not include <a> link, then you will ignore my post.

a.noclick       {_x000D_
  pointer-events: none;_x000D_
<a class="noclick" href="#">this is disabled</a>

Python requests - print entire http request (raw)? content:

import logging
import pytest
import requests
from requests_toolbelt.utils import dump

def print_raw_http(response):
    data = dump.dump_all(response, request_prefix=b'', response_prefix=b'')
    return '\n' * 2 + data.decode('utf-8')

def logger():
    log = logging.getLogger()
    return log

def test_print_response(logger):
    session = requests.Session()
    response = session.get('')
    assert response.status_code == 300, logger.warning(print_raw_http(response)) content:

from flask import Flask
app = Flask(__name__)

def hello_world():
    return 'Hello, World!'


 $ python -m flask
 $ python -m pytest


------------------------------ Captured log call ------------------------------
DEBUG Starting new HTTP connection (1):
DEBUG "GET / HTTP/1.1" 200 13

GET / HTTP/1.1
User-Agent: python-requests/2.23.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive

HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 13
Server: Werkzeug/1.0.1 Python/3.6.8
Date: Thu, 24 Sep 2020 21:00:54 GMT

Hello, World!

Finding moving average from data points in Python

A moving average is a convolution, and numpy will be faster than most pure python operations. This will give you the 10 point moving average.

import numpy as np
smoothed = np.convolve(data, np.ones(10)/10)

I would also strongly suggest using the great pandas package if you are working with timeseries data. There are some nice moving average operations built in.

Javascript search inside a JSON object

I adapted regex to work with JSON.

First, stringify the JSON object. Then, you need to store the starts and lengths of the matched substrings. For example:

"matched".search("ch") // yields 3

For a JSON string, this works exactly the same (unless you are searching explicitly for commas and curly brackets in which case I'd recommend some prior transform of your JSON object before performing regex (i.e. think :, {, }).

Next, you need to reconstruct the JSON object. The algorithm I authored does this by detecting JSON syntax by recursively going backwards from the match index. For instance, the pseudo code might look as follows:

find the next key preceding the match index, call this theKey
then find the number of all occurrences of this key preceding theKey, call this theNumber
using the number of occurrences of all keys with same name as theKey up to position of theKey, traverse the object until keys named theKey has been discovered theNumber times
return this object called parentChain

With this information, it is possible to use regex to filter a JSON object to return the key, the value, and the parent object chain.

You can see the library and code I authored at

Case-Insensitive List Search

Based on Lance Larsen answer - here's an extension method with the recommended string.Compare instead of string.Equals

It is highly recommended that you use an overload of String.Compare that takes a StringComparison parameter. Not only do these overloads allow you to define the exact comparison behavior you intended, using them will also make your code more readable for other developers. [Josh Free @ BCL Team Blog]

public static bool Contains(this List<string> source, string toCheck, StringComparison comp)
       source != null &&
       !string.IsNullOrEmpty(toCheck) &&
       source.Any(x => string.Compare(x, toCheck, comp) == 0);

How to set a header for a HTTP GET request, and trigger file download?



<!-- placeholder , 
    `click` download , `.remove()` options ,
     at js callback , following js 


        $(document).ready(function () {
                // `url` 
                url: '/echo/json/',
                type: "POST",
                dataType: 'json',
                // `file`, data-uri, base64
                data: {
                    json: JSON.stringify({
                        "file": "data:text/plain;base64,YWJj"
                // `custom header`
                headers: {
                    "x-custom-header": 123
                beforeSend: function (jqxhr) {
                    alert("custom headers" + JSON.stringify(this.headers));
                success: function (data) {
                    // `file download`
                        "href": data.file,
                            "download": "file.txt"
                error: function (jqxhr, textStatus, errorThrown) {
                  console.log(textStatus, errorThrown)


How to find tag with particular text with Beautiful Soup?

result = soup.find('strong', text='text I am looking for').text

Ignoring a class property in Entity Framework 4.1 Code First

You can use the NotMapped attribute data annotation to instruct Code-First to exclude a particular property

public class Customer
    public int CustomerID { set; get; }
    public string FirstName { set; get; } 
    public string LastName{ set; get; } 
    public int Age { set; get; }

[NotMapped] attribute is included in the System.ComponentModel.DataAnnotations namespace.

You can alternatively do this with Fluent API overriding OnModelCreating function in your DBContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
   modelBuilder.Entity<Customer>().Ignore(t => t.LastName);

The version I checked is EF 4.3, which is the latest stable version available when you use NuGet.

Edit : SEP 2017

Asp.NET Core(2.0)

Data annotation

If you are using core (2.0 at the time of this writing), The [NotMapped] attribute can be used on the property level.

public class Customer
    public int Id { set; get; }
    public string FirstName { set; get; } 
    public string LastName { set; get; } 
    public int FullName { set; get; }

Fluent API

public class SchoolContext : DbContext
    public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
    protected override void OnModelCreating(ModelBuilder modelBuilder)
        modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
    public DbSet<Customer> Customers { get; set; }

List comprehension with if statement

You put the if at the end:

[y for y in a if y not in b]

List comprehensions are written in the same order as their nested full-specified counterparts, essentially the above statement translates to:

outputlist = []
for y in a:
    if y not in b:

Your version tried to do this instead:

outputlist = []
if y not in b:
    for y in a:

but a list comprehension must start with at least one outer loop.

How do I declare a global variable in VBA?

To use global variables, Insert New Module from VBA Project UI and declare variables using Global

Global iRaw As Integer
Global iColumn As Integer

Best way to return a value from a python script

If you want your script to return values, just do return [1,2,3] from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:

Return values (from a wrapping-function)

(again, this would have to be run by a separate Python script and be imported in order to even do any good):

import ...
def main():
    # calculate stuff
    return [1,2,3]

Exit codes as indicators

(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)

import sys
# calculate and stuff

And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.

(os._exit(100) also works, and is a bit more forceful)

Stdout as your relay

If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.

import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')

Are you running your script in a controlled scheduling environment then exit codes are the best way to go.

Files as conveyors

There's also the option to simply write information to a file, and store the result there.

# calculate
with open('finish.txt', 'wb') as fh:

And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.

Sockets as conveyors

If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.

Find a value in an array of objects in Javascript

You can do it with a simple loop:

var obj = null;    
for (var i = 0; i < array.length; i++) {
    if (array[i].name == "string 1") {
        obj = array[i];

How can I set a website image that will show as preview on Facebook?

If you're using Weebly, start by viewing the published site and right-clicking the image to Copy Image Address. Then in Weebly, go to Edit Site, Pages, click the page you wish to use, SEO Settings, under Header Code enter the code from Shef's answer:

<meta property="og:image" content="/uploads/..." />

just replacing /uploads/... with the copied image address. Click Publish to apply the change.

You can skip the part of Shef's answer about namespace, because that's already set by default in Weebly.

AttributeError: 'str' object has no attribute 'strftime'

You should use datetime object, not str.

>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')

To get the datetime object from the string, use datetime.datetime.strptime:

>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')

Using routes in Express-js

So, after I created my question, I got this related list on the right with a similar issue: Organize routes in Node.js.

The answer in that post linked to the Express repo on GitHub and suggests to look at the 'route-separation' example.

This helped me change my code, and I now have it working. - Thanks for your comments.

My implementation ended up looking like this;

I require my routes in the app.js:

var express = require('express')
  , site = require('./site')
  , wiki = require('./wiki');

And I add my routes like this:

app.get('/', site.index);
app.get('/wiki/:id/edit', wiki.edit);

I have two files called wiki.js and site.js in the root of my app, containing this:

exports.edit = function(req, res) {

    var wiki_entry =;

    res.render('wiki/edit', {
        title: 'Editing Wiki',
        wiki: wiki_entry

In Git, how do I figure out what my current revision is?

There are many ways git log -1 is the easiest and most common, I think

Git Remote: Error: fatal: protocol error: bad line length character: Unab

TL;DR: Do not omit username@ in your remote URLs when on Windows.

On Linux and on Windows with the default ssh, you can omit the username from remote URLs, like so:

git clone server-name:/srv/git/repo-name

Because ssh's default behavior is to just use whatever username you're currently logged in with. If you're on Windows and have set up git to use plink.exe so that you can use the key loaded in your pageant, then this will not work, because plink does not have this same automatic username behavior, resulting in those cryptic error messages, because it will prompt for the username:

$ plink server-name
login as: _


$ plink username@server-name
...logs you in...

If you already cloned a repository somehow you can fix the remotes in your .git/config by adding the username@ to the remote URL.

google chrome extension :: console.log() from background page?

The simplest solution would be to add the following code on the top of the file. And than you can use all full Chrome console api as you would normally.

 console = chrome.extension.getBackgroundPage().console;
// for instance, console.assert(1!=1) will return assertion error
// console.log("msg") ==> prints msg
// etc

What is the difference between `` and `Enum.toString()`?

Use toString() when you want to present information to a user (including a developer looking at a log). Never rely in your code on toString() giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString() return, then it was already broken.

If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overridden.

Replace string in text file using PHP

This works like a charm, fast and accurate:

function replace_string_in_file($filename, $string_to_replace, $replace_with){
    $content_chunks=explode($string_to_replace, $content);
    $content=implode($replace_with, $content_chunks);
    file_put_contents($filename, $content);


replace_string_in_file($filename, $string_to_replace, $replace_with);

// never forget about EXPLODE when it comes about string parsing // it's a powerful and fast tool

jQuery exclude elements with certain class in selector

use this..

$(".content_box a:not('.button')")

CREATE DATABASE permission denied in database 'master' (EF code-first)

As the error suggests, the SQL login has no permission to create database. Permissions are granted when the login have the required roles. The role having permission to create, alter and drop database is dbCreator. Therefore it should be added to the login to solve the problem. It can be done on SQL Management Studio by right-clicking the user then go to Properties>Server Roles. I encountered the same error and resolved it by doing exactly that.

Is Android using NTP to sync time?

I know about Android ICS that it uses a custom service called: NetworkTimeUpdateService. This service also implements a NTP time synchronization via the NtpTrustedTime singleton.

In NtpTrustedTime the default NTP server is requested from the Android system string source:

final Resources res = context.getResources();

final String defaultServer = res.getString(

If the automatic time sync option in the system settings is checked and no NITZ time service is available then the time will be synchronized with the NTP server from

To get the value of you can use the following method:

    final Resources res = this.getResources();
    final int id = Resources.getSystem().getIdentifier(
                       "config_ntpServer", "string","android");
    final String defaultServer = res.getString(id);

jQuery or Javascript - how to disable window scroll without overflow:hidden;

CSS 'fixed' solution (like Facebook does):

body_temp = $("<div class='body_temp' />")
    .css('position', 'fixed')
    .css('top', "-" + scrolltop + 'px')

to toggle to normal state:

var scrolltop = Math.abs($('.body_temp').position().top);

How to overcome root domain CNAME restrictions?

The reason this question still often arises is because, as you mentioned, somewhere somehow someone presumed as important wrote that the RFC states domain names without subdomain in front of them are not valid. If you read the RFC carefully, however, you'll find that this is not exactly what it says. In fact, RFC 1912 states:

Don't go overboard with CNAMEs. Use them when renaming hosts, but plan to get rid of them (and inform your users).

Some DNS hosts provide a way to get CNAME-like functionality at the zone apex (the root domain level, for the naked domain name) using a custom record type. Such records include, for example:

  • ALIAS at DNSimple
  • ANAME at DNS Made Easy
  • ANAME at easyDNS
  • CNAME at CloudFlare

For each provider, the setup is similar: point the ALIAS or ANAME entry for your apex domain to, just as you would with a CNAME record. Depending on the DNS provider, an empty or @ Name value identifies the zone apex.


If your DNS provider does not support such a record-type, and you are unable to switch to one that does, you will need to use subdomain redirection, which is not that hard, depending on the protocol or server software that needs to do it.

I strongly disagree with the statement that it's done only by "amateur admins" or such ideas. It's a simple "What does the name and its service need to do?" deal, and then to adapt your DNS config to serve those wishes; If your main services are web and e-mail, I don' t see any VALID reason why dropping the CNAMEs for-good would be problematic. After all, who would prefer over ? Who needs "www" if you're already set with the protocol itself? It's illogical to assume that use of a root-domainname would be invalid.

Delete directories recursively in Java

In legacy projects, I need to create native Java code. I create this code similar to Paulitex code. See that:

public class FileHelper {

   public static boolean delete(File fileOrFolder) {
      boolean result = true;
      if(fileOrFolder.isDirectory()) {
         for (File file : fileOrFolder.listFiles()) {
            result = result && delete(file);
      result = result && fileOrFolder.delete();
      return result;

And the unit test:

public class FileHelperTest {

    public void setup() throws IOException {
       new File("FOLDER_TO_DELETE/SUBFOLDER").mkdirs();
       new File("FOLDER_TO_DELETE/SUBFOLDER_TWO").mkdirs();
       new File("FOLDER_TO_DELETE/SUBFOLDER_TWO/TEST_FILE.txt").createNewFile();

    public void deleteFolderWithFiles() {
       File folderToDelete = new File("FOLDER_TO_DELETE");
       Assert.assertFalse(new File("FOLDER_TO_DELETE").exists());


What is a .NET developer?

Generally what's meant by that is a fairly intimate familiarity with one (or probably more) of the .NET languages (C#, VB.NET, etc.) and one (or less probably more) of the .NET stacks (WinForms, ASP.NET, WPF, etc.).

As for a specific "formal definition", I don't think you'll find one beyond that. The job description should be specific about what they're looking for. I wouldn't consider a job listing that asks for a ".NET developer" and provides no more detail than that to be sufficiently descriptive.

Changing PowerShell's default output encoding to UTF-8

Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.

  • On PSv5.1 or higher, where > and >> are effectively aliases of Out-File, you can set the default encoding for > / >> / Out-File via the $PSDefaultParameterValues preference variable:

    • $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
  • On PSv5.0 or below, you cannot change the encoding for > / >>, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File.
    (The $PSDefaultParameterValues preference variable was introduced in PSv3.0).

  • On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
    an -Encoding parameter
    (which in PSv5.1+ includes > and >>), use:

    • $PSDefaultParameterValues['*:Encoding'] = 'utf8'

If you place this command in your $PROFILE, cmdlets such as Out-File and Set-Content will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding parameter.

Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues:

  • $PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }

Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.

For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.

The automatic $OutputEncoding variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.

Optional reading: The cross-platform perspective: PowerShell Core:

PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.

  • This means that source-code files without a BOM are assumed to be UTF-8, and using > / Out-File / Set-Content defaults to BOM-less UTF-8; explicit use of the utf8 -Encoding argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom value.

  • If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1 file will typically not have a UTF-8 pseudo-BOM:

    • This works fine on PowerShell Core.
    • It may break on Windows PowerShell, if the file contains non-ASCII characters; if you do need to use non-ASCII characters in your scripts, save them as UTF-8 with BOM.
      Without the BOM, Windows PowerShell (mis)interprets your script as being encoded in the legacy "ANSI" codepage (determined by the system locale for pre-Unicode applications; e.g., Windows-1252 on US-English systems).
  • Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat, sed, and awk - and even some editors such as gedit - to pass the pseudo-BOM through, i.e., to treat it as data.

    • This may not always be a problem, but definitely can be, such as when you try to read a file into a string in bash with, say, text=$(cat file) or text=$(<file) - the resulting variable will contain the pseudo-BOM as the first 3 bytes.

Inconsistent default encoding behavior in Windows PowerShell:

Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.


  • The following doesn't aspire to cover all standard cmdlets.

  • Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.

  • As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.

Cmdlets that write:

Out-File and > / >> create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content / Add-Content (see next point); New-ModuleManifest and Export-CliXml also create UTF-16LE files.

Set-Content (and Add-Content if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default).

Export-Csv indeed creates ASCII files, as documented, but see the notes re -Append below.

Export-PSSession creates UTF-8 files with BOM by default.

New-Item -Type File -Value currently creates BOM-less(!) UTF-8.

The Send-MailMessage help topic also claims that ASCII encoding is the default - I have not personally verified that claim.

Start-Transcript invariably creates UTF-8 files with BOM, but see the notes re -Append below.

Re commands that append to an existing file:

>> / Out-File -Append make no attempt to match the encoding of a file's existing content. That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding, which is not an option with >> (except indirectly in PSv5.1+, via $PSDefaultParameterValues, as shown above). In short: you must know the encoding of an existing file's content and append using that same encoding.

Add-Content is the laudable exception: in the absence of an explicit -Encoding argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.

This inconsistency between Out-File -Append / >> and Add-Content, which also affects PowerShell Core, is discussed in this GitHub issue.

Export-Csv -Append partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append assumes UTF-8 is, whereas Add-Content assumes ANSI.

Start-Transcript -Append partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.

Cmdlets that read (that is, the encoding used in the absence of a BOM):

Get-Content and Import-PowerShellDataFile default to ANSI (Default), which is consistent with Set-Content.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.

By contrast, Import-Csv, Import-CliXml and Select-String assume UTF-8 in the absence of a BOM.

JSONResult to String

You can also use Json.NET.

return JsonConvert.SerializeObject(jsonResult.Data);

SQL Query To Obtain Value that Occurs more than once

For postgresql:

SELECT * AS rec 
    SELECT lastname, COUNT(*) AS counter 
    FROM students 
    GROUP BY lastname) AS tbl 
WHERE counter > 1;

Erasing elements from a vector

  1. You can iterate using the index access,

  2. To avoid O(n^2) complexity you can use two indices, i - current testing index, j - index to store next item and at the end of the cycle new size of the vector.


void erase(std::vector<int>& v, int num)
  size_t j = 0;
  for (size_t i = 0; i < v.size(); ++i) {
    if (v[i] != num) v[j++] = v[i];
  // trim vector to new size

In such case you have no invalidating of iterators, complexity is O(n), and code is very concise and you don't need to write some helper classes, although in some case using helper classes can benefit in more flexible code.

This code does not use erase method, but solves your task.

Using pure stl you can do this in the following way (this is similar to the Motti's answer):

#include <algorithm>

void erase(std::vector<int>& v, int num) {
    vector<int>::iterator it = remove(v.begin(), v.end(), num);
    v.erase(it, v.end());

java Arrays.sort 2d array

For a general solution you can use the Column Comparator. The code to use the class would be:

Arrays.sort(myArr, new ColumnComparator(0));

How does the class_weight parameter in scikit-learn work?

First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in.

For how class_weight works: It penalizes mistakes in samples of class[i] with class_weight[i] instead of 1. So higher class-weight means you want to put more emphasis on a class. From what you say it seems class 0 is 19 times more frequent than class 1. So you should increase the class_weight of class 1 relative to class 0, say {0:.1, 1:.9}. If the class_weight doesn't sum to 1, it will basically change the regularization parameter.

For how class_weight="auto" works, you can have a look at this discussion. In the dev version you can use class_weight="balanced", which is easier to understand: it basically means replicating the smaller class until you have as many samples as in the larger one, but in an implicit way.

When should we call System.exit in Java

In applications that may have complex shutdown hooks, this method should not be called from an unknown thread. System.exit never exits normally because the call will block until the JVM is terminated. It's as if whatever code is running that has the power plug pulled on it before it can finish. Calling System.exit will initiate the program's shutdown hooks and whatever thread that calls System.exit will block until program termination. This has the implication that if the shutdown hook in turn submits a task to the thread from which System.exit was called, the program will deadlock.

I'm handling this in my code with the following:

public static void exit(final int status) {
    new Thread("App-exit") {
        public void run() {

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

I'm not sure where to post this answer of mine but I think it's the right place. I came across this very error today and switching the subsystems didn't change a thing.

Changing the 64bit lib files to 32bit (x86) did the trick for me, I hope it will help someone out there !

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

I got the same issue and did following to fix it.

  1. Settings > Storage > Clear Cached Data
  2. Settings > Apps > Uninstall the apps showing there. I had uninstalled my apps but it was showing there.
  3. Restart and then everything went fine.

Replace comma with newline in sed on MacOS?

Though I am late to this post, just updating my findings. This answer is only for Mac OS X.

$ sed 's/new/
> /g' m1.json > m2.json
sed: 1: "s/new/
/g": unescaped newline inside substitute pattern

In the above command I tried with Shift+Enter to add new line which didn't work. So this time I tried with "escaping" the "unescaped newline" as told by the error.

$ sed 's/new/\
> /g' m1.json > m2.json 

Worked! (in Mac OS X 10.9.3)

JavaScript/regex: Remove text between parentheses

If you need to remove text inside nested parentheses, too, then:

        var prevStr;
        do {
            prevStr = str;
            str = str.replace(/\([^\)\(]*\)/, "");
        } while (prevStr != str);

What Process is using all of my disk IO

Have you considered lsof (list open files)?

iOS: Compare two dates

According to Apple documentation of NSDate compare:

Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date.

- (NSComparisonResult)compare:(NSDate *)anotherDate

Parameters anotherDate

The date with which to compare the receiver. This value must not be nil. If the value is nil, the behavior is undefined and may change in future versions of Mac OS X.

Return Value


The receiver and anotherDate are exactly equal to each other, NSOrderedSame

The receiver is later in time than anotherDate, NSOrderedDescending

The receiver is earlier in time than anotherDate, NSOrderedAscending

In other words:

if ([date1 compare:date2] == NSOrderedSame) ...

Note that it might be easier in your particular case to read and write this :

if ([date2 isEqualToDate:date2]) ...

See Apple Documentation about this one.

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

This code will do what you're looking for. It's based on examples found here and here.

The autofmt_xdate() call is particularly useful for making the x-axis labels readable.

import numpy as np
from matplotlib import pyplot as plt

fig = plt.figure()

width = .35
ind = np.arange(len(OY)), OY, width=width)
plt.xticks(ind + width / 2, OX)



enter image description here

Normalizing a list of numbers in Python


normed = [i/sum(raw) for i in raw]

[0.25, 0.5, 0.25]

How do you find all subclasses of a given class in Java?

It should be noted as well that this will of course only find all those subclasses that exist on your current classpath. Presumably this is OK for what you are currently looking at, and chances are you did consider this, but if you have at any point released a non-final class into the wild (for varying levels of "wild") then it is entirely feasible that someone else has written their own subclass that you will not know about.

Thus if you happened to be wanting to see all subclasses because you want to make a change and are going to see how it affects subclasses' behaviour - then bear in mind the subclasses that you can't see. Ideally all of your non-private methods, and the class itself should be well-documented; make changes according to this documentation without changing the semantics of methods/non-private fields and your changes should be backwards-compatible, for any subclass that followed your definition of the superclass at least.

The character encoding of the plain text document was not declared - mootool script

FireFox is reporting that the response did not even specify the character encoding in the header, eg. Content-Type: text/html; charset=utf-8 and not just Content-Type: text/plain;.

What web server are you using? Are you sure you are not requesting a non-existing page (404) that responds poorly?

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:


Up next is the create script. Creating a database file:


SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);


After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.

Resource u'tokenizers/punkt/english.pickle' not found

If you're looking to only download the punkt model:

import nltk'punkt')

If you're unsure which data/model you need, you can install the popular datasets, models and taggers from NLTK:

import nltk'popular')

With the above command, there is no need to use the GUI to download the datasets.

To delay JavaScript function call using jQuery

Very easy, just call the function within a specific amount of milliseconds using setTimeout()

setTimeout(myFunction, 2000)

function myFunction() {
    alert('Was called after 2 seconds');

Or you can even initiate the function inside the timeout, like so:

setTimeout(function() {
    alert('Was called after 2 seconds');
}, 2000)

ng: command not found while creating new project using angular-cli

Repairing NodeJS installation on windows resolved it for me.

Rails 4: List of available datatypes

It is important to know not only the types but the mapping of these types to the database types, too:

enter image description here

enter image description here

Source added - Agile Web Development with Rails 4

How to target the href to div

Try this code in jquery

  var id=$(this).attr('href');
  var value=$(id).text();

How do you use variables in a simple PostgreSQL script?

Postgresql does not have bare variables, you could use a temporary table. variables are only available in code blocks or as a user-interface feature.

If you need a bare variable you could use a temporary table:


SELECT dbo.PubLists.*
FROM   dbo.PubLists,list
WHERE  Name = list.column1;

How to store directory files listing into an array?

Running any shell command inside $(...) will help to store the output in a variable. So using that we can convert the files to array with IFS.

IFS=' ' read -r -a array <<< $(ls /path/to/dir)

What is the difference between res.end() and res.send()?

res.send is used to send the response to the client where res.end is used to end the response you are sending.

res.send automatically call res.end So you don't have to call or mention it after res.send

How to handle screen orientation change when progress dialog and background thread active?

I am a fresher in android and I tried this and it's worked.

public class loadTotalMemberByBranch extends AsyncTask<Void, Void,Void> {
        ProgressDialog progressDialog = new ProgressDialog(Login.this);
        int ranSucess=0;
        protected void onPreExecute() {
            // TODO Auto-generated method stub

        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub

            return null;
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub

How do I resolve a HTTP 414 "Request URI too long" error?

Under Apache, the limit is a configurable value, LimitRequestLine. Change this value to something larger than its default of 8190 if you want to support a longer request URI. The value is in /etc/apache2/apache2.conf. If not, add a new line (LimitRequestLine 10000) under AccessFileName .htaccess.

However, note that if you're actually running into this limit, you are probably abusing GET to begin with. You should use POST to transmit this sort of data -- especially since you even concede that you're using it to update values. If you check the link above, you'll notice that Apache even says "Under normal conditions, the value should not be changed from the default."

How to trace the path in a Breadth-First Search?

I like both @Qiao first answer and @Or's addition. For a sake of a little less processing I would like to add to Or's answer.

In @Or's answer keeping track of visited node is great. We can also allow the program to exit sooner that it currently is. At some point in the for loop the current_neighbour will have to be the end, and once that happens the shortest path is found and program can return.

I would modify the the method as follow, pay close attention to the for loop

graph = {
1: [2, 3, 4],
2: [5, 6],
3: [10],
4: [7, 8],
5: [9, 10],
7: [11, 12],
11: [13]

    def bfs(graph_to_search, start, end):
        queue = [[start]]
        visited = set()

    while queue:
        # Gets the first path in the queue
        path = queue.pop(0)

        # Gets the last node in the path
        vertex = path[-1]

        # Checks if we got to the end
        if vertex == end:
            return path
        # We check if the current node is already in the visited nodes set in order not to recheck it
        elif vertex not in visited:
            # enumerate all adjacent nodes, construct a new path and push it into the queue
            for current_neighbour in graph_to_search.get(vertex, []):
                new_path = list(path)

                #No need to visit other neighbour. Return at once
                if current_neighbour == end
                    return new_path;

            # Mark the vertex as visited

print bfs(graph, 1, 13)

The output and everything else will be the same. However, the code will take less time to process. This is especially useful on larger graphs. I hope this helps someone in the future.

What does "#pragma comment" mean?

I've always called them "compiler directives." They direct the compiler to do things, branching, including libs like shown above, disabling specific errors etc., during the compilation phase.

Compiler companies usually create their own extensions to facilitate their features. For example, (I believe) Microsoft started the "#pragma once" deal and it was only in MS products, now I'm not so sure.

Pragma Directives It includes "#pragma comment" in the table you'll see.


I suspect GCC, for example, has their own set of #pragma's.

Understanding REST: Verbs, error codes, and authentication

re 1: This looks fine so far. Remember to return the URI of the newly created user in a "Location:" header as part of the response to POST, along with a "201 Created" status code.

re 2: Activation via GET is a bad idea, and including the verb in the URI is a design smell. You might want to consider returning a form on a GET. In a Web app, this would be an HTML form with a submit button; in the API use case, you might want to return a representation that contains a URI to PUT to to activate the account. Of course you can include this URI in the response on POST to /users, too. Using PUT will ensure your request is idempotent, i.e. it can safely be sent again if the client isn't sure about success. In general, think about what resources you can turn your verbs into (sort of "nounification of verbs"). Ask yourself what method your specific action is most closely aligned with. E.g. change_password -> PUT; deactivate -> probably DELETE; add_credit -> possibly POST or PUT. Point the client to the appropriate URIs by including them in your representations.

re 3. Don't invent new status codes, unless you believe they're so generic they merit being standardized globally. Try hard to use the most appropriate status code available (read about all of them in RFC 2616). Include additional information in the response body. If you really, really are sure you want to invent a new status code, think again; if you still believe so, make sure to at least pick the right category (1xx -> OK, 2xx -> informational, 3xx -> redirection; 4xx-> client error, 5xx -> server error). Did I mention that inventing new status codes is a bad idea?

re 4. If in any way possible, use the authentication framework built into HTTP. Check out the way Google does authentication in GData. In general, don't put API keys in your URIs. Try to avoid sessions to enhance scalability and support caching - if the response to a request differs because of something that has happened before, you've usually tied yourself to a specific server process instance. It's much better to turn session state into either client state (e.g. make it part of subsequent requests) or make it explicit by turning it into (server) resource state, i.e. give it its own URI.

How can my iphone app detect its own version number?

Read the info.plist file of your app and get the value for key CFBundleShortVersionString. Reading info.plist will give you an NSDictionary object

Kotlin Android start new Activity

You can use both Kotlin and Java files in your application.

To switch between the two files, make sure you give them unique < action android:name="" in AndroidManifest.xml, like so:

            <activity android:name=".MainActivityKotlin">
                    <action android:name="com.genechuang.basicfirebaseproject.KotlinActivity"/>
                    <category android:name="android.intent.category.DEFAULT" />
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                android:label="MainActivityJava" >
                    <action android:name="com.genechuang.basicfirebaseproject.JavaActivity" />
                    <category android:name="android.intent.category.DEFAULT" />

Then in your MainActivity.kt (Kotlin file), to start an Activity written in Java, do this:

       val intent = Intent("com.genechuang.basicfirebaseproject.JavaActivity")

In your (Java file), to start an Activity written in Kotlin, do this:

       Intent mIntent = new Intent("com.genechuang.basicfirebaseproject.KotlinActivity");

Pass variables between two PHP pages without using a form or the URL of page

Have you tried adding both to $_SESSION?

Then at the top of your page2.php just add:


Selenium WebDriver: Wait for complex page with JavaScript to load

If anyone actually knew a general and always-applicable answer, it would have been implemented everywhere ages ago and would make our lives SO much easier.

There are many things you can do, but every single one of them has a problem:

  1. As Ashwin Prabhu said, if you know the script well, you can observe its behaviour and track some of its variables on window or document etc. This solution, however, is not for everyone and can be used only by you and only on a limited set of pages.

  2. Your solution by observing the HTML code and whether it has or hasn't been changed for some time is not bad (also, there is a method to get the original and not-edited HTML directly by WebDriver), but:

    • It takes a long time to actually assert a page and could prolong the test significantly.
    • You never know what the right interval is. The script might be downloading something big that takes more than 500 ms. There are several scripts on our company's internal page that take several seconds in IE. Your computer may be temporarily short on resources - say that an antivirus will make your CPU work fully, then 500 ms may be too short even for a noncomplex scripts.
    • Some scripts are never done. They call themselves with some delay (setTimeout()) and work again and again and could possibly change the HTML every time they run. Seriously, every "Web 2.0" page does it. Even Stack Overflow. You could overwrite the most common methods used and consider the scripts that use them as completed, but ... you can't be sure.
    • What if the script does something other than changing the HTML? It could do thousands of things, not just some innerHTML fun.
  3. There are tools to help you on this. Namely Progress Listeners together with nsIWebProgressListener and some others. The browser support for this, however, is horrible. Firefox began to try to support it from FF4 onwards (still evolving), IE has basic support in IE9.

And I guess I could come up with another flawed solution soon. The fact is - there's no definite answer on when to say "now the page is complete" because of the everlasting scripts doing their work. Pick the one that serves you best, but beware of its shortcomings.

Tab Escape Character?

Easy one! "\t"

Edit: In fact, here's something official: Escape Sequences

How to detect shake event with android?

This is for Kotlin and use SensorEventListener

Create new class ShakeDetector

class ShakeDetector : SensorEventListener {
    private var mListener: OnShakeListener? = null
    private var mShakeTimestamp: Long = 0
    private var mShakeCount = 0
    fun setOnShakeListener(listener: OnShakeListener?) {
        mListener = listener

    interface OnShakeListener {
        fun onShake(count: Int)

    override fun onAccuracyChanged(
        sensor: Sensor,
        accuracy: Int
    ) { // ignore

    override fun onSensorChanged(event: SensorEvent) {
        if (mListener != null) {
            val x = event.values[0]
            val y = event.values[1]
            val z = event.values[2]
            val gX = x / SensorManager.GRAVITY_EARTH
            val gY = y / SensorManager.GRAVITY_EARTH
            val gZ = z / SensorManager.GRAVITY_EARTH
            // gForce will be close to 1 when there is no movement.
            val gForce: Float = sqrt(gX * gX + gY * gY + gZ * gZ)
            if (gForce > SHAKE_THRESHOLD_GRAVITY) {
                val now = System.currentTimeMillis()
                // ignore shake events too close to each other (500ms)
                if (mShakeTimestamp + SHAKE_SLOP_TIME_MS > now) {
                // reset the shake count after 3 seconds of no shakes
                if (mShakeTimestamp + SHAKE_COUNT_RESET_TIME_MS < now) {
                    mShakeCount = 0
                mShakeTimestamp = now

    companion object {
     * The gForce that is necessary to register as shake.
     * Must be greater than 1G (one earth gravity unit).
     * You can install "G-Force", by Blake La Pierre
     * from the Google Play Store and run it to see how
     *  many G's it takes to register a shake
        private const val SHAKE_THRESHOLD_GRAVITY = 2.7f
        private const val SHAKE_SLOP_TIME_MS = 500
        private const val SHAKE_COUNT_RESET_TIME_MS = 3000

Your main Activity

class MainActivity : AppCompatActivity() {

    // The following are used for the shake detection
    private var mSensorManager: SensorManager? = null
    private var mAccelerometer: Sensor? = null
    private var mShakeDetector: ShakeDetector? = null

    override fun onCreate(savedInstanceState: Bundle?) {
    override fun onResume() {
        // Add the following line to register the Session Manager Listener onResume

    override fun onPause() { // Add the following line to unregister the Sensor Manager onPause

    private fun initSensor() {
        // ShakeDetector initialization
        // ShakeDetector initialization
        mSensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
        mAccelerometer = mSensorManager!!.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
        mShakeDetector = ShakeDetector()
        mShakeDetector!!.setOnShakeListener(object : OnShakeListener {
            override fun onShake(count: Int) { /*
                 * The following method, "handleShakeEvent(count):" is a stub //
                 * method you would use to setup whatever you want done once the
                 * device has been shook.
                Toast.makeText(this@MainActivity, count.toString(), Toast.LENGTH_SHORT).show()

Finally add this code to Manifests to make sure the phone has an accelerometer

<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />

Difference between "enqueue" and "dequeue"

Enqueue means to add an element, dequeue to remove an element.

var stackInput= []; // First stack
var stackOutput= []; // Second stack

// For enqueue, just push the item into the first stack
function enqueue(stackInput, item) {
  return stackInput.push(item);

function dequeue(stackInput, stackOutput) {
  // Reverse the stack such that the first element of the output stack is the
  // last element of the input stack. After that, pop the top of the output to
  // get the first element that was ever pushed into the input stack
  if (stackOutput.length <= 0) {
    while(stackInput.length > 0) {
      var elementToOutput = stackInput.pop();

  return stackOutput.pop();

How to insert a new line in strings in Android


String str = "my string \n my other string";

When printed you will get:

my string
my other string

How to change the height of a <br>?

Another way is to use an HR. But, and here's the cunning part, make it invisible.


<hr style="height:30pt; visibility:hidden;" />

To make a cleaner BR break simulated using the HR: Btw works in all browsers!!

{ height:2px; visibility:hidden; margin-bottom:-1px; }

Excel: Use a cell value as a parameter for a SQL query

The SQL is somewhat like the syntax of MS SQL.

SELECT * FROM [table$] WHERE *;

It is important that the table name is ended with a $ sign and the whole thing is put into brackets. As conditions you can use any value, but so far Excel didn't allow me to use what I call "SQL Apostrophes" (´), so a column title in one word is recommended.

If you have users listed in a table called "Users", and the id is in a column titled "id" and the name in a column titled "Name", your query will look like this:

SELECT Name FROM [Users$] WHERE id = 1;

Hope this helps.

JQuery - Set Attribute value

Use an ID to uniquely identify the checkbox. Your current example is trying to select the checkbox with an id of '#chk0':

<input type="checkbox" id="chk0" name="chk0" value="true" disabled>

$('#chk0').attr("disabled", "disabled");

You'll also need to remove the attribute for disabled to enable the checkbox. Something like:


See the docs for removeAttr

The value XHTML for disabling/enabling an input element is as follows:

<input type="checkbox" id="chk0" name="chk0" value="true" disabled="disabled" />
<input type="checkbox" id="chk0" name="chk0" value="true" />

Note that it's the absence of the disabled attribute that makes the input element enabled.

Is there a way to represent a directory tree in a Github

The best way to do this is to surround your tree in the triple backticks to denote a code block. For more info, see the markdown docs:

Python multiprocessing PicklingError: Can't pickle <type 'function'>

As others have said multiprocessing can only transfer Python objects to worker processes which can be pickled. If you cannot reorganize your code as described by unutbu, you can use dills extended pickling/unpickling capabilities for transferring data (especially code data) as I show below.

This solution requires only the installation of dill and no other libraries as pathos:

import os
from multiprocessing import Pool

import dill

def run_dill_encoded(payload):
    fun, args = dill.loads(payload)
    return fun(*args)

def apply_async(pool, fun, args):
    payload = dill.dumps((fun, args))
    return pool.apply_async(run_dill_encoded, (payload,))

if __name__ == "__main__":

    pool = Pool(processes=5)

    # asyn execution of lambda
    jobs = []
    for i in range(10):
        job = apply_async(pool, lambda a, b: (a, b, a * b), (i, i + 1))

    for job in jobs:
        print job.get()

    # async execution of static method

    class O(object):

        def calc():
            return os.getpid()

    jobs = []
    for i in range(10):
        job = apply_async(pool, O.calc, ())

    for job in jobs:
        print job.get()

Convert double to BigDecimal and set BigDecimal Precision

It's printing out the actual, exact value of the double.

Double.toString(), which converts doubles to Strings, does not print the exact decimal value of the input -- if x is your double value, it prints out exactly enough digits that x is the closest double to the value it printed.

The point is that there is no such double as 47.48 exactly. Doubles store values as binary fractions, not as decimals, so it can't store exact decimal values. (That's what BigDecimal is for!)

Cannot use Server.MapPath

Firt add a reference to System.web, if you don't have. Do that in the References folder.

You can then use Hosting.HostingEnvironment.MapPath(path);

Format number to 2 decimal places

When formatting number to 2 decimal places you have two options TRUNCATE and ROUND. You are looking for TRUNCATE function.


Without rounding:

TRUNCATE(0.166, 2)
-- will be evaluated to 0.16

TRUNCATE(0.164, 2)
-- will be evaluated to 0.16


With rounding:

ROUND(0.166, 2)
-- will be evaluated to 0.17

ROUND(0.164, 2)
-- will be evaluated to 0.16


ngOnInit not being called when Injectable class is Instantiated

I don't know about all the lifecycle hooks, but as for destruction, ngOnDestroy actually get called on Injectable when it's provider is destroyed (for example an Injectable supplied by a component).

From the docs :

Lifecycle hook that is called when a directive, pipe or service is destroyed.

Just in case anyone is interested in destruction check this question:

Get all validation errors from Angular 2 FormGroup

Try This , it will call validation for all control in form :

validateAllFormControl(formGroup: FormGroup) {         
  Object.keys(formGroup.controls).forEach(field => {  
    const control = formGroup.get(field);             
    if (control instanceof FormControl) {             
      control.markAsTouched({ onlySelf: true });
    } else if (control instanceof FormGroup) {        

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

you must change your model name first letter capital. in localhost small letter work properly but online this not work. for exa:


replaced it to


Isn't the size of character in Java 2 bytes?

The constructor String(byte[] bytes) takes the bytes from the buffer and encodes them to characters.

It uses the platform default charset to encode bytes to characters. If you know, your file contains text, that is encoded in a different charset, you can use the String(byte[] bytes, String charsetName) to use the correct encoding (from bytes to characters).

AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

There's an easy way to do that. Very easy. Since I noticed that

$scope.yourModel = [];

removes all $scope.yourModel array list you can do like this

function deleteAnObjectByKey(objects, key) {
    var clonedObjects = Object.assign({}, objects);

     for (var x in clonedObjects)
        if (clonedObjects.hasOwnProperty(x))
             if (clonedObjects[x].id == key)
                 delete clonedObjects[x];

    $scope.yourModel = clonedObjects;

The $scope.yourModel will be updated with the clonedObjects.

Hope that helps.

When does Git refresh the list of remote branches?

The OP did not ask for cleanup for all remotes, rather for all branches of default remote.

So git fetch --prune is what should be used.

Setting git config remote.origin.prune true makes --prune automatic. In that case just git fetch will also prune stale remote branches from the local copy. See also Automatic prune with Git fetch or pull.

Note that this does not clean local branches that are no longer tracking a remote branch. See How to prune local tracking branches that do not exist on remote anymore for that.

Getting command-line password input in Python

This code will print an asterisk instead of every letter.

import sys
import msvcrt

passwor = ''
while True:
    x = msvcrt.getch()
    if x == '\r':
    passwor +=x

print '\n'+passwor

How can I convert a series of images to a PDF from the command line on linux?

Using imagemagick, you can try:

convert page.png page.pdf

Or for multiple images:

convert page*.png mydoc.pdf

How do I change a PictureBox's image?

Assign a new Image object to your PictureBox's Image property. To load an Image from a file, you may use the Image.FromFile method. In your particular case, assuming the current directory is one under bin, this should load the image bin/Pics/image1.jpg, for example:

pictureBox1.Image = Image.FromFile("../Pics/image1.jpg");

Additionally, if these images are static and to be used only as resources in your application, resources would be a much better fit than files.

How to create EditText accepts Alphabets only in android?

For those who want that their editText should accept only alphabets and space (neither numerics nor any special characters), then one can use this InputFilter. Here I have created a method named getEditTextFilter() and written the InputFilter inside it.

public static InputFilter getEditTextFilter() {
        return new InputFilter() {

            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

                boolean keepOriginal = true;
                StringBuilder sb = new StringBuilder(end - start);
                for (int i = start; i < end; i++) {
                    char c = source.charAt(i);
                    if (isCharAllowed(c)) // put your condition here
                        keepOriginal = false;
                if (keepOriginal)
                    return null;
                else {
                    if (source instanceof Spanned) {
                        SpannableString sp = new SpannableString(sb);
                        TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
                        return sp;
                    } else {
                        return sb;

            private boolean isCharAllowed(char c) {
                Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
                Matcher ms = ps.matcher(String.valueOf(c));
                return ms.matches();

Attach this inputFilter to your editText after finding it, like this :

mEditText.setFilters(new InputFilter[]{getEditTextFilter()});

The original credit goes to @UMAR who gave the idea of validating using regular expression and @KamilSeweryn

SVG Positioning

Everything in the g element is positioned relative to the current transform matrix.

To move the content, just put the transformation in the g element:

<g transform="translate(20,2.5) rotate(10)">
    <rect x="0" y="0" width="60" height="10"/>

Links: Example from the SVG 1.1 spec

How do I display a decimal value to 2 decimal places?

If you want it formatted with commas as well as a decimal point (but no currency symbol), such as 3,456,789.12...


Angularjs: input[text] ngChange fires while the value is changing

This is about recent additions to AngularJS, to serve as future answer (also for another question).

Angular newer versions (now in 1.3 beta), AngularJS natively supports this option, using ngModelOptions, like

ng-model-options="{ updateOn: 'default blur', debounce: { default: 500, blur: 0 } }"

NgModelOptions docs


<input type="text" name="username"
       ng-model-options="{updateOn: 'default blur', debounce: {default: 500, blur: 0} }" />

How to add a border to a widget in Flutter?

You can use Container to contain your widget:

  decoration: BoxDecoration(
    border: Border.all(
    color: Color(0xff000000),
    width: 1,
  child: Text()

mkdir's "-p" option

-p|--parent will be used if you are trying to create a directory with top-down approach. That will create the parent directory then child and so on iff none exists.

-p, --parents no error if existing, make parent directories as needed

About rlidwka it means giving full or administrative access. Found it here

How to determine the IP address of a Solaris system

Try using ifconfig -a. Look for "inet", that is your IP address

How to get the ActionBar height?

you just have to add this.

public int getActionBarHeight() {
        int height;

            height = getActivity().getActionBar().getHeight();
        } else {
            height = ((ActionBarActivity) getActivity()).getSupportActionBar().getHeight();

        return height;

SOAP or REST for Web Services?

SOAP is useful from a tooling perspective because the WSDL is so easily consumed by tools. So, you can get Web Service clients generated for you in your favorite language.

REST plays well with AJAX'y web pages. If you keep your requests simple, you can make service calls directly from your JavaScript, and that comes in very handy. Try to stay away from having any namespaces in your response XML, I've seen browsers choke on those. So, xsi:type is probably not going to work for you, no overly complex XML Schemas.

REST tends to have better performance as well. CPU requirements of the code generating REST responses tend to be lower than what SOAP frameworks exhibit. And, if you have your XML generation ducks lined up on the server side, you can effectively stream XML out to the client. So, imagine you're reading rows of database cursor. As you read a row, you format it as an XML element, and you write that directly out to the service consumer. This way, you don't have to collect all of the database rows in memory before starting to write your XML output - you read and write at the same time. Look into novel templating engines or XSLT to get the streaming to work for REST.

SOAP on the other hand tends to get generated by tool-generated services as a big blob and only then written. This is not an absolute truth, mind you, there are ways to get streaming characteristics out of SOAP, like by using attachments.

My decision making process is as follows: if I want my service to be easily tooled by consumers, and the messages I write will be medium-to-small-ish (10MB or less), and I don't mind burning some extra CPU cycles on the server, I go with SOAP. If I need to serve to AJAX on web browsers, or I need the thing to stream, or my responses are gigantic, I go REST.

Finally, there are lots of great standards built up around SOAP, like WS-Security and getting stateful Web Services, that you can plug in to if you're using the right tools. That kind of stuff really makes a difference, and can help you satisfy some hairy requirements.

Submitting a form by pressing enter without a submit button

This is my solution, tested in Chrome, Firefox 6 and IE7+:

    height: 1px;
    width: 1px;
    position: absolute;
    z-index: -100;

Check if a string within a list contains a specific string with Linq

LINQ Any() would do the job:

bool contains = myList.Any(s => s.Contains(pattern));

Any(), MSDN:

Determines whether any element of a sequence satisfies a condition

Explicit vs implicit SQL joins

On some databases (notably Oracle) the order of the joins can make a huge difference to query performance (if there are more than two tables). On one application, we had literally two orders of magnitude difference in some cases. Using the inner join syntax gives you control over this - if you use the right hints syntax.

You didn't specify which database you're using, but probability suggests SQL Server or MySQL where there it makes no real difference.

Placing/Overlapping(z-index) a view above another view in android

There is a way to use LinearLayout. Just set the marginTop of your previous element to the corresponding negative value, and make sure the element you want on top is after the element you want below in your XML.

<linearLayout android:orientation="horizontal" ... >

Laravel 5 – Clear Cache in Shared Hosting Server

Basically I want to clear the views cache.

There is now a command in Laravel 5.1 for that

php artisan view:clear

How to convert milliseconds to seconds with precision

I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.

double time_seconds = time_milliseconds / 1000.0;   // add the decimal
System.out.println(time_milliseconds);              // Now this should give you the right value.

Show special characters in Unix while using 'less' Command

Now, sometimes you already have less open, and you can't use cat on it. For example, you did a | less, and you can't just reopen a file, as that's actually a stream.

If all you need is to identify end of line, one easy way is to search for the last character on the line: /.$. The search will highlight the last character, even if it is a blank, making it easy to identify it.

That will only help with the end of line case. If you need other special characters, you can use the cat -vet solution above with marks and pipe:

  • mark the top of the text you're interested in: ma
  • go to the bottom of the text you're interested in and mark it, as well: mb
  • go back to the mark a: 'a
  • pipe from a to b through cat -vet and view the result in another less command: |bcat -vet | less

This will open another less process, which shows the result of running cat -vet on the text that lies between marks a and b.

If you want the whole thing, instead, do g|$cat -vet | less, to go to the first line and filter all lines through cat.

The advantage of this method over less options is that it does not mess with the output you see on the screen.

One would think that eight years after this question was originally posted, less would have that feature... But I can't even see a feature request for it on

How to duplicate a whole line in Vim?

If you want another way:

"ayy: This will store the line in buffer a.

"ap: This will put the contents of buffer a at the cursor.

There are many variations on this.

"a5yy: This will store the 5 lines in buffer a.

See "Vim help files for more fun.

How to make a <div> appear in front of regular text/tables

Use the display property in CSS:

    <div id="invisible" style="display:none;">Invisible DIV</div>  
    <div>Another DIV 
        <button onclick="document.getElementById('invisible').style.display='block'">

When the the display of the first div is set back to block it will appear and shift the second div down.

How to get Android GPS location

The initial issue is solved by changing lat and lon to double.

I want to add comment to solution with Location location = locationManager.getLastKnownLocation(bestProvider); It works to find out last known location when other app was lisnerning for that. If, for example, no app did that since device start, the code will return zeros (spent some time myself recently to figure that out).

Also, it's a good practice to stop listening when there is no need for that by locationManager.removeUpdates(this);

Also, even with permissions in manifest, the code works when location service is enabled in Android settings on a device.

Migrating from VMWARE to VirtualBox

After many attempts I was finally able to get this working. Essentially what I did was download and use the vmware converter to merge the two disks into one. After that I was able to attach the newly created disk to VitrualBox.

The steps involved are very simple:


1) MAKE A BACKUP!!! Even if you follow these instruction, you could screw things up, so make a backup. Just shutdown the VM and then make a copy of the directory where VM resides.

2) Uninstall VMware Tools from the VM that you are going to convert. If for some reason you forget this step, you can still uninstall it after getting everything running under VirtualBox by following these steps. Do yourself the favor and just do it now.


1) Download and install the VMware Converter. I used 5.0.1 build-875114, just use the latest.

2) Download and install VirtualBox

3) Fire up VMWare convertor:

Fire up VMWare convertor

4) Click on Convert machine

6) Browse to the .vmx for your VM and click Next.

Convert machine

7) Give the new VM a name and select the location where you want to put it. Click Next

Give the new VM a name and select the location

8) Click Next on the Options screen. You shouldn't have to change anything here.

Click <code>Next</code> on the <code>Options</code> screen.

9) Click Finish on the Summary screen to begin the conversion.

Click <code>Finish</code> on the <code>Summary</code> screen

10) The conversion should start. This will take a LOOONG time so be patient.

The conversion should start.

11) Hopefully all went well, if it did, you should see that the conversion is completed:

conversion is completed

12) Now open up VirtualBox and click New.

open up VirtualBox and click <code>New</code>

13) Give your VM a name and select what Type and Version it is. Click Next.

Give your VM a name and select what <code>Type</code> and <code>Version</code> it is.

14) Select the size of the memory you want to give it. Click Next.

Select the size of the memory you want to give it.

15) For the Hard Drive, click Use and existing hard drive file and select the newly converted .vmdk file.

Use and existing hard drive file

16) Now Click Settings and select the Storage menu. The issue is that by default VirtualBox will add the drive as an IDE. This won't work and we need as we need to put it on a SCSI controller.

put it on a SCSI controller

17) Select the IDE controller and the Remove Controller button.

Select the IDE controller and the <code>Remove Controller</code> button.

18) Now click the Add Controller button and select Add SCSI Controller

Add SCSI Controller

19) Click the Add Hard Disk button.

Add Hard Disk

20) Click Choose existing disk

Choose existing disk

21) Select your .vmdk file. Click OK

Select your <code>.vmdk</code> file.

22) Select the System menu.

Select the <code>System</code> menu.

23) Click Enable IO APIC. Then click OK

Click <code>Enable IO APIC</code>.

24) Congrats!!! Your VM is now confgiured! Click Start to startup the VM!

Click <code>Start</code> to startup the VM!

Check if a specific value exists at a specific key in any subarray of a multidimensional array

TMTOWTDI. Here are several solutions in order of complexity.

(Short primer on complexity follows):O(n) or "big o" means worst case scenario where n means the number of elements in the array, and o(n) or "little o" means best case scenario. Long discrete math story short, you only really have to worry about the worst case scenario, and make sure it's not n ^ 2 or n!. It's more a measure of change in computing time as n increases than it is overall computing time. Wikipedia has a good article about computational aka time complexity.

If experience has taught me anything, it's that spending too much time optimizing your programs' little-o is a distinct waste of time better spent doing something - anything - better.

Solution 0: O(n) / o(1) complexity:

This solution has a best case scenario of 1 comparison - 1 iteration thru the loop, but only provided the matching value is in position 0 of the array. The worst case scenario is it's not in the array, and thus has to iterate over every element of the array.

foreach ($my_array as $sub_array) {
    if (@$sub_array['id'] === 152) {
        return true;
return false;

Solution 1: O(n) / o(n) complexity:

This solution must loop thru the entire array no matter where the matching value is, so it's always going to be n iterations thru the array.

return 0 < count(
        function ($a) {
            return array_key_exists('id', $a) && $a['id'] == 152;

Solution 2: O(n log n) / o(n log n) complexity:

A hash insertion is where the log n comes from; n hash insertions = n * log n. There's a hash lookup at the end which is another log n but it's not included because that's just how discrete math works.

$existence_hash = [];
foreach ($my_array as $sub_array) {
    $existence_hash[$sub_array['id']] = true;
return @$existence_hash['152'];

How can I use the MS JDBC driver with MS SQL Server 2008 Express?

Named instances?

URL: jdbc:sqlserver://[serverName][\instanceName][:portNumber][;property=value]

Note: backward slash

make an html svg object also a clickable link

You could also stick something like this in the bottom of your SVG (right before the closing </svg> tag):

<a xmlns="" id="anchor" xlink:href="/" xmlns:xlink="" target="_top">
    <rect x="0" y="0" width="100%" height="100%" fill-opacity="0"/>

Then just amend the link to suit. I have used 100% width and height to cover the SVG it sits in. Credit for the technique goes to the smart folks at - that's where I first saw it used.

What do multiple arrow functions mean in javascript?

Understanding the available syntaxes of arrow functions will give you an understanding of what behaviour they are introducing when 'chained' like in the examples you provided.

When an arrow function is written without block braces, with or without multiple parameters, the expression that constitutes the function's body is implicitly returned. In your example, that expression is another arrow function.

No arrow funcs              Implicitly return `e=>{…}`    Explicitly return `e=>{…}` 
function (field) {         |  field => e => {            |  field => {
  return function (e) {    |                             |    return e => {
      e.preventDefault()   |    e.preventDefault()       |      e.preventDefault()
  }                        |                             |    }
}                          |  }                          |  }

Another advantage of writing anonymous functions using the arrow syntax is that they are bound lexically to the scope in which they are defined. From 'Arrow functions' on MDN:

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value. Arrow functions are always anonymous.

This is particularly pertinent in your example considering that it is taken from a application. As as pointed out by @naomik, in React you often access a component's member functions using this. For example:

Unbound                     Explicitly bound            Implicitly bound 
function (field) {         |  function (field) {       |  field => e => {
  return function (e) {    |    return function (e) {  |    
      this.setState(...)   |      this.setState(...)   |    this.setState(...)
  }                        |    }.bind(this)           |    
}                          |  }.bind(this)             |  }

Counting the number of non-NaN elements in a numpy ndarray in Python

Quick-to-write alterantive

Even though is not the fastest choice, if performance is not an issue you can use:



In [7]: %timeit data.size - np.count_nonzero(np.isnan(data))
10 loops, best of 3: 67.5 ms per loop

In [8]: %timeit sum(~np.isnan(data))
10 loops, best of 3: 154 ms per loop

In [9]: %timeit np.sum(~np.isnan(data))
10 loops, best of 3: 140 ms per loop

List all files in one directory PHP

Check this out : readdir()

This bit of code should list all entries in a certain directory:

if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

            echo "$entry\n";


Edit: miah's solution is much more elegant than mine, you should use his solution instead.

Asus Zenfone 5 not detected by computer

Settings > Storage > Click the USB Icon at the upper right corner > Check your choice

Multi column forms with fieldsets

I disagree that .form-group should be within .col-*-n elements. In my experience, all the appropriate padding happens automatically when you use .form-group like .row within a form.

<div class="form-group">
    <div class="col-sm-12">
        <label for="user_login">Username</label>
        <input class="form-control" id="user_login" name="user[login]" required="true" size="30" type="text" />

Check out this demo.

Altering the demo slightly by adding .form-horizontal to the form tag changes some of that padding.

<form action="#" method="post" class="form-horizontal">

Check out this demo.

When in doubt, inspect in Chrome or use Firebug in Firefox to figure out things like padding and margins. Using .row within the form fails in edsioufi's fiddle because .row uses negative left and right margins thereby drawing the horizontal bounds of the divs classed .row beyond the bounds of the containing fieldsets.

Android checkbox style

Perhaps you want something like:

<style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
    <item name="android:checkboxStyle">@style/customCheckBoxStyle</item>

<style name="customCheckBoxStyle" parent="@android:style/Widget.CompoundButton.CheckBox">
    <item name="android:textColor">@android:color/black</item>

Note, the textColor item.

OR condition in Regex

I think what you need might be simply:

\d( \w)?

Note that your regex would have worked too if it was written as \d \w|\d instead of \d|\d \w.

This is because in your case, once the regex matches the first option, \d, it ceases to search for a new match, so to speak.

changing kafka retention period during runtime

I tested and used this command in kafka confluent V4.0.0 and apache kafka V 1.0.0 and 1.0.1

/opt/kafka/confluent-4.0.0/bin/kafka-configs --zookeeper XX.XX.XX.XX:2181 --entity-type topics --entity-name test --alter --add-config

test is the topic name.

I think it works well in other versions too

SQL Server: Filter output of sp_who2

You could save the results into a temp table, but it would be even better to go directly to the source on master.dbo.sysprocesses.

Here's a query that will return almost the exact same result as sp_who2:

SELECT  spid,
        loginame [Login],
        blocked BlkBy, DBName, 
        cmd Command,
        cpu CPUTime,
        physical_io DiskIO,
        last_batch LastBatch,
        [program_name] ProgramName   
FROM master.dbo.sysprocesses sp 
JOIN master.dbo.sysdatabases sd ON sp.dbid = sd.dbid
ORDER BY spid 

Now you can easily add any ORDER BY or WHERE clauses you like to get meaningful output.

Alternatively, you might consider using Activity Monitor in SSMS (Ctrl + Alt + A) as well

remove white space from the end of line in linux

Use either a simple blank * or [:blank:]* to remove all possible spaces at the end of the line:

sed 's/ *$//' file

Using the [:blank:] class you are removing spaces and tabs:

sed 's/[[:blank:]]*$//' file

Note this is POSIX, hence compatible in both GNU sed and BSD.

For just GNU sed you can use the GNU extension \s* to match spaces and tabs, as described in BaBL86's answer. See POSIX specifications on Basic Regular Expressions.

Let's test it with a simple file consisting on just lines, two with just spaces and the last one also with tabs:

$ cat -vet file
hello   $
bye   $
ha^I  $     # there is a tab here

Remove just spaces:

$ sed 's/ *$//' file | cat -vet -
ha^I$       # tab is still here!

Remove spaces and tabs:

$ sed 's/[[:blank:]]*$//' file | cat -vet -
ha$         # tab was removed!

How to update column value in laravel

I tried to update a field with

$table->update(['field' => 'val']);

But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"

Hope it will help someone :)

How to fix this Error: #include <gl/glut.h> "Cannot open source file gl/glut.h"

Visual Studio Community 2017

Go here : C:\Program Files (x86)\Windows Kits\10

and do whatever you were supposed to go in the given directory for VS 13.

in the lib folder, you will find some versions, I copied the 32-bit glut.lib files in amd and x86 and 64-bit glut.lib in arm64 and x64 directories in um folder for every version that I could find.

That worked for me.

EDIT : I tried this in windows 10, maybe you need to go to C:\Program Files (x86)\Windows Kits\8.1 folder for windows 8/8.1.

mailto using javascript

With JavaScript you can create a link 'on the fly' using something like:

var mail = document.createElement("a");
mail.href = "mailto:[email protected]";;

This is redirected by the browser to some mail client installed on the machine without losing the content of the current window ... and you would not need any API like 'jQuery'.

How does tuple comparison work in Python?

The python 2.5 documentation explains it well.

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]).

Unfortunately that page seems to have disappeared in the documentation for more recent versions.

Disable a Maven plugin defined in a parent POM

See if the plugin has a 'skip' configuration parameter. Nearly all do. if it does, just add it to a declaration in the child:


If not, then use:


How to solve a timeout error in Laravel 5

If you are hosting your Laravel app on Heroku, you can create custom_php.ini in the root of your project and simply add max_execution_time = 60

php - insert a variable in an echo string

echo '<p class="paragraph'.$i.'"></p>';

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

How can I install a .ipa file to my iPhone simulator

First of all, IPAs usually only have ARM slices because the App Store does not currently accept Simulator slices in uploads.

Secondly, as of Xcode 8.3 you can drag & drop a .app bundle into the Simulator window and it will be installed. You can find the app in your build products directory ~/Library/Developer/Xcode/DerivedData/projectname-xyzzyabcdefg/Build/Products/Debug-iphonesimulator if you want to save it or distribute it to other people.

To install from the command line use xcrun simctl install <device> <path>.

device can be the device UUID, its name, or booted which means the currently booted device.

String.Replace(char, char) method in C#

string temp = mystring.Replace("\n", " ");