Programs & Examples On #Disassembly

Involves turning "compiled" code (such as machine code, byte code or IR code) back in higher level assembly mnemonics.

How to disassemble a memory range with GDB?

Yeah, disassemble is not the best command to use here. The command you want is "x/i" (examine as instructions):

(gdb) x/i 0xdeadbeef

How to decompile an APK or DEX file on Android platform?

I have created a tool that combines dex2jar, jd-core and apktool: https://github.com/dirkvranckaert/AndroidDecompiler Just checkout the project locally and run the script as documented and you'll get all the resources and sources decompiled.

How to disassemble a binary executable in Linux to get the assembly code?

An interesting alternative to objdump is gdb. You don't have to run the binary or have debuginfo.

$ gdb -q ./a.out 
Reading symbols from ./a.out...(no debugging symbols found)...done.
(gdb) info functions 
All defined functions:

Non-debugging symbols:
0x00000000004003a8  _init
0x00000000004003e0  __libc_start_main@plt
0x00000000004003f0  __gmon_start__@plt
0x0000000000400400  _start
0x0000000000400430  deregister_tm_clones
0x0000000000400460  register_tm_clones
0x00000000004004a0  __do_global_dtors_aux
0x00000000004004c0  frame_dummy
0x00000000004004f0  fce
0x00000000004004fb  main
0x0000000000400510  __libc_csu_init
0x0000000000400580  __libc_csu_fini
0x0000000000400584  _fini
(gdb) disassemble main
Dump of assembler code for function main:
   0x00000000004004fb <+0>:     push   %rbp
   0x00000000004004fc <+1>:     mov    %rsp,%rbp
   0x00000000004004ff <+4>:     sub    $0x10,%rsp
   0x0000000000400503 <+8>:     callq  0x4004f0 <fce>
   0x0000000000400508 <+13>:    mov    %eax,-0x4(%rbp)
   0x000000000040050b <+16>:    mov    -0x4(%rbp),%eax
   0x000000000040050e <+19>:    leaveq 
   0x000000000040050f <+20>:    retq   
End of assembler dump.
(gdb) disassemble fce
Dump of assembler code for function fce:
   0x00000000004004f0 <+0>:     push   %rbp
   0x00000000004004f1 <+1>:     mov    %rsp,%rbp
   0x00000000004004f4 <+4>:     mov    $0x2a,%eax
   0x00000000004004f9 <+9>:     pop    %rbp
   0x00000000004004fa <+10>:    retq   
End of assembler dump.
(gdb)

With full debugging info it's even better.

(gdb) disassemble /m main
Dump of assembler code for function main:
9       {
   0x00000000004004fb <+0>:     push   %rbp
   0x00000000004004fc <+1>:     mov    %rsp,%rbp
   0x00000000004004ff <+4>:     sub    $0x10,%rsp

10        int x = fce ();
   0x0000000000400503 <+8>:     callq  0x4004f0 <fce>
   0x0000000000400508 <+13>:    mov    %eax,-0x4(%rbp)

11        return x;
   0x000000000040050b <+16>:    mov    -0x4(%rbp),%eax

12      }
   0x000000000040050e <+19>:    leaveq 
   0x000000000040050f <+20>:    retq   

End of assembler dump.
(gdb)

objdump has a similar option (-S)

How to implement a SQL like 'LIKE' operator in java?

To implement LIKE functions of sql in java you don't need regular expression in They can be obtained as:

String text = "apple";
text.startsWith("app"); // like "app%"
text.endsWith("le"); // like "%le"
text.contains("ppl"); // like "%ppl%"

Hash function that produces short hashes?

You need to hash the contents to come up with a digest. There are many hashes available but 10-characters is pretty small for the result set. Way back, people used CRC-32, which produces a 33-bit hash (basically 4 characters plus one bit). There is also CRC-64 which produces a 65-bit hash. MD5, which produces a 128-bit hash (16 bytes/characters) is considered broken for cryptographic purposes because two messages can be found which have the same hash. It should go without saying that any time you create a 16-byte digest out of an arbitrary length message you're going to end up with duplicates. The shorter the digest, the greater the risk of collisions.

However, your concern that the hash not be similar for two consecutive messages (whether integers or not) should be true with all hashes. Even a single bit change in the original message should produce a vastly different resulting digest.

So, using something like CRC-64 (and base-64'ing the result) should get you in the neighborhood you're looking for.

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

It registers the driver; something of the form:

public class SomeDriver implements Driver {
  static {
    try {
      DriverManager.registerDriver(new SomeDriver());
    } catch (SQLException e) {
      // TODO Auto-generated catch block
    }
  }

  //etc: implemented methods
}

MySQL: How to allow remote connection to mysql

Please follow the below mentioned steps inorder to set the wildcard remote access for MySQL User.

(1) Open cmd.

(2) navigate to path C:\Program Files\MySQL\MySQL Server 5.X\bin and run this command.

mysql -u root -p

(3) Enter the root password.

(4) Execute the following command to provide the permission.

GRANT ALL PRIVILEGES ON *.* TO 'USERNAME'@'IP' IDENTIFIED BY 'PASSWORD';

USERNAME: Username you wish to connect to MySQL server.

IP: Public IP address from where you wish to allow access to MySQL server.

PASSWORD: Password of the username used.

IP can be replaced with % to allow user to connect from any IP address.

(5) Flush the previleges by following command and exit.

FLUSH PRIVILEGES;

exit; or \q

enter image description here

How to tar certain file types in all subdirectories?

find ./ -type f -name "*.php" -o -name "*.html" -printf '%P\n' |xargs tar -I 'pigz -9' -cf target.tgz

for multicore or just for one core:

find ./ -type f -name "*.php" -o -name "*.html" -printf '%P\n' |xargs tar -czf target.tgz

How can I determine if a date is between two dates in Java?

import java.util.Date;

public class IsDateBetween {

public static void main (String[] args) {

          IsDateBetween idb=new IsDateBetween("12/05/2010"); // passing your Date
 }
 public IsDateBetween(String dd) {

       long  from=Date.parse("01/01/2000");  // From some date

       long to=Date.parse("12/12/2010");     // To Some Date

       long check=Date.parse(dd);

       int x=0;

      if((check-from)>0 && (to-check)>0)
      {
             x=1;
      }

 System.out.println ("From Date is greater Than  ToDate : "+x);
}   

}

Can Twitter Bootstrap alerts fade in as well as out?

For 2.3 and above, just add:

$(".alert").fadeOut(3000 );

bootstrap:

<div class="alert success fade in" data-alert="alert" >
    <a class="close" data-dismiss="alert" href="#">&times;</a>
    // code 
</div>

Works in all browsers.

Android: How to open a specific folder via Intent and show its content in a file browser?

Today, you should be representing a folder using its content: URI as obtained from the Storage Access Framework, and opening it should be as simple as:

Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);

Alas, the Files app currently contains a bug that causes it to crash when you try this using the external storage provider. Folders from third party providers however can be displayed in this way.

Is it possible to refresh a single UITableViewCell in a UITableView?

Here is a UITableView extension with Swift 5:

import UIKit

extension UITableView
{    
    func updateRow(row: Int, section: Int = 0)
    {
        let indexPath = IndexPath(row: row, section: section)

        self.beginUpdates()
        self.reloadRows(at: [indexPath as IndexPath], with: UITableView.RowAnimation.automatic)
        self.endUpdates()
    }

}

Call with

self.tableView.updateRow(row: 1)

click() event is calling twice in jquery

My simple answer was to turn the click bind into a function and call that from the onclick of the element - worked a treat! whereas none of the above did

Submit two forms with one button

You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....

what difference does this make?

For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript method:

Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _ 
"document.forms[0]['TextBox1'].focus();", True)

This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.

But, if instead it was written like this (using the RegisterClientScriptBlock method):

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)

Focus will not get to the textbox control and a JavaScript error will be generated on the page

The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.

what does "error : a nonstatic member reference must be relative to a specific object" mean?

CPMSifDlg::EncodeAndSend() method is declared as non-static and thus it must be called using an object of CPMSifDlg. e.g.

CPMSifDlg obj;
return obj.EncodeAndSend(firstName, lastName, roomNumber, userId, userFirstName, userLastName);

If EncodeAndSend doesn't use/relate any specifics of an object (i.e. this) but general for the class CPMSifDlg then declare it as static:

class CPMSifDlg {
...
  static int EncodeAndSend(...);
  ^^^^^^
};

C free(): invalid pointer

You can't call free on the pointers returned from strsep. Those are not individually allocated strings, but just pointers into the string s that you've already allocated. When you're done with s altogether, you should free it, but you do not have to do that with the return values of strsep.

using mailto to send email with an attachment

what about this

<FORM METHOD="post" ACTION="mailto:[email protected]" ENCTYPE="multipart/form-data">
Attachment: <INPUT TYPE="file" NAME="attachedfile" MAXLENGTH=50 ALLOW="text/*" >
 <input type="submit" name="submit" id="submit" value="Email"/>
</FORM>

How to align a div inside td element using CSS class

I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.

What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;

If you do go down the inline-block route then you may have to consider my favorite IE hack.

width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only

Happy Coding :)

:not(:empty) CSS selector is not working?

You could try using :placeholder-shown...

_x000D_
_x000D_
input {
  padding: 10px 15px;
  font-size: 16px;
  border-radius: 5px;
  border: 2px solid lightblue;
  outline: 0;
  font-weight:bold;
  transition: border-color 200ms;
  font-family: sans-serif;
}

.validation {
  opacity: 0;
  font-size: 12px;
  font-family: sans-serif;
  color: crimson;
  transition: opacity;
}

input:required:valid {
  border-color: forestgreen;
}

input:required:invalid:not(:placeholder-shown) {
  border-color: crimson;
}

input:required:invalid:not(:placeholder-shown) + .validation {
  opacity: 1;
}

  
_x000D_
<input type="email" placeholder="e-mail" required>
<div class="validation">Not valid</span>
_x000D_
_x000D_
_x000D_

no great support though... caniuse

What is PostgreSQL equivalent of SYSDATE from Oracle?

You may want to use statement_timestamp(). This give the timestamp when the statement was executed. Whereas NOW() and CURRENT_TIMESTAMP give the timestamp when the transaction started.

More details in the manual

Select datatype of the field in postgres

If you like 'Mike Sherrill' solution but don't want to use psql, I used this query to get the missing information:

select column_name,
case 
    when domain_name is not null then domain_name
    when data_type='character varying' THEN 'varchar('||character_maximum_length||')'
    when data_type='numeric' THEN 'numeric('||numeric_precision||','||numeric_scale||')'
    else data_type
end as myType
from information_schema.columns
where table_name='test'

with result:

column_name |     myType
-------------+-------------------
 test_id     | test_domain
 test_vc     | varchar(15)
 test_n      | numeric(15,3)
 big_n       | bigint
 ip_addr     | inet

Difference between volatile and synchronized in Java

synchronized is method level/block level access restriction modifier. It will make sure that one thread owns the lock for critical section. Only the thread,which own a lock can enter synchronized block. If other threads are trying to access this critical section, they have to wait till current owner releases the lock.

volatile is variable access modifier which forces all threads to get latest value of the variable from main memory. No locking is required to access volatile variables. All threads can access volatile variable value at same time.

A good example to use volatile variable : Date variable.

Assume that you have made Date variable volatile. All the threads, which access this variable always get latest data from main memory so that all threads show real (actual) Date value. You don't need different threads showing different time for same variable. All threads should show right Date value.

enter image description here

Have a look at this article for better understanding of volatile concept.

Lawrence Dol cleary explained your read-write-update query.

Regarding your other queries

When is it more suitable to declare variables volatile than access them through synchronized?

You have to use volatile if you think all threads should get actual value of the variable in real time like the example I have explained for Date variable.

Is it a good idea to use volatile for variables that depend on input?

Answer will be same as in first query.

Refer to this article for better understanding.

SQLiteDatabase.query method

tableColumns

  • null for all columns as in SELECT * FROM ...
  • new String[] { "column1", "column2", ... } for specific columns as in SELECT column1, column2 FROM ... - you can also put complex expressions here:
    new String[] { "(SELECT max(column1) FROM table1) AS max" } would give you a column named max holding the max value of column1

whereClause

  • the part you put after WHERE without that keyword, e.g. "column1 > 5"
  • should include ? for things that are dynamic, e.g. "column1=?" -> see whereArgs

whereArgs

  • specify the content that fills each ? in whereClause in the order they appear

the others

  • just like whereClause the statement after the keyword or null if you don't use it.

Example

String[] tableColumns = new String[] {
    "column1",
    "(SELECT max(column1) FROM table2) AS max"
};
String whereClause = "column1 = ? OR column1 = ?";
String[] whereArgs = new String[] {
    "value1",
    "value2"
};
String orderBy = "column1";
Cursor c = sqLiteDatabase.query("table1", tableColumns, whereClause, whereArgs,
        null, null, orderBy);

// since we have a named column we can do
int idx = c.getColumnIndex("max");

is equivalent to the following raw query

String queryString =
    "SELECT column1, (SELECT max(column1) FROM table1) AS max FROM table1 " +
    "WHERE column1 = ? OR column1 = ? ORDER BY column1";
sqLiteDatabase.rawQuery(queryString, whereArgs);

By using the Where/Bind -Args version you get automatically escaped values and you don't have to worry if input-data contains '.

Unsafe: String whereClause = "column1='" + value + "'";
Safe: String whereClause = "column1=?";

because if value contains a ' your statement either breaks and you get exceptions or does unintended things, for example value = "XYZ'; DROP TABLE table1;--" might even drop your table since the statement would become two statements and a comment:

SELECT * FROM table1 where column1='XYZ'; DROP TABLE table1;--'

using the args version XYZ'; DROP TABLE table1;-- would be escaped to 'XYZ''; DROP TABLE table1;--' and would only be treated as a value. Even if the ' is not intended to do bad things it is still quite common that people have it in their names or use it in texts, filenames, passwords etc. So always use the args version. (It is okay to build int and other primitives directly into whereClause though)

How to update Ruby to 1.9.x on Mac?

As previously mentioned, the bundler version may be too high for your version of rails.

I ran into the same problem using Rails 3.0.1 which requires Bundler v1.0.0 - v1.0.22

Check your bundler version using: gem list bundler

If your bundler version is not within the appropriate range, I found this solution to work: rvm @global do gem uninstall bundler

Note: rvm is required for this solution... another case for why you should be using rvm in the first place.

How to split a comma separated string and process in a loop using JavaScript

My two cents, adding trim to remove the initial whitespaces left in sAc's answer.

var str = 'Hello, World, etc';
var str_array = str.split(',');

for(var i = 0; i < str_array.length; i++) {
   // Trim the excess whitespace.
   str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
   // Add additional code here, such as:
   alert(str_array[i]);
}

Edit:

After getting several upvotes on this answer, I wanted to revisit this. If you want to split on comma, and perform a trim operation, you can do it in one method call without any explicit loops due to the fact that split will also take a regular expression as an argument:

'Hello, cruel , world!'.split(/\s*,\s*/);
//-> ["Hello", "cruel", "world!"]

This solution, however, will not trim the beginning of the first item and the end of the last item which is typically not an issue.

And so to answer the question in regards to process in a loop, if your target browsers support ES5 array extras such as the map or forEach methods, then you could just simply do the following:

myStringWithCommas.split(/\s*,\s*/).forEach(function(myString) {
    console.log(myString);
});

Node.js: Gzip compression?

If you're using Express, then you can use its compress method as part of the configuration:

var express = require('express');
var app = express.createServer();
app.use(express.compress());

And you can find more on compress here: http://expressjs.com/api.html#compress

And if you're not using Express... Why not, man?! :)

NOTE: (thanks to @ankitjaininfo) This middleware should be one of the first you "use" to ensure all responses are compressed. Ensure that this is above your routes and static handler (eg. how I have it above).

NOTE: (thanks to @ciro-costa) Since express 4.0, the express.compress middleware is deprecated. It was inherited from connect 3.0 and express no longer includes connect 3.0. Check Express Compression for getting the middleware.

Importing CSV File to Google Maps

For generating the KML file from your CSV file (or XLS), you can use MyGeodata online GIS Data Converter. Here is the CSV to KML How-To.

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

Get GPS location from the web browser

If you use the Geolocation API, it would be as simple as using the following code.

navigator.geolocation.getCurrentPosition(function(location) {
  console.log(location.coords.latitude);
  console.log(location.coords.longitude);
  console.log(location.coords.accuracy);
});

You may also be able to use Google's Client Location API.

This issue has been discussed in Is it possible to detect a mobile browser's GPS location? and Get position data from mobile browser. You can find more information there.

How can I determine the current CPU utilization from the shell?

Maybe something like this

ps -eo pid,pcpu,comm

And if you like to parse and maybe only look at some processes.

#!/bin/sh
ps -eo pid,pcpu,comm | awk '{if ($2 > 4) print }' >> ~/ps_eo_test.txt

Calculate summary statistics of columns in dataframe

Now there is the pandas_profiling package, which is a more complete alternative to df.describe().

If your pandas dataframe is df, the below will return a complete analysis including some warnings about missing values, skewness, etc. It presents histograms and correlation plots as well.

import pandas_profiling
pandas_profiling.ProfileReport(df)

See the example notebook detailing the usage.

How to return JSon object

First of all, there's no such thing as a JSON object. What you've got in your question is a JavaScript object literal (see here for a great discussion on the difference). Here's how you would go about serializing what you've got to JSON though:

I would use an anonymous type filled with your results type:

string json = JsonConvert.SerializeObject(new
{
    results = new List<Result>()
    {
        new Result { id = 1, value = "ABC", info = "ABC" },
        new Result { id = 2, value = "JKL", info = "JKL" }
    }
});

Also, note that the generated JSON has result items with ids of type Number instead of strings. I doubt this will be a problem, but it would be easy enough to change the type of id to string in the C#.

I'd also tweak your results type and get rid of the backing fields:

public class Result
{
    public int id { get ;set; }
    public string value { get; set; }
    public string info { get; set; }
}

Furthermore, classes conventionally are PascalCased and not camelCased.

Here's the generated JSON from the code above:

{
  "results": [
    {
      "id": 1,
      "value": "ABC",
      "info": "ABC"
    },
    {
      "id": 2,
      "value": "JKL",
      "info": "JKL"
    }
  ]
}

Determine the process pid listening on a certain port

netstat -nlp should tell you the PID of what's listening on which port.

Set style for TextView programmatically

When using custom views that may use style inheritance (or event styleable attributes), you have to modify the second constructor in order not to lose the style. This worked for me, without needing to use setTextAppearence():

public CustomView(Context context, AttributeSet attrs) {
    this(context, attrs, attrs.getStyleAttribute());
}

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

java.lang.ClassNotFoundException is indicate that class is not found in class path. it could be the version of log4j is not compatible. check for different log4j version.

Drop unused factor levels in a subsetted data frame

If you don't want this behaviour, don't use factors, use character vectors instead. I think this makes more sense than patching things up afterwards. Try the following before loading your data with read.table or read.csv:

options(stringsAsFactors = FALSE)

The disadvantage is that you're restricted to alphabetical ordering. (reorder is your friend for plots)

Foreach loop in java for a custom object list

You can fix your example with the iterator pattern by changing the parametrization of the class:

List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Iterator<Room> i = rooms.iterator(); i.hasNext(); ) {
  String item = i.next();
  System.out.println(item);
}

or much simpler way:

List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Room room : rooms) {
  System.out.println(room);
}

How to create an HTTPS server in Node.js?

To enable your app to listen for both http and https on ports 80 and 443 respectively, do the following

Create an express app:

var express = require('express');
var app = express();

The app returned by express() is a JavaScript function. It can be be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app using the same code base.

You can do so as follows:

var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();

var options = {
  key: fs.readFileSync('/path/to/key.pem'),
  cert: fs.readFileSync('/path/to/cert.pem')
};

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);

For complete detail see the doc

Compiling C++11 with g++

If you want to keep the GNU compiler extensions, use -std=gnu++0x rather than -std=c++0x. Here's a quote from the man page:

The compiler can accept several base standards, such as c89 or c++98, and GNU dialects of those standards, such as gnu89 or gnu++98. By specifying a base standard, the compiler will accept all programs following that standard and those using GNU extensions that do not contradict it. For example, -std=c89 turns off certain features of GCC that are incompatible with ISO C90, such as the "asm" and "typeof" keywords, but not other GNU extensions that do not have a meaning in ISO C90, such as omitting the middle term of a "?:" expression. On the other hand, by specifying a GNU dialect of a standard, all features the compiler support are enabled, even when those features change the meaning of the base standard and some strict-conforming programs may be rejected. The particular standard is used by -pedantic to identify which features are GNU extensions given that version of the standard. For example-std=gnu89 -pedantic would warn about C++ style // comments, while -std=gnu99 -pedantic would not.

Delete item from state array in react

removePeople(e){
    var array = this.state.people;
    var index = array.indexOf(e.target.value); // Let's say it's Bob.
    array.splice(index,1);
}

Redfer doc for more info

Git 'fatal: Unable to write new index file'

I had/have this problem too. In my case, none of the explanations applied:

  • enough disk room
  • I had sufficient privileges, I can write the index file, I can rename it, I can create it, the workaround did nothing
  • restarting windows didn't work
  • index not locked by processes

Until I found out that once I accessed the windows folder via another (linux) computer, git worked without complaints. It must have something to do with the git version I use from my normal debian buster computer: git 1.2.20 is giving me the 'unable to write new index' error, whereas from a ubuntu fuzzy virtualbox (git 1.2.2) adds the file without problems.

Checking if date is weekend PHP

If you have PHP >= 5.1:

function isWeekend($date) {
    return (date('N', strtotime($date)) >= 6);
}

otherwise:

function isWeekend($date) {
    $weekDay = date('w', strtotime($date));
    return ($weekDay == 0 || $weekDay == 6);
}

How do I tidy up an HTML file's indentation in VI?

I use this script: https://github.com/maksimr/vim-jsbeautify

In the above link you have all the info:

  1. Install
  2. Configure (copy from the first example)
  3. Run :call HtmlBeautify()

Does the job beautifully!

Python list / sublist selection -1 weirdness

If you want to get a sub list including the last element, you leave blank after colon:

>>> ll=range(10)
>>> ll
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ll[5:]
[5, 6, 7, 8, 9]
>>> ll[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Meaning of "[: too many arguments" error from if [] (square brackets)

I have had same problem with my scripts. But when I did some modifications it worked for me. I did like this :-

export k=$(date "+%k");
if [ $k -ge 16 ] 
    then exit 0; 
else 
    echo "good job for nothing"; 
fi;

that way I resolved my problem. Hope that will help for you too.

How to sort a Pandas DataFrame by index?

Slightly more compact:

df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)

Note:

python: how to get information about a function?

Try

help(my_list)

to get built-in help messages.

How to convert an OrderedDict into a regular dict in python3

Even though this is a year old question, I would like to say that using dict will not help if you have an ordered dict within the ordered dict. The simplest way that could convert those recursive ordered dict will be

import json
from collections import OrderedDict
input_dict = OrderedDict([('method', 'constant'), ('recursive', OrderedDict([('m', 'c')]))])
output_dict = json.loads(json.dumps(input_dict))
print output_dict

How to check that a string is parseable to a double?

Something like below should suffice :-

String decimalPattern = "([0-9]*)\\.([0-9]*)";  
String number="20.00";  
boolean match = Pattern.matches(decimalPattern, number);
System.out.println(match); //if true then decimal else not  

How to implement "Access-Control-Allow-Origin" header in asp.net

Another option is to add it on the web.config directly:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://www.yourSite.com" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
      </customHeaders>
    </httpProtocol>

... I found this in here

How to add icons to React Native app

I would use a service to scale the icon correctly. http://makeappicon.com/ seems good. Use a image on the larger size as scaling up a smaller image can lead to the larger icons being pixelated. That site will give you sizes for both iOS and Android.

From there its just a matter of setting the icon like you would a regular native app.

https://help.apple.com/xcode/mac/8.0/#/dev10510b1f7

Set icon for Android application

String replacement in batch file

I was able to use Joey's Answer to create a function:

Use it as:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

SET "MYTEXT=jump over the chair"
echo !MYTEXT!
call:ReplaceText "!MYTEXT!" chair table RESULT
echo !RESULT!

GOTO:EOF

And these Functions to the bottom of your Batch File.

:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B

:ReplaceText
::Replace Text In String
::USE:
:: CALL:ReplaceText "!OrginalText!" OldWordToReplace NewWordToUse  Result
::Example
::SET "MYTEXT=jump over the chair"
::  echo !MYTEXT!
::  call:ReplaceText "!MYTEXT!" chair table RESULT
::  echo !RESULT!
::
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: "!MYTEXT!" !chair! !table! !RESULT!
:: ^^Because it has a ! around the chair table and RESULT
:: Remember to add quotes "" around the MYTEXT Variable when calling.
:: If you don't add quotes, it won't treat it as a single string
::
set "OrginalText=%~1"
set "OldWord=%~2"
set "NewWord=%~3"
call set OrginalText=%%OrginalText:!OldWord!=!NewWord!%%
SET %4=!OrginalText!
GOTO:EOF

And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.

How to style the menu items on an Android action bar

I did this way:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="actionMenuTextAppearance">@style/MenuTextAppearance</item>
    <item name="android:actionMenuTextAppearance">@style/MenuTextAppearance</item>
    <item name="actionMenuTextColor">@color/colorAccent</item>
</style>

<style name="MenuTextAppearance" >
    <item name="android:textAppearance">@android:style/TextAppearance.Large</item>
    <item name="android:textSize">20sp</item>
    <item name="android:textStyle">bold</item>
</style>

How to hide Android soft keyboard on EditText

Simply Use EditText.setFocusable(false); in activity

or use in xml

android:focusable="false"

Difference between try-catch and throw in java

Try/catch and throw clause are for different purposes. So they are not alternative to each other but they are complementary.

  1. If you have throw some checked exception in your code, it should be inside some try/catch in codes calling hierarchy.

  2. Conversely, you need try/catch block only if there is some throw clause inside the code (your code or the API call) that throws checked exception.

Sometimes, you may want to throw exception if particular condition occurred which you want to handle in calling code block and in some cases handle some exception catch block and throw a same or different exception again to handle in calling block.

ToList().ForEach in Linq

Try with this combination of Lambda expressions:

employees.ToList().ForEach(emp => 
{
    collection.AddRange(emp.Departments);
    emp.Departments.ToList().ForEach(dept => dept.SomeProperty = null);                    
});

What does `return` keyword mean inside `forEach` function?

From the Mozilla Developer Network:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Early termination may be accomplished with:

The other Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.

The name 'ViewBag' does not exist in the current context

I had already tried deleting the bin and obj file and restarting VS and had no luck.

I've also had this issue many times and it's a pain to solve each time. Often it is due to the web.config file not having the correct version of one of the references. This means click on the reference in Visual Studio to see the version in the property tab, and then match it to the version in the web.config files.

Another way is (if possible) upgrade to a later version of the .net framework and then deleting bin/obj files and restarting Visual Studio. I can only assume it's changing something in the

A quick check of the diff between the csproj file doesn't actually show any major difference... But the differences it did show was (I've added (remove) to show the old line)

<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> (remove)
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>(remove)
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>

In the Web.Config file (not the one in View)

<add key="webpages:Version" value="2.0.0.0" /> (remove)
<add key="webpages:Version" value="3.0.0.0"/>

It also added (to the same web.config file) but I manually removed it

 <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>

Finally, in the Package Manager Console, add update-package

Run the website locally and see any compilation errors which was fixed by my second paragraph (matching the versions of the references)

Install pdo for postgres Ubuntu

Pecl PDO package is now deprecated. By the way the debian package php5-pgsql now includes both the regular and the PDO driver, so just:

apt-get install php-pgsql

Apache also needs to be restarted before sites can use it:

sudo systemctl restart apache2

How can I brew link a specific version?

brew switch libfoo mycopy

You can use brew switch to switch between versions of the same package, if it's installed as versioned subdirectories under Cellar/<packagename>/

This will list versions installed ( for example I had Cellar/sdl2/2.0.3, I've compiled into Cellar/sdl2/2.0.4)

brew info sdl2

Then to switch between them

brew switch sdl2 2.0.4
brew info 

Info now shows * next to the 2.0.4

To install under Cellar/<packagename>/<version> from source you can do for example

cd ~/somewhere/src/foo-2.0.4
./configure --prefix $(brew --Cellar)/foo/2.0.4
make

check where it gets installed with

make install -n

if all looks correct

make install

Then from cd $(brew --Cellar) do the switch between version.

I'm using brew version 0.9.5

Android: Cancel Async Task

create some member variables in your activity like

YourAsyncTask mTask;
Dialog mDialog;

use these for your dialog and task;

in onPause() simply call

if(mTask!=null) mTask.cancel(); 
if(mDialog!=null) mDialog.dismiss();

Excel 2007: How to display mm:ss format not as a DateTime (e.g. 73:07)?

To make life easier when entering multiple dates/times it is possible to use a custom format to remove the need to enter the colon, and the leading "hour" 0. This however requires a second field for the numerical date to be stored, as the displayed date from the custom format is in base 10.

Displaying a number as a time (no need to enter colons, but no time conversion)

For displaying the times on the sheet, and for entering them without having to type the colon set the cell format to custom and use:

0/:00

Then enter your time. For example, if you wanted to enter 62:30, then you would simply type 6230 and your custom format would visually insert a colon 2 decimal points from the right.

If you only need to display the times, stop here.

Converting number to time

If you need to be able to calculate with the times, you will need to convert them from base 10 into the time format.

This can be done with the following formula (change A2 to the relevant cell reference):

=TIME(0,TRUNC(A2/100),MOD(A2,100))

  • =TIME starts the number to time conversion
  • We don't need hours, so enter 0, at the beginning of the formula, as the format is always hh,mm,ss (to display hours and minutes instead of minutes and seconds, place the 0 at the end of the formula).
  • For the minutes, TRUNC(A2/100), discards the rightmost 2 digits.
  • For the seconds, MOD(A2,100) keeps the rightmost 2 digits and discards everything to the left.

The above formula was found and adapted from this article: PC Mag.com - Easy Date and Time Entry in Excel

Alternatively, you could skip the 0/:00 custom formatting, and just enter your time in a cell to be referenced of the edge of the visible workspace or on another sheet as you would for the custom formatting (ie: 6230 for 62:30)

Then change the display format of the cells with the formula to [m]:ss as @Sean Chessire suggested.

Here is a screen shot to show what I mean.

Excel screen shot showing time conversion formula and custom formatting

Sending data through POST request from a node.js server to a node.js server

You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.

Just do the following for executing a POST request:

var requestify = require('requestify');

requestify.post('http://example.com', {
    hello: 'world'
})
.then(function(response) {
    // Get the response body (JSON parsed or jQuery object for XMLs)
    response.getBody();
});

How do I check if a string contains another string in Objective-C?

So personally I really hate NSNotFound but understand its necessity.

But some people may not understand the complexities of comparing against NSNotFound

For example, this code:

- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
    if([string rangeOfString:otherString].location != NSNotFound)
        return YES;
    else
        return NO;
}

has its problems:

1) Obviously if otherString = nil this code will crash. a simple test would be:

NSLog(@"does string contain string - %@", [self doesString:@"hey" containString:nil] ? @"YES": @"NO");

results in !! CRASH !!

2) What is not so obvious to someone new to objective-c is that the same code will NOT crash when string = nil. For example, this code:

NSLog(@"does string contain string - %@", [self doesString:nil containString:@"hey"] ? @"YES": @"NO");

and this code:

NSLog(@"does string contain string - %@", [self doesString:nil containString:nil] ? @"YES": @"NO");

will both result in

does string contains string - YES

Which is clearly NOT what you want.

So the better solution that I believe works is to use the fact that rangeOfString returns the length of 0 so then a better more reliable code is this:

- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
    if(otherString && [string rangeOfString:otherString].length)
        return YES;
    else
        return NO;
}

OR SIMPLY:

- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
    return (otherString && [string rangeOfString:otherString].length);
}

which will for cases 1 and 2 will return

does string contains string - NO

That's my 2 cents ;-)

Please check out my Gist for more helpful code.

Android 5.0 - Add header/footer to a RecyclerView

I would just add an alternative to all those HeaderRecyclerViewAdapter implementation. CompoundAdapter:

https://github.com/negusoft/CompoundAdapter-android

It is a more flexible approach, since you can create a AdapterGroup out of Adapters. For the header example, use your adapter as it is, along with an adapter containing one item for the header:

AdapterGroup adapterGroup = new AdapterGroup();
adapterGroup.addAdapter(SingleAdapter.create(R.layout.header));
adapterGroup.addAdapter(new MyAdapter(...));

recyclerView.setAdapter(adapterGroup);

It is fairly simple and readable. You can implement more complex adapter easily using the same principle.

Should I use the datetime or timestamp data type in MySQL?

The timestamp data type stores date and time, but in UTC format, not in the current timezone format as datetime does. And when you fetch data, timestamp again converts that into the current timezone time.

So suppose you are in USA and getting data from a server which has a time zone of USA. Then you will get the date and time according to the USA time zone. The timestamp data type column always get updated automatically when its row gets updated. So it can be useful to track when a particular row was updated last time.

For more details you can read the blog post Timestamp Vs Datetime .

What is the best way to create and populate a numbers table?

I use numbers tables for primarily dummying up reports in BIRT without having to fiddle around with dynamic creation of recordsets.

I do the same with dates, having a table spanning from 10 years in the past to 10 years in the future (and hours of the day for more detailed reporting). It's a neat trick to be able to get values for all dates even if your 'real' data tables don't have data for them.

I have a script which I use to create these, something like (this is from memory):

drop table numbers; commit;
create table numbers (n integer primary key); commit;
insert into numbers values (0); commit;
insert into numbers select n+1 from numbers; commit;
insert into numbers select n+2 from numbers; commit;
insert into numbers select n+4 from numbers; commit;
insert into numbers select n+8 from numbers; commit;
insert into numbers select n+16 from numbers; commit;
insert into numbers select n+32 from numbers; commit;
insert into numbers select n+64 from numbers; commit;

The number of rows doubles with each line so it doesn't take a lot to produce truly huge tables.

I'm not sure I agree with you that it's important to be created fast since you only create it once. The cost of that is amortized over all the accesses to it, rendering that time fairly insignificant.

CSS3 Spin Animation

You haven't specified any keyframes. I made it work here.

div {
    margin: 20px;
    width: 100px; 
    height: 100px;    
    background: #f00;
    -webkit-animation: spin 4s infinite linear;
}

@-webkit-keyframes spin {
    0%  {-webkit-transform: rotate(0deg);}
    100% {-webkit-transform: rotate(360deg);}   
}

You can actually do lots of really cool stuff with this. Here is one I made earlier.

:)

N.B. You can skip having to write out all the prefixes if you use -prefix-free.

Excel - Button to go to a certain sheet

You have to add Button to excel sheet(say sheet1) from which you can go to another sheet(say sheet2).

Button can be added from Developer tab in excel. If developer tab is not there follow below steps to enable.

GOTO file -> options -> Customize Ribbon -> enable checkbox of developer on right panel -> Done.

To Add button :-

Developer Tab -> Insert -> choose first item button -> choose location of button-> Done.

To give name for button :-

Right click on button -> edit text.

To add code for going to sheet2 :-

Right click on button -> Assign Macro -> New -> (microsoft visual basic will open to code for button) -> paste below code

Worksheets("Sheet2").Visible = True
Worksheets("Sheet2").Activate

Save the file using 'Excel Macro Enable Template(*.xltm)' By which the code is appended with excel sheet.

Is there a way to @Autowire a bean that requires constructor arguments?

Most answers are fairly old, so it might have not been possible back then, but there actually is a solution that satisfies all the possible use-cases.

So right know the answers are:

  • Not providing a real Spring component (the factory design)
  • or does not fit every situation (using @Value you have to have the value in a configuration file somewhere)

The solution to solve those issues is to create the object manually using the ApplicationContext:

@Component
public class MyConstructorClass
{
    String var;

    public MyConstructorClass() {}
    public MyConstructorClass(String constrArg) {
        this.var = var;
    }
}

@Service
public class MyBeanService implements ApplicationContextAware
{
    private static ApplicationContext applicationContext;

    MyConstructorClass myConstructorClass;

    public MyBeanService()
    {
        // Creating the object manually
        MyConstructorClass myObject = new MyConstructorClass("hello world");
        // Initializing the object as a Spring component
        AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
        factory.autowireBean(myObject);
        factory.initializeBean(myObject, myObject.getClass().getSimpleName());
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }
}

This is a cool solution because:

  • It gives you access to all the Spring functionalities on your object (@Autowired obviously, but also @Async for example),
  • You can use any source for your constructor arguments (configuration file, computed value, hard-coded value, ...),
  • It only requires you to add a few lines of code without having to change anything.
  • It can also be used to dynamically create a unknown number of instances of a Spring-managed class (I'm using it to create multiple asynchronous executors on the fly for example)

The only thing to keep in mind is that you have to have a constructor that takes no arguments (and that can be empty) in the class you want to instantiate (or an @Autowired constructor if you need it).

Is there a standard sign function (signum, sgn) in C/C++?

double signof(double a) { return (a == 0) ? 0 : (a<0 ? -1 : 1); }

Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

I was getting this error too and the reason ended up being wrong call url. I am leaving this answer here, if someone else happens to mix the urls and getting this error. Took me hours to realize I had wrong URL.

Error I got (HTTP code 400):

{
    "error": "unsupported_grant_type",
    "error_description": "grant type not supported"
}

I was calling:

https://MY_INSTANCE.lightning.force.com

While the correct URL would have been:

https://MY_INSTANCE.cs110.my.salesforce.com

How can two strings be concatenated?

help.search() is a handy function, e.g.

> help.search("concatenate")

will lead you to paste().

Getting session value in javascript

protected void Page_Load(object sender, EventArgs e)
    {
        Session["MyTest"] = "abcd";

        String csname = "OnSubmitScript";
        Type cstype = this.GetType();

        // Get a ClientScriptManager reference from the Page class.
        ClientScriptManager cs = Page.ClientScript;

        // Check to see if the OnSubmit statement is already registered.
        if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
        {
            string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession()  ; ";
            cs.RegisterOnSubmitStatement(cstype, csname, cstext);
        }

        if (TextBox1.Text.Equals("")) { }
        else {
              Session["MyTest"] = TextBox1.Text;
        }

    }


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

    <script language=javascript type="text/javascript">
        function getMyvalSession() {

             var txt = "efgh";
             var ff = '<%=Session["MyTest"] %>' + txt;
             return ff ;
        }
    </script>

</head>
<body>

    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"  AutoPostBack=true ></asp:TextBox>
     <input type="submit"  value="Submit" />
    </div>
    </form>
</body>
</html>

Get a substring of a char*

char subbuff[5];
memcpy( subbuff, &buff[10], 4 );
subbuff[4] = '\0';

Job done :)

In SQL how to compare date values?

Nevermind found an answer. Ty the same for anyone who was willing to reply.

WHERE DATEDIFF(mydata,'2008-11-20') >=0;

How to add double quotes to a string that is inside a variable?

You can also include the double quotes into single quotes.

string str = '"' + "How to add doublequotes" + '"';

How to sum all column values in multi-dimensional array?

We need to check first if array key does exist.

CODE:

$sum = array();
foreach ($array as $key => $sub_array) {
    foreach ($sub_array as $sub_key => $value) {

        //If array key doesn't exists then create and initize first before we add a value.
        //Without this we will have an Undefined index error.
        if( ! array_key_exists($sub_key, $sum)) $sum[$sub_key] = 0;

        //Add Value
        $sum[$sub_key]+=$value;
    }
}
print_r($sum);

OUTPUT With Array Key Validation:

Array
(
    [gozhi] => 10
    [uzorong] => 1
    [ngangla] => 8
    [langthel] => 10
)

OUTPUT Without Array Key Validation:

Notice: Undefined index: gozhi in F:\web\index.php on line 37

Notice: Undefined index: uzorong in F:\web\index.php on line 37

Notice: Undefined index: ngangla in F:\web\index.php on line 37

Notice: Undefined index: langthel in F:\web\index.php on line 37

Array
(
    [gozhi] => 10
    [uzorong] => 1
    [ngangla] => 8
    [langthel] => 10
)

This is a bad practice although it prints the output. Always check first if key does exist.

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

The alternative would be to use ServletContext.getResource() which returns a URI. This URI may be a 'file:' URL, but there's no guarantee for that.

You don't need it to be a file:... URL. You just need it to be a URL that your JVM can read--and it will be.

Given a class, see if instance has method (Ruby)

I think there is something wrong with method_defined? in Rails. It may be inconsistent or something, so if you use Rails, it's better to use something from attribute_method?(attribute).

"testing for method_defined? on ActiveRecord classes doesn't work until an instantiation" is a question about the inconsistency.

history.replaceState() example?

look at the example

window.history.replaceState({
    foo: 'bar'
}, 'Nice URL Title', '/nice_url');

window.onpopstate = function (e) {
    if (typeof e.state == "object" && e.state.foo == "bar") {
        alert("Blah blah blah");
    }
};

window.history.go(-1);

and search location.hash;

Is it possible to have multiple styles inside a TextView?

I was running into the same problem. I could use fromHtml, but I am android now, not web, so I decided to try this out. I do have to localize this though so I gave it a shot using string replacement concept. I set the style on the TextView to be the main style, then just format the other peices.

I hope this helps others looking to do the same thing - I don't know why this isn't easier in the framework.

My strings look like this:


<string name="my_text">{0} You will need a {1} to complete this assembly</string>
<string name="text_sub0">1:</string>
<string name="text_sub1">screwdriver, hammer, and measuring tape</string>

Here are the styles:


<style name="MainStyle">
    <item name="android:textSize">@dimen/regular_text</item>
    <item name="android:textColor">@color/regular_text</item>
</style>
<style name="style0">
    <item name="android:textSize">@dimen/paragraph_bullet</item>
    <item name="android:textColor">@color/standout_text</item>
    <item name="android:textStyle">bold</item>
</style>
<style name="style1">
    <item name="android:textColor">@color/standout_light_text</item>
    <item name="android:textStyle">italic</item>
</style>

Here is my code that calls my formatStyles method:


SpannableString formattedSpan = formatStyles(getString(R.string.my_text), getString(R.string.text_sub0), R.style.style0, getString(R.string.main_text_sub1), R.style.style1);
textView.setText(formattedSpan, TextView.BufferType.SPANNABLE);

The format method:


private SpannableString formatStyles(String value, String sub0, int style0, String sub1, int style1)
{
    String tag0 = "{0}";
    int startLocation0 = value.indexOf(tag0);
    value = value.replace(tag0, sub0);

    String tag1 = "{1}";
    int startLocation1 = value.indexOf(tag1);
    if (sub1 != null && !sub1.equals(""))
    {
        value = value.replace(tag1, sub1);
    }

    SpannableString styledText = new SpannableString(value);
    styledText.setSpan(new TextAppearanceSpan(getActivity(), style0), startLocation0, startLocation0 + sub0.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    if (sub1 != null && !sub1.equals(""))
    {
        styledText.setSpan(new TextAppearanceSpan(getActivity(), style1), startLocation1, startLocation1 + sub1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    return styledText;
}

How to 'update' or 'overwrite' a python list

I'm learning to code and I found this same problem. I believe the easier way to solve this is literaly overwriting the list like @kerby82 said:

An item in a list in Python can be set to a value using the form

x[n] = v

Where x is the name of the list, n is the index in the array and v is the value you want to set.

In your exemple:

aList = [123, 'xyz', 'zara', 'abc']
aList[0] = 2014
print aList
>>[2014, 'xyz', 'zara', 'abc']

Concatenate two char* strings in a C program

Here is a working solution:

#include <stdio.h>
#include <string.h>

int main(int argc, char** argv) 
{
      char str1[16];
      char str2[16];
      strcpy(str1, "sssss");
      strcpy(str2, "kkkk");
      strcat(str1, str2);
      printf("%s", str1);
      return 0;
}

Output:

ssssskkkk

You have to allocate memory for your strings. In the above code, I declare str1 and str2 as character arrays containing 16 characters. I used strcpy to copy characters of string literals into them, and strcat to append the characters of str2 to the end of str1. Here is how these character arrays look like during the execution of the program:

After declaration (both are empty): 
str1: [][][][][][][][][][][][][][][][][][][][] 
str2: [][][][][][][][][][][][][][][][][][][][]

After calling strcpy (\0 is the string terminator zero byte): 
str1: [s][s][s][s][s][\0][][][][][][][][][][][][][][] 
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]

After calling strcat: 
str1: [s][s][s][s][s][k][k][k][k][\0][][][][][][][][][][] 
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]

libxml/tree.h no such file or directory

I had this problem when I reopened a project (which was developed on XCode 3.something on Leopard) after upgrading to Snow Leopard and XCode 3.2. Curious enough, it only affected some kinds of builds (emulator builds went fine, device ones gave me the error). And I have libxml2 at /usr/include, and it indeed contains libxml/tree.h.

Even the magic "Clean" did not work, but "Empty Caches..." under the "XCode" menu (between the Apple logo and File) did the trick (was that menu there in previous versions?). Beats me the reason, but after a clean there were no more complaints regarding libxml/tree.h

How to get duration, as int milli's and float seconds from <chrono>?

Is this what you're looking for?

#include <chrono>
#include <iostream>

int main()
{
    typedef std::chrono::high_resolution_clock Time;
    typedef std::chrono::milliseconds ms;
    typedef std::chrono::duration<float> fsec;
    auto t0 = Time::now();
    auto t1 = Time::now();
    fsec fs = t1 - t0;
    ms d = std::chrono::duration_cast<ms>(fs);
    std::cout << fs.count() << "s\n";
    std::cout << d.count() << "ms\n";
}

which for me prints out:

6.5e-08s
0ms

TypeError: method() takes 1 positional argument but 2 were given

Something else to consider when this type of error is encountered:

I was running into this error message and found this post helpful. Turns out in my case I had overridden an __init__() where there was object inheritance.

The inherited example is rather long, so I'll skip to a more simple example that doesn't use inheritance:

class MyBadInitClass:
    def ___init__(self, name):
        self.name = name

    def name_foo(self, arg):
        print(self)
        print(arg)
        print("My name is", self.name)


class MyNewClass:
    def new_foo(self, arg):
        print(self)
        print(arg)


my_new_object = MyNewClass()
my_new_object.new_foo("NewFoo")
my_bad_init_object = MyBadInitClass(name="Test Name")
my_bad_init_object.name_foo("name foo")

Result is:

<__main__.MyNewClass object at 0x033C48D0>
NewFoo
Traceback (most recent call last):
  File "C:/Users/Orange/PycharmProjects/Chapter9/bad_init_example.py", line 41, in <module>
    my_bad_init_object = MyBadInitClass(name="Test Name")
TypeError: object() takes no parameters

PyCharm didn't catch this typo. Nor did Notepad++ (other editors/IDE's might).

Granted, this is a "takes no parameters" TypeError, it isn't much different than "got two" when expecting one, in terms of object initialization in Python.

Addressing the topic: An overloading initializer will be used if syntactically correct, but if not it will be ignored and the built-in used instead. The object won't expect/handle this and the error is thrown.

In the case of the sytax error: The fix is simple, just edit the custom init statement:

def __init__(self, name):
    self.name = name

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

its occurred if you build your apk from some other PC and update it from different PC.

What's the best practice for putting multiple projects in a git repository?

While most people will tell you to just use multiple repositories, I feel it's worth mentioning there are other solutions.

Solution 1

A single repository can contain multiple independent branches, called orphan branches. Orphan branches are completely separate from each other; they do not share histories.

git checkout --orphan BRANCHNAME

This creates a new branch, unrelated to your current branch. Each project should be in its own orphaned branch.

Now for whatever reason, git needs a bit of cleanup after an orphan checkout.

rm .git/index
rm -r *

Make sure everything is committed before deleting

Once the orphan branch is clean, you can use it normally.

Solution 2

Avoid all the hassle of orphan branches. Create two independent repositories, and push them to the same remote. Just use different branch names for each repo.

# repo 1
git push origin master:master-1

# repo 2
git push origin master:master-2

How do you install GLUT and OpenGL in Visual Studio 2012?

OpenGL is bundled with Visual Studio. You just need to install GLUT package (freeglut would be fine), which can be found in NuGet.

Open your solution, click TOOLS->NuGet Package Manager->Package Manager Console to open a NuGet console, type Install-Package freeglut.

--

For VS 2013, use nupengl.core package instead.

--

It's 2020 now. Use VCPKG.

How do I make a file:// hyperlink that works in both IE and Firefox?

In case someone else finds this topic while using localhost in the file URIs - Internet Explorer acts completely different if the host name is localhost or 127.0.0.1 - if you use the actual hostname, it works fine (from trusted sites/intranet zone).

Another big difference between IE and FF - IE is fine with uris like file://server/share/file.txt but FF requires additional slashes file:////server/share/file.txt.

How to convert JSON object to JavaScript array?

As simple as this !

var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [json_data];
console.log(result);

GroupBy pandas DataFrame and select most common value

A slightly clumsier but faster approach for larger datasets involves getting the counts for a column of interest, sorting the counts highest to lowest, and then de-duplicating on a subset to only retain the largest cases. The code example is following:

>>> import pandas as pd
>>> source = pd.DataFrame(
        {
            'Country': ['USA', 'USA', 'Russia', 'USA'], 
            'City': ['New-York', 'New-York', 'Sankt-Petersburg', 'New-York'],
            'Short name': ['NY', 'New', 'Spb', 'NY']
        }
    )
>>> grouped_df = source\
        .groupby(['Country','City','Short name'])[['Short name']]\
        .count()\
        .rename(columns={'Short name':'count'})\
        .reset_index()\
        .sort_values('count', ascending=False)\
        .drop_duplicates(subset=['Country', 'City'])\
        .drop('count', axis=1)
>>> print(grouped_df)
  Country              City Short name
1     USA          New-York         NY
0  Russia  Sankt-Petersburg        Spb

How to allow http content within an iframe on a https site

Using Google as the SSL proxy is not working currently,

Why?

If you opened any page from google, you will find there is a x-frame-options field in the header. Google response header

The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame>, <iframe> or <object>. Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites.

(Quote from MDN)

One of the solution

Below is my work around for this problem:

Upload the content to AWS S3, and it will create a https link for the resource.
Notice: set the permission to the html file for allowing everyone view it.

After that, we can using it as the src of iframe in the https websites. AWS

How to declare and initialize a static const array as a class member?

// in foo.h
class Foo {
    static const unsigned char* Msg;
};

// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;

Warning: mysqli_query() expects parameter 1 to be mysqli, resource given

You are mixing mysqli and mysql extensions, which will not work.

You need to use

$myConnection= mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql"); 

mysqli_select_db($myConnection, "mrmagicadam") or die ("no database");   

mysqli has many improvements over the original mysql extension, so it is recommended that you use mysqli.

SQL : BETWEEN vs <= and >=

See this excellent blog post from Aaron Bertrand about why you should change your string format and how the boundary values are handled in date range queries.

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

I am amazed to see so many string replace ideas of UUID. How about this:

UUID temp = UUID.randomUUID();
String uuidString = Long.toHexString(temp.getMostSignificantBits())
     + Long.toHexString(temp.getLeastSignificantBits());

This is the fasted way of doing it since the whole toString() of UUID is already more expensive not to mention the regular expression which has to be parsed and executed or the replacing with empty string.

How is attr_accessible used in Rails 4?

We can use

params.require(:person).permit(:name, :age)

where person is Model, you can pass this code on a method person_params & use in place of params[:person] in create method or else method

Getting a "This application is modifying the autolayout engine from a background thread" error?

You already have the correct code answer from @Mark but, just to share my findings: The issue is that you are requesting a change in the view and assuming that it will happen instantly. In reality, the loading of a view depends on the available resources. If everything loads quickly enough and there are no delays then you don't notice anything. In scenarios, where there is any delay due to the process thread being busy etc, the application runs into a situation where it is supposed to display something even though its not ready yet. Hence, it is advisable to dispatch these requests in a asynchronous queues so, they get executed based on the load.

Can I install the "app store" in an IOS simulator?

You can install other builds but not Appstore build.

From Xcode 8.2,drag and drop the build to simulator for the installation.

https://stackoverflow.com/a/41671233/1522584

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

@opsb's answers is neat, but the center point is not accurate, moreover, as @Jithin noted, if the angle is 360, then nothing is drawn at all.

@Jithin fixed the 360 issue, but if you selected less than 360 degree, then you'll get a line closing the arc loop, which is not required.

I fixed that, and added some animation in the code below:

_x000D_
_x000D_
function myArc(cx, cy, radius, max){       _x000D_
       var circle = document.getElementById("arc");_x000D_
        var e = circle.getAttribute("d");_x000D_
        var d = " M "+ (cx + radius) + " " + cy;_x000D_
        var angle=0;_x000D_
        window.timer = window.setInterval(_x000D_
        function() {_x000D_
            var radians= angle * (Math.PI / 180);  // convert degree to radians_x000D_
            var x = cx + Math.cos(radians) * radius;  _x000D_
            var y = cy + Math.sin(radians) * radius;_x000D_
           _x000D_
            d += " L "+x + " " + y;_x000D_
            circle.setAttribute("d", d)_x000D_
            if(angle==max)window.clearInterval(window.timer);_x000D_
            angle++;_x000D_
        }_x000D_
      ,5)_x000D_
 }     _x000D_
_x000D_
  myArc(110, 110, 100, 360);_x000D_
    
_x000D_
<svg xmlns="http://www.w3.org/2000/svg" style="width:220; height:220;"> _x000D_
    <path d="" id="arc" fill="none" stroke="red" stroke-width="2" />_x000D_
</svg>
_x000D_
_x000D_
_x000D_

SQL Server Configuration Manager not found

Go to this location C:\Windows\System32 and find SQLServerManager . Worked for me. Configuration manager was there but somehow wasn't showing up in search results.

Access to the requested object is only available from the local network phpmyadmin

I newer version of xampp you may use another method first open your httpd-xampp.conf file and find the string "phpmyadmin" using ctrl+F command (Windows). and then replace this code

Alias /phpmyadmin "D:/server/phpMyAdmin/"
<Directory "D:/server/phpMyAdmin">
    AllowOverride AuthConfig
    Require local
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

with this

Alias /phpmyadmin "D:/server/phpMyAdmin/"
<Directory "D:/server/phpMyAdmin">
    AllowOverride AuthConfig
    Require all granted
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

Don't Forget to Restart your Xampp.

AngularJS format JSON string output

If you are looking to render JSON as HTML and it can be collapsed/opened, you can use this directive that I just made to render it nicely:

https://github.com/mohsen1/json-formatter/

enter image description here

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

sending tag <img src="c:\images\mypic.jpg"> would cause user browser to access image from his filesystem. if you have to store images in folder located in c:\images i would suggest to create an servlet like images.jsp, that as a parameter takes name of a file, then sets servlet response content to an image/jpg and then loads bytes of image from server location and put it to a response.

But what you use to create your application? is it pure servlet? Spring? JSF?

Here you can find some info about, how to do it.

Simple JavaScript login form validation

Here is some useful links with example Login form Validation in javascript

function validate() {
        var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;
        if (username == null || username == "") {
            alert("Please enter the username.");
            return false;
        }
        if (password == null || password == "") {
            alert("Please enter the password.");
            return false;
        }
        alert('Login successful');

    } 

  <input type="text" name="username" id="username" />
  <input type="password" name="password" id="password" />
  <input type="button" value="Login" id="submit" onclick="validate();" />

Is it possible to write to the console in colour in .NET?

Above comments are both solid responses, however note that they aren't thread safe. If you are writing to the console with multiple threads, changing colors will add a race condition that can create some strange looking output. It is simple to fix though:

public class ConsoleWriter
{
    private static object _MessageLock= new object();

    public void WriteMessage(string message)
    {
        lock (_MessageLock)
        {
            Console.BackgroundColor = ConsoleColor.Red;
            Console.WriteLine(message);
            Console.ResetColor();
        }
    }
}

Copy folder structure (without files) from one location to another

Substitute target_dir and source_dir with the appropriate values:

cd target_dir && (cd source_dir; find . -type d ! -name .) | xargs -i mkdir -p "{}"

Tested on OSX+Ubuntu.

How to install VS2015 Community Edition offline

Even if you download the ISO files there will be lots of stuff not included in the installer which requires connection to internet when installing, for example:

  • Emulators for Windows Mobile
  • Windows 10 SDK
  • Tools for Windows 10 Universal Apps
  • GitHub Extension for Visual Studio and Git CLI
  • C#/.NET Xamarin
  • Visual C++ Mobile Development (iOS support)
  • Joyent Node.js
  • Java SE Development Kit
  • Android SDK, NDK, and emulator

Perhaps some of them are not possible to include but it is annoying nonetheless.

Java AES encryption and decryption

Here is the implementation that was mentioned above:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;

try
{
    String passEncrypt = "my password";
    byte[] saltEncrypt = "choose a better salt".getBytes();
    int iterationsEncrypt = 10000;
    SecretKeyFactory factoryKeyEncrypt = SecretKeyFactory
            .getInstance("PBKDF2WithHmacSHA1");
    SecretKey tmp = factoryKeyEncrypt.generateSecret(new PBEKeySpec(
            passEncrypt.toCharArray(), saltEncrypt, iterationsEncrypt,
            128));
    SecretKeySpec encryptKey = new SecretKeySpec(tmp.getEncoded(),
            "AES");

    Cipher aesCipherEncrypt = Cipher
            .getInstance("AES/ECB/PKCS5Padding");
    aesCipherEncrypt.init(Cipher.ENCRYPT_MODE, encryptKey);

    // get the bytes
    byte[] bytes = StringUtils.getBytesUtf8(toEncodeEncryptString);

    // encrypt the bytes
    byte[] encryptBytes = aesCipherEncrypt.doFinal(bytes);

    // encode 64 the encrypted bytes
    String encoded = Base64.encodeBase64URLSafeString(encryptBytes);

    System.out.println("e: " + encoded);

    // assume some transport happens here

    // create a new string, to make sure we are not pointing to the same
    // string as the one above
    String encodedEncrypted = new String(encoded);

    //we recreate the same salt/encrypt as if its a separate system
    String passDecrypt = "my password";
    byte[] saltDecrypt = "choose a better salt".getBytes();
    int iterationsDecrypt = 10000;
    SecretKeyFactory factoryKeyDecrypt = SecretKeyFactory
            .getInstance("PBKDF2WithHmacSHA1");
    SecretKey tmp2 = factoryKeyDecrypt.generateSecret(new PBEKeySpec(passDecrypt
            .toCharArray(), saltDecrypt, iterationsDecrypt, 128));
    SecretKeySpec decryptKey = new SecretKeySpec(tmp2.getEncoded(), "AES");

    Cipher aesCipherDecrypt = Cipher.getInstance("AES/ECB/PKCS5Padding");
            aesCipherDecrypt.init(Cipher.DECRYPT_MODE, decryptKey);

    //basically we reverse the process we did earlier

    // get the bytes from encodedEncrypted string
    byte[] e64bytes = StringUtils.getBytesUtf8(encodedEncrypted);

    // decode 64, now the bytes should be encrypted
    byte[] eBytes = Base64.decodeBase64(e64bytes);

    // decrypt the bytes
    byte[] cipherDecode = aesCipherDecrypt.doFinal(eBytes);

    // to string
    String decoded = StringUtils.newStringUtf8(cipherDecode);

    System.out.println("d: " + decoded);

}
catch (Exception e)
{
    e.printStackTrace();
}

How to set an environment variable only for the duration of the script?

Just put

export HOME=/blah/whatever

at the point in the script where you want the change to happen. Since each process has its own set of environment variables, this definition will automatically cease to have any significance when the script terminates (and with it the instance of bash that has a changed environment).

MySQL, Check if a column exists in a table with SQL

I am using this simple script:

mysql_query("select $column from $table") or mysql_query("alter table $table add $column varchar (20)");

It works if you are already connected to the database.

How can I specify a [DllImport] path at runtime?

If all fails, simply put the DLL in the windows\system32 folder . The compiler will find it. Specify the DLL to load from with: DllImport("user32.dll"..., set EntryPoint = "my_unmanaged_function" to import your desired unmanaged function to your C# app:

 using System;
using System.Runtime.InteropServices;

class Example
{
   // Use DllImport to import the Win32 MessageBox function.

   [DllImport ("user32.dll", CharSet = CharSet.Auto)]
   public static extern int MessageBox 
      (IntPtr hWnd, String text, String caption, uint type);

   static void Main()
   {
      // Call the MessageBox function using platform invoke.
      MessageBox (new IntPtr(0), "Hello, World!", "Hello Dialog", 0);    
   }
}

Source and even more DllImport examples : http://msdn.microsoft.com/en-us/library/aa288468(v=vs.71).aspx

Send data from javascript to a mysql database

The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.

So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net

If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.

http://api.jquery.com/jQuery.ajax/

Play a Sound with Python

After the play() command add a delay of say 10 secs or so, it'll work

import pygame

import time

pygame.init()

pygame.mixer.music.load("test.wav")

pygame.mixer.music.play()

time.sleep(10)

This also plays .mp3 files.

Most efficient way to remove special characters from string

I suggest creating a simple lookup table, which you can initialize in the static constructor to set any combination of characters to valid. This lets you do a quick, single check.

edit

Also, for speed, you'll want to initialize the capacity of your StringBuilder to the length of your input string. This will avoid reallocations. These two methods together will give you both speed and flexibility.

another edit

I think the compiler might optimize it out, but as a matter of style as well as efficiency, I recommend foreach instead of for.

Python: Pandas Dataframe how to multiply entire column with a scalar

Note: for those using pandas 0.20.3 and above, and are looking for an answer, all these options will work:

df = pd.DataFrame(np.ones((5,6)),columns=['one','two','three',
                                       'four','five','six'])
df.one *=5
df.two = df.two*5
df.three = df.three.multiply(5)
df['four'] = df['four']*5
df.loc[:, 'five'] *=5
df.iloc[:, 5] = df.iloc[:, 5]*5

which results in

   one  two  three  four  five  six
0  5.0  5.0    5.0   5.0   5.0  5.0
1  5.0  5.0    5.0   5.0   5.0  5.0
2  5.0  5.0    5.0   5.0   5.0  5.0
3  5.0  5.0    5.0   5.0   5.0  5.0
4  5.0  5.0    5.0   5.0   5.0  5.0

String escape into XML

EDIT: You say "I am concatenating simple and short XML file and I do not use serialization, so I need to explicitly escape XML character by hand".

I would strongly advise you not to do it by hand. Use the XML APIs to do it all for you - read in the original files, merge the two into a single document however you need to (you probably want to use XmlDocument.ImportNode), and then write it out again. You don't want to write your own XML parsers/formatters. Serialization is somewhat irrelevant here.

If you can give us a short but complete example of exactly what you're trying to do, we can probably help you to avoid having to worry about escaping in the first place.


Original answer

It's not entirely clear what you mean, but normally XML APIs do this for you. You set the text in a node, and it will automatically escape anything it needs to. For example:

LINQ to XML example:

using System;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        XElement element = new XElement("tag",
                                        "Brackets & stuff <>");

        Console.WriteLine(element);
    }
}

DOM example:

using System;
using System.Xml;

class Test
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        XmlElement element = doc.CreateElement("tag");
        element.InnerText = "Brackets & stuff <>";
        Console.WriteLine(element.OuterXml);
    }
}

Output from both examples:

<tag>Brackets &amp; stuff &lt;&gt;</tag>

That's assuming you want XML escaping, of course. If you're not, please post more details.

How to make a UILabel clickable?

You need to enable the user interaction of that label.....

For e.g

yourLabel.userInteractionEnabled = true

how to make a specific text on TextView BOLD

If you are using Kotlin, it becomes even easier to do by using core-ktx, as it provides a domain-specific-language (DSL) for doing this:

val string: SpannedString = buildSpannedString {
    bold {
        append("foo")
    }
    append("bar")     
}

More options provided by it are:

append("Hello There")
bold {
    append("bold")
    italic {
        append("bold and italic")
        underline {
            append("then some text with underline")
        }
    }
}

At last, you can just to:

textView.text = string

How to check if a character in a string is a digit or letter

You need to convert your string into character..

String character = in.next();
char myChar = character.charAt(0);

if (Character.isDigit(myChar)) {
   // print true
}

Check Character for other methods..

How can you debug a CORS request with cURL?

Updated answer that covers most cases

curl -H "Access-Control-Request-Method: GET" -H "Origin: http://localhost" --head http://www.example.com/
  1. Replace http://www.example.com/ with URL you want to test.
  2. If response includes Access-Control-Allow-* then your resource supports CORS.

Rationale for alternative answer

I google this question every now and then and the accepted answer is never what I need. First it prints response body which is a lot of text. Adding --head outputs only headers. Second when testing S3 URLs we need to provide additional header -H "Access-Control-Request-Method: GET".

Hope this will save time.

Function for Factorial in Python

If you are using Python2.5 or older try

from operator import mul
def factorial(n):
    return reduce(mul, range(1,n+1))

for newer Python, there is factorial in the math module as given in other answers here

How do I obtain a Query Execution Plan in SQL Server?

In addition to the comprehensive answer already posted sometimes it is useful to be able to access the execution plan programatically to extract information. Example code for this is below.

DECLARE @TraceID INT
EXEC StartCapture @@SPID, @TraceID OUTPUT
EXEC sp_help 'sys.objects' /*<-- Call your stored proc of interest here.*/
EXEC StopCapture @TraceID

Example StartCapture Definition

CREATE PROCEDURE StartCapture
@Spid INT,
@TraceID INT OUTPUT
AS
DECLARE @maxfilesize BIGINT = 5
DECLARE @filepath NVARCHAR(200) = N'C:\trace_' + LEFT(NEWID(),36)

EXEC sp_trace_create @TraceID OUTPUT, 0, @filepath, @maxfilesize, NULL 

exec sp_trace_setevent @TraceID, 122, 1, 1
exec sp_trace_setevent @TraceID, 122, 22, 1
exec sp_trace_setevent @TraceID, 122, 34, 1
exec sp_trace_setevent @TraceID, 122, 51, 1
exec sp_trace_setevent @TraceID, 122, 12, 1
-- filter for spid
EXEC sp_trace_setfilter @TraceID, 12, 0, 0, @Spid
-- start the trace
EXEC sp_trace_setstatus @TraceID, 1

Example StopCapture Definition

CREATE  PROCEDURE StopCapture
@TraceID INT
AS
WITH  XMLNAMESPACES ('http://schemas.microsoft.com/sqlserver/2004/07/showplan' as sql), 
      CTE
     as (SELECT CAST(TextData AS VARCHAR(MAX)) AS TextData,
                ObjectID,
                ObjectName,
                EventSequence,
                /*costs accumulate up the tree so the MAX should be the root*/
                MAX(EstimatedTotalSubtreeCost) AS EstimatedTotalSubtreeCost
         FROM   fn_trace_getinfo(@TraceID) fn
                CROSS APPLY fn_trace_gettable(CAST(value AS NVARCHAR(200)), 1)
                CROSS APPLY (SELECT CAST(TextData AS XML) AS xPlan) x
                CROSS APPLY (SELECT T.relop.value('@EstimatedTotalSubtreeCost',
                                            'float') AS EstimatedTotalSubtreeCost
                             FROM   xPlan.nodes('//sql:RelOp') T(relop)) ca
         WHERE  property = 2
                AND TextData IS NOT NULL
                AND ObjectName not in ( 'StopCapture', 'fn_trace_getinfo' )
         GROUP  BY CAST(TextData AS VARCHAR(MAX)),
                   ObjectID,
                   ObjectName,
                   EventSequence)
SELECT ObjectName,
       SUM(EstimatedTotalSubtreeCost) AS EstimatedTotalSubtreeCost
FROM   CTE
GROUP  BY ObjectID,
          ObjectName  

-- Stop the trace
EXEC sp_trace_setstatus @TraceID, 0
-- Close and delete the trace
EXEC sp_trace_setstatus @TraceID, 2
GO

How to connect to MySQL Database?

Looking at the code below, I tried it and found: Instead of writing DBCon = DBConnection.Instance(); you should put DBConnection DBCon - new DBConnection(); (That worked for me)

and instead of MySqlComman cmd = new MySqlComman(query, DBCon.GetConnection()); you should put MySqlCommand cmd = new MySqlCommand(query, DBCon.GetConnection()); (it's missing the d)

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

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

Finding out the name of the original repository you cloned from in Git

This is quick Bash command, that you're probably searching for, will print only a basename of the remote repository:

Where you fetch from:

basename $(git remote show -n origin | grep Fetch | cut -d: -f2-)

Alternatively where you push to:

basename $(git remote show -n origin | grep Push | cut -d: -f2-)

Especially the -n option makes the command much quicker.

Transpose a data frame

You can use the transpose function from the data.table library. Simple and fast solution that keeps numeric values as numeric.

library(data.table)

# get data
  data("mtcars")

# transpose
  t_mtcars <- transpose(mtcars)

# get row and colnames in order
  colnames(t_mtcars) <- rownames(mtcars)
  rownames(t_mtcars) <- colnames(mtcars)

Sort an array of objects in React and render them

Try lodash sortBy

import * as _ from "lodash";
_.sortBy(data.applications,"id").map(application => (
    console.log("application")
    )
)

Read more : lodash.sortBy

Python Pandas Counting the Occurrences of a Specific value

An elegant way to count the occurrence of '?' or any symbol in any column, is to use built-in function isin of a dataframe object.

Suppose that we have loaded the 'Automobile' dataset into df object. We do not know which columns contain missing value ('?' symbol), so let do:

df.isin(['?']).sum(axis=0)

DataFrame.isin(values) official document says:

it returns boolean DataFrame showing whether each element in the DataFrame is contained in values

Note that isin accepts an iterable as input, thus we need to pass a list containing the target symbol to this function. df.isin(['?']) will return a boolean dataframe as follows.

    symboling   normalized-losses   make    fuel-type   aspiration-ratio ...
0   False       True                False   False       False
1   False       True                False   False       False
2   False       True                False   False       False
3   False       False               False   False       False
4   False       False               False   False       False
5   False       True                False   False       False
...

To count the number of occurrence of the target symbol in each column, let's take sum over all the rows of the above dataframe by indicating axis=0. The final (truncated) result shows what we expect:

symboling             0
normalized-losses    41
...
bore                  4
stroke                4
compression-ratio     0
horsepower            2
peak-rpm              2
city-mpg              0
highway-mpg           0
price                 4

Reading CSV file and storing values into an array

Just came across this library: https://github.com/JoshClose/CsvHelper

Very intuitive and easy to use. Has a nuget package too which made is quick to implement: http://nuget.org/packages/CsvHelper/1.17.0. Also appears to be actively maintained which I like.

Configuring it to use a semi-colon is easy: https://github.com/JoshClose/CsvHelper/wiki/Custom-Configurations

YouTube iframe embed - full screen

React.JS People, remember allowFullScreen and frameBorder="0"

Without camel-case, react strips these tags out!

val() vs. text() for textarea

The best way to set/get the value of a textarea is the .val(), .value method.

.text() internally uses the .textContent (or .innerText for IE) method to get the contents of a <textarea>. The following test cases illustrate how text() and .val() relate to each other:

var t = '<textarea>';
console.log($(t).text('test').val());             // Prints test
console.log($(t).val('too').text('test').val());  // Prints too
console.log($(t).val('too').text());              // Prints nothing
console.log($(t).text('test').val('too').val());  // Prints too

console.log($(t).text('test').val('too').text()); // Prints test

The value property, used by .val() always shows the current visible value, whereas text()'s return value can be wrong.

Python 3 Online Interpreter / Shell

I recently came across Python 3 interpreter at CompileOnline.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

When you get a UnicodeEncodeError, it means that somewhere in your code you convert directly a byte string to a unicode one. By default in Python 2 it uses ascii encoding, and utf8 encoding in Python3 (both may fail because not every byte is valid in either encoding)

To avoid that, you must use explicit decoding.

If you may have 2 different encoding in your input file, one of them accepts any byte (say UTF8 and Latin1), you can try to first convert a string with first and use the second one if a UnicodeDecodeError occurs.

def robust_decode(bs):
    '''Takes a byte string as param and convert it into a unicode one.
First tries UTF8, and fallback to Latin1 if it fails'''
    cr = None
    try:
        cr = bs.decode('utf8')
    except UnicodeDecodeError:
        cr = bs.decode('latin1')
    return cr

If you do not know original encoding and do not care for non ascii character, you can set the optional errors parameter of the decode method to replace. Any offending byte will be replaced (from the standard library documentation):

Replace with a suitable replacement character; Python will use the official U+FFFD REPLACEMENT CHARACTER for the built-in Unicode codecs on decoding and ‘?’ on encoding.

bs.decode(errors='replace')

Create a asmx web service in C# using visual studio 2013

  1. Create Empty ASP.NET Project enter image description here
  2. Add Web Service(asmx) to your project
    enter image description here

How to make spring inject value into a static field

As these answers are old, I found this alternative. It is very clean and works with just java annotations:

To fix it, create a “none static setter” to assign the injected value for the static variable. For example :

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class GlobalValue {

public static String DATABASE;

@Value("${mongodb.db}")
public void setDatabase(String db) {
    DATABASE = db;
}
}

https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/

Using print statements only to debug

The logging module has everything you could want. It may seem excessive at first, but only use the parts you need. I'd recommend using logging.basicConfig to toggle the logging level to stderr and the simple log methods, debug, info, warning, error and critical.

import logging, sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
logging.debug('A debug message!')
logging.info('We processed %d records', len(processed_records))

Using headers with the Python requests library's get method

Seems pretty straightforward, according to the docs on the page you linked (emphasis mine).

requests.get(url, params=None, headers=None, cookies=None, auth=None, timeout=None)

Sends a GET request. Returns Response object.

Parameters:

  • url – URL for the new Request object.
  • params – (optional) Dictionary of GET Parameters to send with the Request.
  • headers – (optional) Dictionary of HTTP Headers to send with the Request.
  • cookies – (optional) CookieJar object to send with the Request.
  • auth – (optional) AuthObject to enable Basic HTTP Auth.
  • timeout – (optional) Float describing the timeout of the request.

Change language of Visual Studio 2017 RC

I solved this just created label on desktop with option/parameter --locale en-US

"C:\Program Files (x86)\Microsoft Visual Studio\Installer\vs_installer.exe" --locale en-US

Explode PHP string by new line

Cover all cases. Don't rely that your input is coming from a Windows environment.

$skuList = preg_split("/\\r\\n|\\r|\\n/", $_POST['skuList']);

or

$skuList = preg_split('/\r\n|\r|\n/', $_POST['skuList']);

How to merge remote changes at GitHub?

If you "git pull" and it says "Already up-to-date.", and still get this error, it might be because one of your other branches isn't up to date. Try switching to another branch and making sure that one is also up-to-date before trying to "git push" again:

Switch to branch "foo" and update it:

$ git checkout foo
$ git pull

You can see the branches you've got by issuing command:

$ git branch

What are XAND and XOR

Guys, don´t scare the crap out of others (hey! just kidding), but it´s really all a question of equivalences and synonyms:

firstly:

"XAND" doesn´t exist logically, neither does "XNAND", however "XAND" is normally thought-up by a studious but confused initiating logic student.(wow!). It com from the thought that, if there´s a XOR(exclusive OR) it´s logical to exist a "XAND"("exclusive" AND). The rational suggestion would be an "IAND"("inclusive" AND), which isn´t used or recognised as well. So:

 XNOR <=> !XOR <=> EQV

And all this just discribes a unique operator, called the equivalency operator(<=>, EQV) so:

A  |  B  | A <=> B | A XAND B | A XNOR B | A !XOR B | ((NOT(A) AND B)AND(A AND NOT(B)))
---------------------------------------------------------------------------------------
T  |  T  |    T    |     T    |     T    |     T    |                T    
T  |  F  |    F    |     F    |     F    |     F    |                F    
F  |  T  |    F    |     F    |     F    |     F    |                F    
F  |  F  |    T    |     T    |     T    |     T    |                T    

And just a closing comment: The 'X' prefix is only possible if and only if the base operator isn´t unary. So, XNOR <=> NOT XOR <=/=> X NOR.

Peace.

How do I pass the this context to a function?

Javascripts .call() and .apply() methods allow you to set the context for a function.

var myfunc = function(){
    alert(this.name);
};

var obj_a = {
    name:  "FOO"
};

var obj_b = {
    name:  "BAR!!"
};

Now you can call:

myfunc.call(obj_a);

Which would alert FOO. The other way around, passing obj_b would alert BAR!!. The difference between .call() and .apply() is that .call() takes a comma separated list if you're passing arguments to your function and .apply() needs an array.

myfunc.call(obj_a, 1, 2, 3);
myfunc.apply(obj_a, [1, 2, 3]);

Therefore, you can easily write a function hook by using the apply() method. For instance, we want to add a feature to jQuerys .css() method. We can store the original function reference, overwrite the function with custom code and call the stored function.

var _css = $.fn.css;
$.fn.css = function(){
   alert('hooked!');
   _css.apply(this, arguments);
};

Since the magic arguments object is an array like object, we can just pass it to apply(). That way we guarantee, that all parameters are passed through to the original function.

Can Mockito stub a method without regard to the argument?

Another option is to rely on good old fashion equals method. As long as the argument in the when mock equals the argument in the code being tested, then Mockito will match the mock.

Here is an example.

public class MyPojo {

    public MyPojo( String someField ) {
        this.someField = someField;
    }

    private String someField;

    @Override
    public boolean equals( Object o ) {
        if ( this == o ) return true;
        if ( o == null || getClass() != o.getClass() ) return false;
        MyPojo myPojo = ( MyPojo ) o;
        return someField.equals( myPojo.someField );
    }

}

then, assuming you know what the value for someField will be, you can mock it like this.

when(fooDao.getBar(new MyPojo(expectedSomeField))).thenReturn(myFoo);

pros: This is more explicit then any matchers. As a reviewer of code, I keep an eye open for any in the code junior developers write, as it glances over their code's logic to generate the appropriate object being passed.

con: Sometimes the field being passed to the object is a random ID. For this case you cannot easily construct the expected argument object in your mock code.

Another possible approach is to use Mockito's Answer object that can be used with the when method. Answer lets you intercept the actual call and inspect the input argument and return a mock object. In the example below I am using any to catch any request to the method being mocked. But then in the Answer lambda, I can further inspect the Bazo argument... maybe to verify that a proper ID was passed to it. I prefer this over any by itself so that at least some inspection is done on the argument.

    Bar mockBar = //generate mock Bar.

    when(fooDao.getBar(any(Bazo.class))
    .thenAnswer(  ( InvocationOnMock invocationOnMock) -> {
        Bazo actualBazo = invocationOnMock.getArgument( 0 );

        //inspect the actualBazo here and thrw exception if it does not meet your testing requirements.
        return mockBar;
    } );

So to sum it all up, I like relying on equals (where the expected argument and actual argument should be equal to each other) and if equals is not possible (due to not being able to predict the actual argument's state), I'll resort to Answer to inspect the argument.

I get Access Forbidden (Error 403) when setting up new alias

I'm using XAMPP with Apache2.4, I had this same issue. I wanted to leave the default xampp/htdocs folder in place, be able to access it from locahost and have a Virtual Host to point to my dev area...

The full contents of my C:\xampp\apache\conf\extra\http-vhosts.conf file is below...

# Virtual Hosts
#
# Required modules: mod_log_config

# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at 
# <URL:http://httpd.apache.org/docs/2.4/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.

#
# Use name-based virtual hosting.
#

##NameVirtualHost *:80

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ##ServerName or ##ServerAlias in any <VirtualHost> block.
#
##<VirtualHost *:80>
    ##ServerAdmin [email protected]
    ##DocumentRoot "C:/xampp/htdocs/dummy-host.example.com"
    ##ServerName dummy-host.example.com
    ##ServerAlias www.dummy-host.example.com
    ##ErrorLog "logs/dummy-host.example.com-error.log"
    ##CustomLog "logs/dummy-host.example.com-access.log" common
##</VirtualHost>

##<VirtualHost *:80>
    ##ServerAdmin [email protected]
    ##DocumentRoot "C:/xampp/htdocs/dummy-host2.example.com"
    ##ServerName dummy-host2.example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
##</VirtualHost>


<VirtualHost *:80>
    DocumentRoot "C:\xampp\htdocs"
    ServerName localhost
</VirtualHost>


<VirtualHost *:80>
    DocumentRoot "C:\nick\static"
    ServerName dev.middleweek.co.uk
    <Directory "C:\nick\static">
        Allow from all
        Require all granted
    </Directory>
</VirtualHost>

I then updated my C:\windows\System32\drivers\etc\hosts file like this...

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost

127.0.0.1   dev.middleweek.co.uk
127.0.0.1       localhost

Restart your machine for good measure, open the XAMPP Control Panel and start Apache.

Now open your custom domain in your browser, in the above example, it'll be http://dev.middleweek.co.uk

Hope that helps someone!

And if you want to be able to view directory listings under your new Virtual host, then edit your VirtualHost block in C:\xampp\apache\conf\extra\http-vhosts.conf to include "Options Indexes" like this...

<VirtualHost *:80>
    DocumentRoot "C:\nick\static"
    ServerName dev.middleweek.co.uk
    <Directory "C:\nick\static">
        Allow from all
        Require all granted
        Options Indexes
    </Directory>
</VirtualHost>

Cheers, Nick

Mean per group in a data.frame

I describe two ways to do this, one based on data.table and the other based on reshape2 package . The data.table way already has an answer, but I have tried to make it cleaner and more detailed.

The data is like this:

 d <- structure(list(Name = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 
3L, 3L), .Label = c("Aira", "Ben", "Cat"), class = "factor"), 
    Month = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), Rate1 = c(12L, 
    18L, 19L, 53L, 22L, 19L, 22L, 67L, 45L), Rate2 = c(23L, 73L, 
    45L, 19L, 87L, 45L, 87L, 43L, 32L)), .Names = c("Name", "Month", 
"Rate1", "Rate2"), class = "data.frame", row.names = c(NA, -9L
))
head(d)
  Name Month Rate1 Rate2
1 Aira     1    12    23
2 Aira     2    18    73
3 Aira     3    19    45
4  Ben     1    53    19
5  Ben     2    22    87
6  Ben     3    19    45


library("reshape2")
mym <- melt(d, id = c("Name"))
res <- dcast(mym, Name ~ variable, mean)
res
#Name Month    Rate1    Rate2
#1 Aira     2 16.33333 47.00000
#2  Ben     2 31.33333 50.33333
#3  Cat     2 44.66667 54.00000

Using data.table:

# At first, I convert the data.frame to data.table and then I group it 
setDT(d)
d[, .(Rate1 = mean(Rate1), Rate2 = mean(Rate2)), by = .(Name)]
#   Name    Rate1    Rate2
#1: Aira 16.33333 47.00000
#2:  Ben 31.33333 50.33333
#3:  Cat 44.66667 54.00000

There is another way of doing it by avoiding to write many argument for j in data.table using a .SD

d[, lapply(.SD, mean), by = .(Name)]
#   Name Month    Rate1    Rate2
#1: Aira     2 16.33333 47.00000
#2:  Ben     2 31.33333 50.33333
#3:  Cat     2 44.66667 54.00000

if we only want to have Rate1 and Rate2 then we can use the .SDcols as follows:

d[, lapply(.SD, mean), by = .(Name), .SDcols = 3:4]
#  Name    Rate1    Rate2
#1: Aira 16.33333 47.00000
#2:  Ben 31.33333 50.33333
#3:  Cat 44.66667 54.00000

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

time = Time.now.to_s

time = DateTime.parse(time).strftime("%d/%m/%Y %H:%M")

for increment decrement month use << >> operators

examples

datetime_month_before = DateTime.parse(time) << 1



datetime_month_before = DateTime.now << 1

Why is 1/1/1970 the "epoch time"?

History.

The earliest versions of Unix time had a 32-bit integer incrementing at a rate of 60 Hz, which was the rate of the system clock on the hardware of the early Unix systems. The value 60 Hz still appears in some software interfaces as a result. The epoch also differed from the current value. The first edition Unix Programmer's Manual dated November 3, 1971 defines the Unix time as "the time since 00:00:00, Jan. 1, 1971, measured in sixtieths of a second".

jQuery How do you get an image to fade in on load?

OK so I did this and it works. It's basically hacked together from different responses here. Since there is STILL not a clear answer in this thread I decided to post this.

<script type="text/javascript">
  $(document).ready(function () {
    $("#logo").hide();
    $("#logo").bind("load", function () { $(this).fadeIn(); });
  });
</script>

This seems to me to be the best way to go about it. Despite Sohnee's best intentions he failed to mention that the object must first be set to display:none with CSS. The problem here is that if for what ever reason the user's JS is not working the object will just never appear. Not good, especially if it's the frikin' logo.

This solution leaves the item alone in the CSS, and first hides, then fades it in all using JS. This way if JS is not working properly the item will just load as normal.

Hope that helps anyone else who stumbles into this google ranked #1 not-so-helpful thread.

How do I solve this "Cannot read property 'appendChild' of null" error?

Your condition id !== 0 will always be different that zero because you are assigning a string value. On pages where the element with id views_slideshow_controls_text_next_slideshow-block is not found, you will still try to append the img element, which causes the Cannot read property 'appendChild' of null error.

Instead of assigning a string value, you can assign the DOM element and verify if it exists within the page.

window.onload = function loadContIcons() {
    var elem = document.createElement("img");
    elem.src = "http://arno.agnian.com/sites/all/themes/agnian/images/up.png";
    elem.setAttribute("class", "up_icon");

    var container = document.getElementById("views_slideshow_controls_text_next_slideshow-block");
    if (container !== null) {
        container.appendChild(elem);
    } else console.log("aaaaa");

    var elem1 = document.createElement("img");
    elem1.src = "http://arno.agnian.com/sites/all/themes/agnian/images/down.png";
    elem1.setAttribute("class", "down_icon");

    container = document.getElementById("views_slideshow_controls_text_previous_slideshow-block");
    if (container !== null) {
        container.appendChild(elem1);
    } else console.log("aaaaa");
}

Keeping it simple and how to do multiple CTE in a query

You can have multiple CTEs in one query, as well as reuse a CTE:

WITH    cte1 AS
        (
        SELECT  1 AS id
        ),
        cte2 AS
        (
        SELECT  2 AS id
        )
SELECT  *
FROM    cte1
UNION ALL
SELECT  *
FROM    cte2
UNION ALL
SELECT  *
FROM    cte1

Note, however, that SQL Server may reevaluate the CTE each time it is accessed, so if you are using values like RAND(), NEWID() etc., they may change between the CTE calls.

How to trim a file extension from a String in JavaScript?

I like this one because it is a one liner which isn't too hard to read:

filename.substring(0, filename.lastIndexOf('.')) || filename

Extract regression coefficient values

A summary.lm object stores these values in a matrix called 'coefficients'. So the value you are after can be accessed with:

a2Pval <- summary(mg)$coefficients[2, 4]

Or, more generally/readably, coef(summary(mg))["a2","Pr(>|t|)"]. See here for why this method is preferred.

Pointers in JavaScript?

Since JavaScript does not support passing parameters by reference, you'll need to make the variable an object instead:

_x000D_
_x000D_
var x = {Value: 0};_x000D_
_x000D_
function a(obj)_x000D_
{_x000D_
    obj.Value++;_x000D_
}_x000D_
_x000D_
a(x);_x000D_
document.write(x.Value); //Here i want to have 1 instead of 0
_x000D_
_x000D_
_x000D_

In this case, x is a reference to an object. When x is passed to the function a, that reference is copied over to obj. Thus, obj and x refer to the same thing in memory. Changing the Value property of obj affects the Value property of x.

Javascript will always pass function parameters by value. That's simply a specification of the language. You could create x in a scope local to both functions, and not pass the variable at all.

Is it possible to use the instanceof operator in a switch statement?

You can't. The switch statement can only contain case statements which are compile time constants and which evaluate to an integer (Up to Java 6 and a string in Java 7).

What you are looking for is called "pattern matching" in functional programming.

See also Avoiding instanceof in Java

Java Singleton and Synchronization

Enum singleton

The simplest way to implement a Singleton that is thread-safe is using an Enum

public enum SingletonEnum {
  INSTANCE;
  public void doSomething(){
    System.out.println("This is a singleton");
  }
}

This code works since the introduction of Enum in Java 1.5

Double checked locking

If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.

public class Singleton {

  private static volatile Singleton instance = null;

  private Singleton() {
  }

  public static Singleton getInstance() {
    if (instance == null) {
      synchronized (Singleton.class){
        if (instance == null) {
          instance = new Singleton();
        }
      }
    }
    return instance ;
  }
}

This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.

Early loading Singleton (works even before Java 1.5)

This implementation instantiates the singleton when the class is loaded and provides thread safety.

public class Singleton {

  private static final Singleton instance = new Singleton();

  private Singleton() {
  }

  public static Singleton getInstance() {
    return instance;
  }

  public void doSomething(){
    System.out.println("This is a singleton");
  }

}

Git On Custom SSH Port

(Update: a few years later Google and Qwant "airlines" still send me here when searching for "git non-default ssh port") A probably better way in newer git versions is to use the GIT_SSH_COMMAND ENV.VAR like:

GIT_SSH_COMMAND="ssh -oPort=1234 -i ~/.ssh/myPrivate_rsa.key" \ git clone myuser@myGitRemoteServer:/my/remote/git_repo/path

This has the added advantage of allowing any other ssh suitable option (port, priv.key, IPv6, PKCS#11 device, ...).

Exception is never thrown in body of corresponding try statement

As pointed out in the comments, you cannot catch an exception that's not thrown by the code within your try block. Try changing your code to:

try{
    Integer.parseInt(args[i-1]); // this only throws a NumberFormatException
}
catch(NumberFormatException e){
    throw new MojException("Bledne dane");
}

Always check the documentation to see what exceptions are thrown by each method. You may also wish to read up on the subject of checked vs unchecked exceptions before that causes you any confusion in the future.

Best timestamp format for CSV/Excel?

I would guess that ISO-format is a good idea. (Wikipedia article, also with time info)

Java reflection: how to get field value from an object, not knowing its class

I strongly recommend using Java generics to specify what type of object is in that List, ie. List<Car>. If you have Cars and Trucks you can use a common superclass/interface like this List<Vehicle>.

However, you can use Spring's ReflectionUtils to make fields accessible, even if they are private like the below runnable example:

List<Object> list = new ArrayList<Object>();

list.add("some value");
list.add(3);

for(Object obj : list)
{
    Class<?> clazz = obj.getClass();

    Field field = org.springframework.util.ReflectionUtils.findField(clazz, "value");
    org.springframework.util.ReflectionUtils.makeAccessible(field);

    System.out.println("value=" + field.get(obj));
}

Running this has an output of:

value=[C@1b67f74
value=3

Where/How to getIntent().getExtras() in an Android Fragment?

What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent in an Activity and then pass any extra data to fragments by instantiating them with arguments.

There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity and Fragment from the support library.

You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:

public static class DetailsActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // (omitted some other stuff)

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            DetailsFragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction().add(
                    android.R.id.content, details).commit();
        }
    }
}

In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance in the examples given by Google. There actually is a newInstance method in DetailsFragment, so I'm unsure why it isn't used in the snippet above...

Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments(). Since this returns a Bundle, its usage is similar to that of the extras in an Activity.

public static class DetailsFragment extends Fragment {
    /**
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
     */
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    // (other stuff omitted)

}

Use Awk to extract substring

I am asking in general, how to write a compatible awk script that performs the same functionality ...

To solve the problem in your quesiton is easy. (check others' answer).

If you want to write an awk script, which portable to any awk implementations and versions (gawk/nawk/mawk...) it is really hard, even if with --posix (gawk)

for example:

  • some awk works on string in terms of characters, some with bytes
  • some supports \x escape, some not
  • FS interpreter works differently
  • keywords/reserved words abbreviation restriction
  • some operator restriction e.g. **
  • even same awk impl. (gawk for example), the version 4.0 and 3.x have difference too.
  • the implementation of certain functions are also different. (your problem is one example, see below)

well all the points above are just spoken in general. Back to your problem, you problem is only related to fundamental feature of awk. awk '{print $x}' the line like that will work all awks.

There are two reasons why your awk line behaves differently on gawk and mawk:

  • your used substr() function wrongly. this is the main cause. you have substr($0, 0, RSTART - 1) the 0 should be 1, no matter which awk do you use. awk array, string idx etc are 1-based.

  • gawk and mawk implemented substr() differently.

RegExp in TypeScript

You can do just:

var regex = /^[1-9]\d{0,2}$/g
regex.test('2') // outputs true

Finding the layers and layer sizes for each Docker image

Not exactly the original question but to find the sum total of all the images without double-counting shared layers, the following is useful (ubuntu 18):

sudo du -h -d1  /var/lib/docker/overlay2 | sort -h

Determine whether a key is present in a dictionary

if 'name' in mydict:

is the preferred, pythonic version. Use of has_key() is discouraged, and this method has been removed in Python 3.

Extract a single (unsigned) integer from a string

preg_replace('/[^0-9]/', '', $string);

This should do better job!...

Angular 2 - Redirect to an external URL and open in a new tab

onNavigate(){
    window.open("https://www.google.com", "_blank");
}

Removing highcharts.com credits link

Both of the following code will work fine for removing highchart.com from the chart:-

credits: false

or

credits:{
 enabled:false,
}

Modular multiplicative inverse function in Python

Here is a one-liner for CodeFights; it is one of the shortest solutions:

MMI = lambda A, n,s=1,t=0,N=0: (n < 2 and t%N or MMI(n, A%n, t, s-A//n*t, N or n),-1)[n<1]

It will return -1 if A has no multiplicative inverse in n.

Usage:

MMI(23, 99) # returns 56
MMI(18, 24) # return -1

The solution uses the Extended Euclidean Algorithm.

Collection that allows only unique items in .NET?

If all you need is to ensure uniqueness of elements, then HashSet is what you need.

What do you mean when you say "just a set implementation"? A set is (by definition) a collection of unique elements that doesn't save element order.

Convert a string representation of a hex dump to a byte array using Java?

If you have a preference for Java 8 streams as your coding style then this can be achieved using just JDK primitives.

String hex = "0001027f80fdfeff";

byte[] converted = IntStream.range(0, hex.length() / 2)
    .map(i -> Character.digit(hex.charAt(i * 2), 16) << 4 | Character.digit(hex.charAt((i * 2) + 1), 16))
    .collect(ByteArrayOutputStream::new,
             ByteArrayOutputStream::write,
             (s1, s2) -> s1.write(s2.toByteArray(), 0, s2.size()))
    .toByteArray();

The , 0, s2.size() parameters in the collector concatenate function can be omitted if you don't mind catching IOException.

Hide all elements with class using plain Javascript

I would propose a different approach. Instead of changing the properties of all objects manually, let's add a new CSS to the document:

/* License: CC0 */
var newStylesheet = document.createElement('style');
newStylesheet.textContent = '.classname { display: none; }';
document.head.appendChild(newStylesheet);

Spark dataframe: collect () vs select ()

Short answer in bolds:

  • collect is mainly to serialize
    (loss of parallelism preserving all other data characteristics of the dataframe)
    For example with a PrintWriter pw you can't do direct df.foreach( r => pw.write(r) ), must to use collect before foreach, df.collect.foreach(etc).
    PS: the "loss of parallelism" is not a "total loss" because after serialization it can be distributed again to executors.

  • select is mainly to select columns, similar to projection in relational algebra
    (only similar in framework's context because Spark select not deduplicate data).
    So, it is also a complement of filter in the framework's context.


Commenting explanations of other answers: I like the Jeff's classification of Spark operations in transformations (as select) and actions (as collect). It is also good remember that transforms (including select) are lazily evaluated.

Java: Getting a substring from a string starting after a particular character

java android

in my case

I want to change from

~/propic/........png

anything after /propic/ doesn't matter what before it

........png

finally, I found the code in Class StringUtils

this is the code

     public static String substringAfter(final String str, final String separator) {
         if (isEmpty(str)) {
             return str;
         }
         if (separator == null) {
             return "";
         }
         final int pos = str.indexOf(separator);
         if (pos == 0) {
             return str;
         }
         return str.substring(pos + separator.length());
     }

shell-script headers (#!/bin/sh vs #!/bin/csh)

This is known as a Shebang:

http://en.wikipedia.org/wiki/Shebang_(Unix)

#!interpreter [optional-arg]

A shebang is only relevant when a script has the execute permission (e.g. chmod u+x script.sh).

When a shell executes the script it will use the specified interpreter.

Example:

#!/bin/bash
# file: foo.sh
echo 1

$ chmod u+x foo.sh
$ ./foo.sh
  1

Android studio takes too much memory

Open below mention path on your system and delete all your avd's (Virtual devices: Emulator)

C:\Users{Username}.android\avd

Note: - Deleting Emulator only from android studio will not delete all the spaces grab by their avd's. So delete all avd's from above given path and then create new emulator, if you needed.

How to sort an array of associative arrays by value of a given key in PHP?

Complete Dynamic Function I jumped here for associative array sorting and found this amazing function on http://php.net/manual/en/function.sort.php. This function is very dynamic that sort in ascending and descending order with specified key.

Simple function to sort an array by a specific key. Maintains index association

<?php

function array_sort($array, $on, $order=SORT_ASC)
{
    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
            break;
            case SORT_DESC:
                arsort($sortable_array);
            break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}

$people = array(
    12345 => array(
        'id' => 12345,
        'first_name' => 'Joe',
        'surname' => 'Bloggs',
        'age' => 23,
        'sex' => 'm'
    ),
    12346 => array(
        'id' => 12346,
        'first_name' => 'Adam',
        'surname' => 'Smith',
        'age' => 18,
        'sex' => 'm'
    ),
    12347 => array(
        'id' => 12347,
        'first_name' => 'Amy',
        'surname' => 'Jones',
        'age' => 21,
        'sex' => 'f'
    )
);

print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname

Is it valid to define functions in JSON results?

The problem is that JSON as a data definition language evolved out of JSON as a JavaScript Object Notation. Since Javascript supports eval on JSON, it is legitimate to put JSON code inside JSON (in that use-case). If you're using JSON to pass data remotely, then I would say it is bad practice to put methods in the JSON because you may not have modeled your client-server interaction well. And, further, when wishing to use JSON as a data description language I would say you could get yourself into trouble by embedding methods because some JSON parsers were written with only data description in mind and may not support method definitions in the structure.

Wikipedia JSON entry makes a good case for not including methods in JSON, citing security concerns:

Unless you absolutely trust the source of the text, and you have a need to parse and accept text that is not strictly JSON compliant, you should avoid eval() and use JSON.parse() or another JSON specific parser instead. A JSON parser will recognize only JSON text and will reject other text, which could contain malevolent JavaScript. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.

Table cell widths - fixing width, wrapping/truncating long words

Stack Overflow has solved a similar problem with long lines of code by using a DIV and having overflow-x:auto. CSS can't break up words for you.

Form Google Maps URL that searches for a specific places near specific coordinates

What do you want to search near that known place?

For example if you want to search a restaurant near a known place you can use the parameters "q=" and "near=" and construct this URL: maps.google.com/?q=restaurant&near=47.154719,27.60551

For a list of complete parameters you can see this: https://web.archive.org/web/20070708030513/http://mapki.com/wiki/Google_Map_Parameters

Depending on what is the format you want your information in you can add at the end of the url the parameter output like this: maps.google.com/?q=restaurant&near=47.154719,27.60551&output=kml

For more types of output format you can read chapter 2 of this: http://csie-tw.blogspot.de/2009/06/android-driving-direction-route-path.html

How can I divide two integers stored in variables in Python?

x / y

quotient of x and y

x // y 

(floored) quotient of x and y

Unix ls command: show full path when using options

simply use find tool.

find absolute_path

displays full paths on my Linux machine, while

find relative_path

will not.

How do I install opencv using pip?

run the following command by creating a virtual enviroment using python 3 and run

pip3 install opencv-python

to check it has installed correctly run

python3 -c "import cv2"

Eclipse shows errors but I can't find them

This happens from time to time in Eclipse. In the "Project" menu there's a "Clean" option, that usually takes care of the problem.

What is the difference between UTF-8 and Unicode?

Unicode only define code points, that is, a number which represents a character. How you store these code points in memory depends of the encoding that you are using. UTF-8 is one way of encoding Unicode characters, among many others.

How can I search Git branches for a file or directory?

You could use gitk --all and search for commits "touching paths" and the pathname you are interested in.

HtmlSpecialChars equivalent in Javascript?

Chances are you don't need such a function. Since your code is already in the browser*, you can access the DOM directly instead of generating and encoding HTML that will have to be decoded backwards by the browser to be actually used.

Use innerText property to insert plain text into the DOM safely and much faster than using any of the presented escape functions. Even faster than assigning a static preencoded string to innerHTML.

Use classList to edit classes, dataset to set data- attributes and setAttribute for others.

All of these will handle escaping for you. More precisely, no escaping is needed and no encoding will be performed underneath**, since you are working around HTML, the textual representation of DOM.

_x000D_
_x000D_
// use existing element_x000D_
var author = 'John "Superman" Doe <[email protected]>';_x000D_
var el = document.getElementById('first');_x000D_
el.dataset.author = author;_x000D_
el.textContent = 'Author: '+author;_x000D_
_x000D_
// or create a new element_x000D_
var a = document.createElement('a');_x000D_
a.classList.add('important');_x000D_
a.href = '/search?q=term+"exact"&n=50';_x000D_
a.textContent = 'Search for "exact" term';_x000D_
document.body.appendChild(a);_x000D_
_x000D_
// actual HTML code_x000D_
console.log(el.outerHTML);_x000D_
console.log(a.outerHTML);
_x000D_
.important { color: red; }
_x000D_
<div id="first"></div>
_x000D_
_x000D_
_x000D_

* This answer is not intended for server-side JavaScript users (Node.js, etc.)

** Unless you explicitly convert it to actual HTML afterwards. E.g. by accessing innerHTML - this is what happens when you run $('<div/>').text(value).html(); suggested in other answers. So if your final goal is to insert some data into the document, by doing it this way you'll be doing the work twice. Also you can see that in the resulting HTML not everything is encoded, only the minimum that is needed for it to be valid. It is done context-dependently, that's why this jQuery method doesn't encode quotes and therefore should not be used as a general purpose escaper. Quotes escaping is needed when you're constructing HTML as a string with untrusted or quote-containing data at the place of an attribute's value. If you use the DOM API, you don't have to care about escaping at all.

Create an Oracle function that returns a table

I think you want a pipelined table function.

Something like this:

CREATE OR REPLACE PACKAGE test AS

    TYPE measure_record IS RECORD(
       l4_id VARCHAR2(50), 
       l6_id VARCHAR2(50), 
       l8_id VARCHAR2(50), 
       year NUMBER, 
       period NUMBER,
       VALUE NUMBER);

    TYPE measure_table IS TABLE OF measure_record;

    FUNCTION get_ups(foo NUMBER)
        RETURN measure_table
        PIPELINED;
END;

CREATE OR REPLACE PACKAGE BODY test AS

    FUNCTION get_ups(foo number)
        RETURN measure_table
        PIPELINED IS

        rec            measure_record;

    BEGIN
        SELECT 'foo', 'bar', 'baz', 2010, 5, 13
          INTO rec
          FROM DUAL;

        -- you would usually have a cursor and a loop here   
        PIPE ROW (rec);

        RETURN;
    END get_ups;
END;

For simplicity I removed your parameters and didn't implement a loop in the function, but you can see the principle.

Usage:

SELECT *
  FROM table(test.get_ups(0));



L4_ID L6_ID L8_ID       YEAR     PERIOD      VALUE
----- ----- ----- ---------- ---------- ----------
foo   bar   baz         2010          5         13
1 row selected.

Sniffing/logging your own Android Bluetooth traffic

Also, this might help finding the actual location the btsnoop_hci.log is being saved:

adb shell "cat /etc/bluetooth/bt_stack.conf | grep FileName"

System.IO.IOException: file used by another process

Are you running a real-time antivirus scanner by any chance ? If so, you could try (temporarily) disabling it to see if that is what is accessing the file you are trying to delete. (Chris' suggestion to use Sysinternals process explorer is a good one).

Convert a JSON Object to Buffer and Buffer to JSON Object back

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

And for converting string to json obj :

var temp = JSON.parse(buf.toString());

Assign multiple values to array in C

typedef struct{
  char array[4];
}my_array;

my_array array = { .array = {1,1,1,1} }; // initialisation

void assign(my_array a)
{
  array.array[0] = a.array[0];
  array.array[1] = a.array[1];
  array.array[2] = a.array[2];
  array.array[3] = a.array[3]; 
}

char num = 5;
char ber = 6;

int main(void)
{
  printf("%d\n", array.array[0]);
// ...

  // this works even after initialisation
  assign((my_array){ .array = {num,ber,num,ber} });

  printf("%d\n", array.array[0]);
// ....
  return 0;
}

Remove border from IFrame

Add the frameBorder attribute (note the capital ‘B’).

So it would look like:

<iframe src="myURL" width="300" height="300" frameBorder="0">Browser not compatible.</iframe>

Excel formula to remove space between words in a cell

Steps (1) Just Select your range, rows or column or array , (2) Press ctrl+H , (3 a) then in the find type a space (3 b) in the replace do not enter anything, (4)then just click on replace all..... you are done.

Stash just a single file

The best option is to stage everything but this file, and tell stash to keep the index with git stash save --keep-index, thus stashing your unstaged file:

$ git add .
$ git reset thefiletostash
$ git stash save --keep-index

As Dan points out, thefiletostash is the only one to be reset by the stash, but it also stashes the other files, so it's not exactly what you want.

/bin/sh: apt-get: not found

If you are looking inside dockerfile while creating image, add this line:

RUN apk add --update yourPackageName

c++ array assignment of multiple values

You have to replace the values one by one such as in a for-loop or copying another array over another such as using memcpy(..) or std::copy

e.g.

for (int i = 0; i < arrayLength; i++) {
    array[i] = newValue[i];
}

Take care to ensure proper bounds-checking and any other checking that needs to occur to prevent an out of bounds problem.

Search for all occurrences of a string in a mysql database

A simple solution would be doing something like this:

mysqldump -u myuser --no-create-info --extended-insert=FALSE databasename | grep -i "<search string>"

Entity Framework - Include Multiple Levels of Properties

I'm going to add my solution to my particular problem. I had two collections at the same level I needed to include. The final solution looked like this.

var recipe = _bartendoContext.Recipes
    .Include(r => r.Ingredients)
    .ThenInclude(r => r.Ingredient)
    .Include(r => r.Ingredients)
    .ThenInclude(r => r.MeasurementQuantity)
    .FirstOrDefault(r => r.Id == recipeId);
if (recipe?.Ingredients == null) return 0m;
var abv = recipe.Ingredients.Sum(ingredient => ingredient.Ingredient.AlcoholByVolume * ingredient.MeasurementQuantity.Quantity);
return abv;

This is calculating the percent alcohol by volume of a given drink recipe. As you can see I just included the ingredients collection twice then included the ingredient and quantity onto that.