Programs & Examples On #Recursive regex

Using a regular expression to parse an expression which contains the same expression e.g. `{ foo bar {zoo} }`

How to do a SOAP Web Service call from Java class?

Or just use Apache CXF's wsdl2java to generate objects you can use.

It is included in the binary package you can download from their website. You can simply run a command like this:

$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl

It uses the wsdl to generate objects, which you can use like this (object names are also grabbed from the wsdl, so yours will be different a little):

DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
System.out.println(res);

There is even a Maven plug-in which generates the sources: https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html

Note: If you generate sources using CXF and IDEA, you might want to look at this: https://stackoverflow.com/a/46812593/840315

Retrieving Property name from lambda expression

now in C# 6 you can simply use nameof like this nameof(User.UserId)

which has many benefits, among them is that this is done at compile time, not runtime.

https://msdn.microsoft.com/en-us/magazine/dn802602.aspx

Find rows that have the same value on a column in MySQL

Here is query to find email's which are used for more then one login_id:

SELECT email
FROM table
GROUP BY email
HAVING count(*) > 1

You'll need second (of nested) query to get list of login_id by email.

How to read a line from a text file in c/c++?

In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed of getting all lines.

If there's a chance you may have really really long lines and you have to process line by line, you could malloc a resonable buffer, and use realloc to double it's size each time you get close to filling it.

#include <stdio.h>
#include <stdlib.h>

void handle_line(char *line) {
  printf("%s", line);
}

int main(int argc, char *argv[]) {
    int size = 1024, pos;
    int c;
    char *buffer = (char *)malloc(size);

    FILE *f = fopen("myfile.txt", "r");
    if(f) {
      do { // read all lines in file
        pos = 0;
        do{ // read one line
          c = fgetc(f);
          if(c != EOF) buffer[pos++] = (char)c;
          if(pos >= size - 1) { // increase buffer length - leave room for 0
            size *=2;
            buffer = (char*)realloc(buffer, size);
          }
        }while(c != EOF && c != '\n');
        buffer[pos] = 0;
        // line is now in buffer
        handle_line(buffer);
      } while(c != EOF); 
      fclose(f);           
    }
    free(buffer);
    return 0;
}

How to return values in javascript

Its very simple. Call one function inside another function with parameters.

    function fun1()
    {
     var a=10;
     var b=20;
     fun2(a,b); //calling function fun2() and passing 2 parameters
    }

   function fun2(num1,num2)
   {
    var sum;
    sum = num1+num2;
    return sum;
   }

   fun1(); //trigger function fun1

Can a foreign key refer to a primary key in the same table?

A good example of using ids of other rows in the same table as foreign keys is nested lists.

Deleting a row that has children (i.e., rows, which refer to parent's id), which also have children (i.e., referencing ids of children) will delete a cascade of rows.

This will save a lot of pain (and a lot of code of what to do with orphans - i.e., rows, that refer to non-existing ids).

Ways to implement data versioning in MongoDB

The first big question when diving in to this is "how do you want to store changesets"?

  1. Diffs?
  2. Whole record copies?

My personal approach would be to store diffs. Because the display of these diffs is really a special action, I would put the diffs in a different "history" collection.

I would use the different collection to save memory space. You generally don't want a full history for a simple query. So by keeping the history out of the object you can also keep it out of the commonly accessed memory when that data is queried.

To make my life easy, I would make a history document contain a dictionary of time-stamped diffs. Something like this:

{
    _id : "id of address book record",
    changes : { 
                1234567 : { "city" : "Omaha", "state" : "Nebraska" },
                1234568 : { "city" : "Kansas City", "state" : "Missouri" }
               }
}

To make my life really easy, I would make this part of my DataObjects (EntityWrapper, whatever) that I use to access my data. Generally these objects have some form of history, so that you can easily override the save() method to make this change at the same time.

UPDATE: 2015-10

It looks like there is now a spec for handling JSON diffs. This seems like a more robust way to store the diffs / changes.

Actual meaning of 'shell=True' in subprocess

Executing programs through the shell means that all user input passed to the program is interpreted according to the syntax and semantic rules of the invoked shell. At best, this only causes inconvenience to the user, because the user has to obey these rules. For instance, paths containing special shell characters like quotation marks or blanks must be escaped. At worst, it causes security leaks, because the user can execute arbitrary programs.

shell=True is sometimes convenient to make use of specific shell features like word splitting or parameter expansion. However, if such a feature is required, make use of other modules are given to you (e.g. os.path.expandvars() for parameter expansion or shlex for word splitting). This means more work, but avoids other problems.

In short: Avoid shell=True by all means.

Can I make a function available in every controller in angular?

Though the first approach is advocated as 'the angular like' approach, I feel this adds overheads.

Consider if I want to use this myservice.foo function in 10 different controllers. I will have to specify this 'myService' dependency and then $scope.callFoo scope property in all ten of them. This is simply a repetition and somehow violates the DRY principle.

Whereas, if I use the $rootScope approach, I specify this global function gobalFoo only once and it will be available in all my future controllers, no matter how many.

Adding a column to an existing table in a Rails migration

You can also force to table columns in table using force: true, if you table is already exist.

example:

ActiveRecord::Schema.define(version: 20080906171750) do
  create_table "authors", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
end

Java Array, Finding Duplicates

public static ArrayList<Integer> duplicate(final int[] zipcodelist) {

    HashSet<Integer> hs = new HashSet<>();
    ArrayList<Integer> al = new ArrayList<>();
    for(int element: zipcodelist) {
        if(hs.add(element)==false) {
            al.add(element);
        }   
    }
    return al;
}

angular.min.js.map not found, what is it exactly?

As eaon21 and monkey said, source map files basically turn minified code into its unminified version for debugging.

You can find the .map files here. Just add them into the same directory as the minified js files and it'll stop complaining. The reason they get fetched is the

/*
//@ sourceMappingURL=angular.min.js.map
*/

at the end of angular.min.js. If you don't want to add the .map files you can remove those lines and it'll stop the fetch attempt, but if you plan on debugging it's always good to keep the source maps linked.

Why is quicksort better than mergesort?

One of the reason is more philosophical. Quicksort is Top->Down philosophy. With n elements to sort, there are n! possibilities. With 2 partitions of m & n-m which are mutually exclusive, the number of possibilities go down in several orders of magnitude. m! * (n-m)! is smaller by several orders than n! alone. imagine 5! vs 3! *2!. 5! has 10 times more possibilities than 2 partitions of 2 & 3 each . and extrapolate to 1 million factorial vs 900K!*100K! vs. So instead of worrying about establishing any order within a range or a partition,just establish order at a broader level in partitions and reduce the possibilities within a partition. Any order established earlier within a range will be disturbed later if the partitions themselves are not mutually exclusive.

Any bottom up order approach like merge sort or heap sort is like a workers or employee's approach where one starts comparing at a microscopic level early. But this order is bound to be lost as soon as an element in between them is found later on. These approaches are very stable & extremely predictable but do a certain amount of extra work.

Quick Sort is like Managerial approach where one is not initially concerned about any order , only about meeting a broad criterion with No regard for order. Then the partitions are narrowed until you get a sorted set. The real challenge in Quicksort is in finding a partition or criterion in the dark when you know nothing about the elements to sort. That is why we either need to spend some effort to find a median value or pick 1 at random or some arbitrary "Managerial" approach . To find a perfect median can take significant amount of effort and leads to a stupid bottom up approach again. So Quicksort says just a pick a random pivot and hope that it will be somewhere in the middle or do some work to find median of 3 , 5 or something more to find a better median but do not plan to be perfect & don't waste any time in initially ordering. That seems to do well if you are lucky or sometimes degrades to n^2 when you don't get a median but just take a chance. Any way data is random. right. So I agree more with the top ->down logical approach of quicksort & it turns out that the chance it takes about pivot selection & comparisons that it saves earlier seems to work better more times than any meticulous & thorough stable bottom ->up approach like merge sort. But

C# Checking if button was clicked

button1, button2 and button3 have same even handler

private void button1_Click(Object sender, EventArgs e)
    {
        Button btnSender = (Button)sender;
        if (btnSender == button1 || btnSender == button2)
        {
            //some code here
        }
        else if (btnSender == button3)
            //some code here
    }

javascript variable reference/alias

in 2019 I need to write minified jquery plugins so I need it too this alias and so testing these examples and others ,from other sources,I found a way without copy in the memory of whe entire object ,but creating only a reference. I tested this already with firefox and watching task manager's tab memory on firefox before. The code is:

var {p: d} ={p: document};
console.log(d.body);

Function to calculate distance between two coordinates

I have written the function to find distance between two coordinates. It will return distance in meter.

 function findDistance() {
   var R = 6371e3; // R is earth’s radius
   var lat1 = 23.18489670753479; // starting point lat
   var lat2 = 32.726601;         // ending point lat
   var lon1 = 72.62524545192719; // starting point lon
   var lon2 = 74.857025;         // ending point lon
   var lat1radians = toRadians(lat1);
   var lat2radians = toRadians(lat2);

   var latRadians = toRadians(lat2-lat1);
   var lonRadians = toRadians(lon2-lon1);

   var a = Math.sin(latRadians/2) * Math.sin(latRadians/2) +
        Math.cos(lat1radians) * Math.cos(lat2radians) *
        Math.sin(lonRadians/2) * Math.sin(lonRadians/2);
   var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

   var d = R * c;

   console.log(d)
}

function toRadians(val){
    var PI = 3.1415926535;
    return val / 180.0 * PI;
}

What is the worst programming language you ever worked with?

Well since this question refuses to die and since the OP did prod me into answering...

I humbly proffer for your consideration Authorware (AW) as the worst language it is possible to create. (n.b. I'm going off recollection here, it's been ~6 years since I used AW, which of course means there's a number of awful things I can't even remember)

the horror, the horror http://img.brothersoft.com/screenshots/softimage/a/adobe_authorware-67096-1.jpeg

Let's start with the fact that it's a Macromedia product (-10 points), a proprietary language (-50 more) primarily intended for creating e-learning software and moreover software that could be created by non-programmers and programmers alike implemented as an iconic language AND a text language (-100).

Now if that last statement didn't scare you then you haven't had to fix WYSIWYG generated code before (hello Dreamweaver and Frontpage devs!), but the salient point is that AW had a library of about 12 or so elements which could be dragged into a flow. Like "Page" elements, Animations, IFELSE, and GOTO (-100). Of course removing objects from the flow created any number of broken connections and artifacts which the IDE had variable levels of success coping with. Naturally the built in wizards (-10) were a major source of these.

Fortunately you could always step into a code view, and eventually you'd have to because with a limited set of iconic elements some things just weren't possible otherwise. The language itself was based on TUTOR (-50) - a candidate for worst language itself if only it had the ambition and scope to reach the depths AW would strive for - about which wikipedia says:

...the TUTOR language was not easy to learn. In fact, it was even suggested that several years of experience with the language would be required before programmers could build programs worth keeping.

An excellent foundation then, which was built upon in the years before the rise of the internet with exactly nothing. Absolutely no form of data structure beyond an array (-100), certainly no sugar (real men don't use switch statements?) (-10), and a large splash of syntactic vinegar ("--" was the comment indicator so no decrement operator for you!) (-10). Language reference documentation was provided in paper or zip file formats (-100), but at least you had the support of the developer run usegroup and could quickly establish the solution to your problem was to use the DLL or SWF importing features of AW to enable you to do the actual coding in a real language.

AW was driven by a flow (with necessary PAUSE commands) and therefore has all the attendant problems of a linear rather than event based system (-50), and despite the outright marketing lies of the documentation it was not object oriented (-50) either. All code reuse was achieved through GOTO. No scope, lots of globals (-50).

It's not the language's fault directly, but obviously no source control integration was possible, and certainly no TDD, documentation generation or any other add-on tool you might like.

Of course Macromedia met the challenge of the internet head on with a stubborn refusal to engage for years, eventually producing the buggy, hard to use, security nightmare which is Shockwave (-100) to essentially serialise desktop versions of the software through a required plugin (-10). AS HTML rose so did AW stagnate, still persisting with it's shockwave delivery even in the face of IEEE SCORM javascript standards.

Ultimately after years of begging and promises Macromedia announced a radical new version of AW in development to address these issues, and a few years later offshored the development and then cancelled the project. Although of course Macromedia are still selling it (EVIL BONUS -500).

If anything else needs to be said, this is the language which allows spaces in variable names (-10000).

If you ever want to experience true pain, try reading somebody else's uncommented hungarian notation in a language which isn't case sensitive and allows variable name spaces.


Total Annakata Arbitrary Score (AAS): -11300
Adjusted for personal experience: OutOfRangeException

(apologies for length, but it was cathartic)

MongoDB: How to query for records where field is null or not set?

db.employe.find({ $and:[ {"dept":{ $exists:false }, "empno": { $in:[101,102] } } ] }).count();

How do I remove the horizontal scrollbar in a div?

Don't forget to write overflow-x: hidden;

The code should be:

overflow-y: scroll;
overflow-x: hidden;

How to replace � in a string

No above answer resolve my issue. When i download xml it apppends <xml to my xml. I simply

xml = parser.getXmlFromUrl(url);

xml = xml.substring(3);// it remove first three character from string,

now it is running accurately.

angular 4: *ngIf with multiple conditions

You got a ninja ')'.

Try :

<div *ngIf="currentStatus !== 'open' || currentStatus !== 'reopen'">

Sending files using POST with HttpURLConnection

I haven't tested this, but you might try using PipedInputStream and PipedOutputStream. It might look something like:

final Bitmap bmp = … // your bitmap

// Set up Piped streams
final PipedOutputStream pos = new PipedOutputStream(new ByteArrayOutputStream());
final PipedInputStream pis = new PipedInputStream(pos);

// Send bitmap data to the PipedOutputStream in a separate thread
new Thread() {
    public void run() {
        bmp.compress(Bitmap.CompressFormat.PNG, 100, pos);
    }
}.start();

// Send POST request
try {
    // Construct InputStreamEntity that feeds off of the PipedInputStream
    InputStreamEntity reqEntity = new InputStreamEntity(pis, -1);

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true);
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
    e.printStackTrace()
}

How do I specify new lines on Python, when writing on files?

The new line character is \n. It is used inside a string.

Example:

    print('First line \n Second line') 

where \n is the newline character.

This would yield the result:

First line
 Second line

If you use Python 2, you do not use the parentheses on the print function.

How to change UINavigationBar background color from the AppDelegate

For doing this in iOS 7:

[[UINavigationBar appearance] setBarTintColor:myColor];

How to automatically insert a blank row after a group of data

Select your array, including column labels, DATA > Outline -Subtotal, At each change in: column1, Use function: Count, Add subtotal to: column3, check Replace current subtotals and Summary below data, OK.

Filter and select for Column1, Text Filters, Contains..., Count, OK. Select all visible apart from the labels and delete contents. Remove filter and, if desired, ungroup rows.

Extracting Ajax return data in jQuery

You can use .filter on a jQuery object that was created from the response:

success: function(data){
    //Create jQuery object from the response HTML.
    var $response=$(data);

    //Query the jQuery object for the values
    var oneval = $response.filter('#one').text();
    var subval = $response.filter('#sub').text();
}

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

If you install Web Essentials into Visual studio you can go to Edit => Past special => paste JSON as class.

That is probably the easiest there is.

Web Essentials: http://vswebessentials.com/

How to get number of entries in a Lua table?

You could use penlight library. This has a function size which gives the actual size of the table.

It has implemented many of the function that we may need while programming and missing in Lua.

Here is the sample for using it.

> tablex = require "pl.tablex"
> a = {}
> a[2] = 2
> a[3] = 3 
> a['blah'] = 24

> #a
0

> tablex.size(a)
3

return error message with actionResult

Inside Controller Action you can access HttpContext.Response. There you can set the response status as in the following listing.

[HttpPost]
public ActionResult PostViaAjax()
{
    var body = Request.BinaryRead(Request.TotalBytes);

    var result = Content(JsonError(new Dictionary<string, string>()
    {
        {"err", "Some error!"}
    }), "application/json; charset=utf-8");
    HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    return result;
}

The preferred way of creating a new element with jQuery

I personally think that it's more important for the code to be readable and editable than performant. Whichever one you find easier to look at and it should be the one you choose for above factors. You can write it as:

$('#box').append(
  $('<div/>')
    .attr("id", "newDiv1")
    .addClass("newDiv purple bloated")
    .append("<span/>")
      .text("hello world")
);

And your first Method as:

// create an element with an object literal, defining properties
var $e = $("<div>", {id: "newDiv1", name: 'test', class: "aClass"});
$e.click(function(){ /* ... */ });
// add the element to the body
$("#box").append($e);

But as far as readability goes; the jQuery approach is my favorite. Follow this Helpful jQuery Tricks, Notes, and Best Practices

How to take off line numbers in Vi?

Easily Display Line number:

set number flag (to show line number type)

:set nu or :set number

to unset the number flag (hide the line number type)

:set nu!

If you need number every time you start vi/vim, append following line to your ~/.vimrc file:

set number

Open a file at particular location/line number

$ vi +linenumber file.rb
$ vi +300 initlib.rb 

How to download the latest artifact from Artifactory repository?

With awk:

     curl  -sS http://the_repo/com/stackoverflow/the_artifact/maven-metadata.xml | grep latest | awk -F'<latest>' '{print $2}' | awk -F'</latest>' '{print $1}'

With sed:

    curl  -sS http://the_repo/com/stackoverflow/the_artifact/maven-metadata.xml | grep latest | sed 's:<latest>::' | sed 's:</latest>::'

Free Rest API to retrieve current datetime as string (timezone irrelevant)

This API gives you the current time and several formats in JSON - https://market.mashape.com/parsify/format#time. Here's a sample response:

{
  "time": {
    "daysInMonth": 31,
    "millisecond": 283,
    "second": 42,
    "minute": 55,
    "hour": 1,
    "date": 6,
    "day": 3,
    "week": 10,
    "month": 2,
    "year": 2013,
    "zone": "+0000"
  },
  "formatted": {
    "weekday": "Wednesday",
    "month": "March",
    "ago": "a few seconds",
    "calendar": "Today at 1:55 AM",
    "generic": "2013-03-06T01:55:42+00:00",
    "time": "1:55 AM",
    "short": "03/06/2013",
    "slim": "3/6/2013",
    "hand": "Mar 6 2013",
    "handTime": "Mar 6 2013 1:55 AM",
    "longhand": "March 6 2013",
    "longhandTime": "March 6 2013 1:55 AM",
    "full": "Wednesday, March 6 2013 1:55 AM",
    "fullSlim": "Wed, Mar 6 2013 1:55 AM"
  },
  "array": [
    2013,
    2,
    6,
    1,
    55,
    42,
    283
  ],
  "offset": 1362534942283,
  "unix": 1362534942,
  "utc": "2013-03-06T01:55:42.283Z",
  "valid": true,
  "integer": false,
  "zone": 0
}

jQueryUI modal dialog does not show close button (x)

While the op does not explicitly state they are using jquery ui and bootstrap together, an identical problem happens if you do. You can resolve the problem by loading bootstrap (js) before jquery ui (js). However, that will cause problems with button state colors.

The final solution is to either use bootstrap or jquery ui, but not both. However, a workaround is:

    $('<div>dialog content</div>').dialog({
        title: 'Title',
        open: function(){
            var closeBtn = $('.ui-dialog-titlebar-close');
            closeBtn.append('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
        }
    });

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

Switch statement fallthrough in C#?

They left out this behaviour by design to avoid when it was not used by will but caused problems.

It can be used only if there is no statement in the case part, like:

switch (whatever)
{
    case 1:
    case 2:
    case 3: boo; break;
}

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

I encounted this error and found that it was because the "strict" parameter was set to true in the tsconfig.json file. Just set it "false" (obviously). In my case I had generated the tsconfig file from the cmd prompt and simply missed the "strict" parameter, which was located further down in the file.

Android: failed to convert @drawable/picture into a drawable

My Image name was 21.jpg. I renamed it as abc.jpg and it worked. So Make sure your image name not starting with a number. However all above answers are also accepted.

How do you read a file into a list in Python?

To summarize a bit from what people have been saying:

f=open('data.txt', 'w') # will make a new file or erase a file of that name if it is present
f=open('data.txt', 'r') # will open a file as read-only
f=open('data.txt', 'a') # will open a file for appending (appended data goes to the end of the file)

If you wish have something in place similar to a try/catch

with open('data.txt') as f:
    for line in f:
        print line

I think @movieyoda code is probably what you should use however

TensorFlow: "Attempting to use uninitialized value" in variable initialization

Normally there are two ways of initializing variables, 1) using the sess.run(tf.global_variables_initializer()) as the previous answers noted; 2) the load the graph from checkpoint.

You can do like this:

sess = tf.Session(config=config)
saver = tf.train.Saver(max_to_keep=3)
try:
    saver.restore(sess, tf.train.latest_checkpoint(FLAGS.model_dir))
    # start from the latest checkpoint, the sess will be initialized 
    # by the variables in the latest checkpoint
except ValueError:
    # train from scratch
    init = tf.global_variables_initializer()
    sess.run(init)

And the third method is to use the tf.train.Supervisor. The session will be

Create a session on 'master', recovering or initializing the model as needed, or wait for a session to be ready.

sv = tf.train.Supervisor([parameters])
sess = sv.prepare_or_wait_for_session()

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

YES, PUT, DELETE, HEAD etc HTTP methods are available in all modern browsers.

To be compliant with XMLHttpRequest Level 2 browsers must support these methods. To check which browsers support XMLHttpRequest Level 2 I recommend CanIUse:

http://caniuse.com/#feat=xhr2

Only Opera Mini is lacking support atm (juli '15), but Opera Mini lacks support for everything. :)

How can I have a newline in a string in sh?

On my system (Ubuntu 17.10) your example just works as desired, both when typed from the command line (into sh) and when executed as a sh script:

[bash]§ sh
$ STR="Hello\nWorld"
$ echo $STR
Hello
World
$ exit
[bash]§ echo "STR=\"Hello\nWorld\"
> echo \$STR" > test-str.sh
[bash]§ cat test-str.sh 
STR="Hello\nWorld"
echo $STR
[bash]§ sh test-str.sh 
Hello
World

I guess this answers your question: it just works. (I have not tried to figure out details such as at what moment exactly the substitution of the newline character for \n happens in sh).

However, i noticed that this same script would behave differently when executed with bash and would print out Hello\nWorld instead:

[bash]§ bash test-str.sh
Hello\nWorld

I've managed to get the desired output with bash as follows:

[bash]§ STR="Hello
> World"
[bash]§ echo "$STR"

Note the double quotes around $STR. This behaves identically if saved and run as a bash script.

The following also gives the desired output:

[bash]§ echo "Hello
> World"

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

I found a short solution for it. No extra code is needed just trigger the changeDate event. E.g. $('.datepicker').datepicker().trigger('changeDate');

Convert object to JSON string in C#

I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.

public class ReturnData 
{
    public int totalCount { get; set; }
    public List<ExceptionReport> reports { get; set; }  
}

public class ExceptionReport
{
    public int reportId { get; set; }
    public string message { get; set; }  
}


string json = JsonConvert.SerializeObject(myReturnData);

Laravel Eloquent Sum of relation's column

I tried doing something similar, which took me a lot of time before I could figure out the collect() function. So you can have something this way:

collect($items)->sum('amount');

This will give you the sum total of all the items.

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

Disable a link in Bootstrap

You cant set links to "disabled" just system elements like input, textfield etc.

But you can disable links with jQuery/JavaScript

$('.disabled').click(function(e){
    e.preventDefault();
});

Just wrap the above code in whatever event you want to disable the links.

How do I completely remove root password

Did you try passwd -d root? Most likely, this will do what you want.


You can also manually edit /etc/shadow: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to

root:$X$SK5xfLB1ZW:0:0...

There, delete the second field (everything between the first and second colon):

root::0:0...

Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)

root:*:0:0...

Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd, and use mkpasswd to create the second field for the /etc/shadow.)

adding line break

The correct answer is to use Environment.NewLine, as you've noted. It is environment specific and provides clarity over "\r\n" (but in reality makes no difference).

foreach (var item in FirmNameList) 
{
    if (FirmNames != "")
    {
        FirmNames += ", " + Environment.NewLine;
    }
    FirmNames += item; 
} 

Programmatically add custom event in the iPhone Calendar

Working code in Swift-4.2

import UIKit
import EventKit
import EventKitUI

class yourViewController: UIViewController{

    let eventStore = EKEventStore()

    func addEventToCalendar() {

    eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in
        DispatchQueue.main.async {
            if (granted) && (error == nil) {
                let event = EKEvent(eventStore: self.eventStore)
                event.title = self.headerDescription
                event.startDate = self.parse(self.requestDetails.value(forKey: "session_time") as? String ?? "")
                event.endDate = self.parse(self.requestDetails.value(forKey: "session_end_time") as? String ?? "")
                let eventController = EKEventEditViewController()
                eventController.event = event
                eventController.eventStore = self.eventStore
                eventController.editViewDelegate = self
                self.present(eventController, animated: true, completion: nil)

            }
        }


       })
    }

}

Now we will get the event screen and here you can also modify your settings:

enter image description here

Now add delegate method to handle Cancel and add the event button action of event screen:

    extension viewController: EKEventEditViewDelegate {

    func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
        controller.dismiss(animated: true, completion: nil)

    }
}

Note: Don't forget to add NSCalendarsUsageDescription key into info plist.

React navigation goBack() and update parent state

You can pass a callback function as parameter when you call navigate like this:

  const DEMO_TOKEN = await AsyncStorage.getItem('id_token');
  if (DEMO_TOKEN === null) {
    this.props.navigation.navigate('Login', {
      onGoBack: () => this.refresh(),
    });
    return -3;
  } else {
    this.doSomething();
  }

And define your callback function:

refresh() {
  this.doSomething();
}

Then in the login/registration view, before goBack, you can do this:

await AsyncStorage.setItem('id_token', myId);
this.props.navigation.state.params.onGoBack();
this.props.navigation.goBack();

Update for React Navigation v5:

await AsyncStorage.setItem('id_token', myId);
this.props.route.params.onGoBack();
this.props.navigation.goBack();

MySQL Error 1093 - Can't specify target table for update in FROM clause

DELETE FROM story_category
WHERE category_id NOT IN (
    SELECT cid FROM (
        SELECT DISTINCT category.id AS cid FROM category INNER JOIN story_category ON category_id=category.id
    ) AS c
)

I need an unordered list without any bullets

I tried and observed:

header ul {
   margin: 0;
   padding: 0;
}

ASP.NET DateTime Picker

@Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control", @type = "date" } })

this works well

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

Why use getters and setters/accessors?

This is a good question with even better answers. As there are a lot of them, I will just put there a little more This example is based on C#, just a useful piece of code. Validating data in the brackets were already explained.

public class foo
{
    public int f1 { get; set; }             // A classic GS
    public int f2 { get; private set; }     // A GS with public read access, the write is only on the private level
    public int f3 { private get; set; }     // A GS where "You can set, but you can't get" outside the class
    public int f4 { get; set; } = 10;       // A GS with default value, this is a NEW feature of C# 6.0 / .NET 4.6
}

How can we redirect a Java program console output to multiple files?

Go to run as and choose Run Configurations -> Common and in the Standard Input and Output you can choose a File also.

How to access Winform textbox control from another class?

// Take the Active form to a form variable.

Form F1 = myForm1.ActiveForm;

//Findout the Conntrol and Change the properties

F1.Controls.Find("Textbox1", true).ElementAt(0).Text= "Whatever you want to write";

How to create JSON string in JavaScript?

The way i do it is:

   var obj = new Object();
   obj.name = "Raj";
   obj.age  = 32;
   obj.married = false;
   var jsonString= JSON.stringify(obj);

I guess this way can reduce chances for errors.

How do I get ruby to print a full backtrace instead of a truncated one?

One liner for callstack:

begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace; end

One liner for callstack without all the gems's:

begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace.grep_v(/\/gems\//); end

One liner for callstack without all the gems's and relative to current directory

begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace.grep_v(/\/gems\//).map { |l| l.gsub(`pwd`.strip + '/', '') }; end

How do you fadeIn and animate at the same time?

Another way to do simultaneous animations if you want to call them separately (eg. from different code) is to use queue. Again, as with Tinister's answer you would have to use animate for this and not fadeIn:

$('.tooltip').css('opacity', 0);
$('.tooltip').show();
...

$('.tooltip').animate({opacity: 1}, {queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');

How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

<form>
  <label for="company">
    <span>Company Name</span>
    <input type="text" id="company" />
  </label>
  <label for="contact">
    <span>Contact Name</span>
    <input type="text" id="contact" />
  </label>
</form>

label { width: 200px; float: left; margin: 0 20px 0 0; }
span { display: block; margin: 0 0 3px; font-size: 1.2em; font-weight: bold; }
input { width: 200px; border: 1px solid #000; padding: 5px; }

Illustrated at http://jsfiddle.net/H3y8j/

Single quotes vs. double quotes in Python

I use double quotes in general, but not for any specific reason - Probably just out of habit from Java.

I guess you're also more likely to want apostrophes in an inline literal string than you are to want double quotes.

C++ Singleton design pattern

You could avoid memory allocation. There are many variants, all having problems in case of multithreading environment.

I prefer this kind of implementation (actually, it is not correctly said I prefer, because I avoid singletons as much as possible):

class Singleton
{
private:
   Singleton();

public:
   static Singleton& instance()
   {
      static Singleton INSTANCE;
      return INSTANCE;
   }
};

It has no dynamic memory allocation.

Set default heap size in Windows

Setup JAVA_OPTS as a system variable with the following content:

JAVA_OPTS="-Xms256m -Xmx512m"

After that in a command prompt run the following commands:

SET JAVA_OPTS="-Xms256m -Xmx512m"

This can be explained as follows:

  • allocate at minimum 256MBs of heap
  • allocate at maximum 512MBs of heap

These values should be changed according to application requirements.

EDIT:

You can also try adding it through the Environment Properties menu which can be found at:

  1. From the Desktop, right-click My Computer and click Properties.
  2. Click Advanced System Settings link in the left column.
  3. In the System Properties window click the Environment Variables button.
  4. Click New to add a new variable name and value.
  5. For variable name enter JAVA_OPTS for variable value enter -Xms256m -Xmx512m
  6. Click ok and close the System Properties Tab.
  7. Restart any java applications.

EDIT 2:

JAVA_OPTS is a system variable that stores various settings/configurations for your local Java Virtual Machine. By having JAVA_OPTS set as a system variable all applications running on top of the JVM will take their settings from this parameter.

To setup a system variable you have to complete the steps listed above from 1 to 4.

Is there a timeout for idle PostgreSQL connections?

A possible workaround that allows to enable database session timeout without an external scheduled task is to use the extension pg_timeout that I have developped.

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

How to use Switch in SQL Server

Actually i am getting return value from a another sp into @temp and then it @temp =1 then i want to inc the count of @SelectoneCount by 1 and so on. Please let me know what is the correct syntax.

What's wrong with:

IF @Temp = 1 --Or @Temp = 2 also?
BEGIN
    SET @SelectoneCount = @SelectoneCount + 1
END

(Although this does reek of being procedural code - not usually the best way to use SQL)

Spring Boot Java Config Set Session Timeout

You should be able to set the server.session.timeout in your application.properties file.

ref: http://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Delete from a table based on date

This is pretty vague. Do you mean like in SQL:

DELETE FROM myTable
WHERE dateColumn < '2007'

Java 8 Stream and operation on arrays

Be careful if you have to deal with large numbers.

int[] arr = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE};
long sum = Arrays.stream(arr).sum(); // Wrong: sum == 0

The sum above is not 2 * Integer.MIN_VALUE. You need to do this in this case.

long sum = Arrays.stream(arr).mapToLong(Long::valueOf).sum(); // Correct

CSS background-image-opacity?

Try this

<div style="background: linear-gradient( rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7) ), url(/image.png);background-repeat: no-repeat; background-position: center;"> </div>

Scala check if element is present in a list

You can also implement a contains method with foldLeft, it's pretty awesome. I just love foldLeft algorithms.

For example:

object ContainsWithFoldLeft extends App {

  val list = (0 to 10).toList
  println(contains(list, 10)) //true
  println(contains(list, 11)) //false

  def contains[A](list: List[A], item: A): Boolean = {
    list.foldLeft(false)((r, c) => c.equals(item) || r)
  }
}

Is it possible to get the current spark context settings in PySpark?

For Spark 2+ you can also use when using scala

spark.conf.getAll; //spark as spark session 

How does database indexing work?

Classic example "Index in Books"

Consider a "Book" of 1000 pages, divided by 10 Chapters, each section with 100 pages.

Simple, huh?

Now, imagine you want to find a particular Chapter that contains a word "Alchemist". Without an index page, you have no other option than scanning through the entire book/Chapters. i.e: 1000 pages.

This analogy is known as "Full Table Scan" in database world.

enter image description here

But with an index page, you know where to go! And more, to lookup any particular Chapter that matters, you just need to look over the index page, again and again, every time. After finding the matching index you can efficiently jump to that chapter by skipping the rest.

But then, in addition to actual 1000 pages, you will need another ~10 pages to show the indices, so totally 1010 pages.

Thus, the index is a separate section that stores values of indexed column + pointer to the indexed row in a sorted order for efficient look-ups.

Things are simple in schools, isn't it? :P

Formatting a float to 2 decimal places

You can pass the format in to the ToString method, e.g.:

myFloatVariable.ToString("0.00"); //2dp Number

myFloatVariable.ToString("n2"); // 2dp Number

myFloatVariable.ToString("c2"); // 2dp currency

Standard Number Format Strings

SQL Server Format Date DD.MM.YYYY HH:MM:SS

See http://msdn.microsoft.com/en-us/library/ms187928.aspx

You can concatenate it:

SELECT CONVERT(VARCHAR(10), GETDATE(), 104) + ' ' + CONVERT(VARCHAR(8), GETDATE(), 108)

How to handle the click event in Listview in android?

First, the class must implements the click listenener :

implements OnItemClickListener

Then set a listener to the ListView

yourList.setOnItemclickListener(this);

And finally, create the clic method:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(MainActivity.this, "You Clicked at ",   
 Toast.LENGTH_SHORT).show();
}

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

{"a":"\u00e1"} and {"a":"á"} are different ways to write the same JSON document; The JSON decoder will decode the unicode escape.

In php 5.4+, php's json_encode does have the JSON_UNESCAPED_UNICODE option for plain output. On older php versions, you can roll out your own JSON encoder that does not encode non-ASCII characters, or use Pear's JSON encoder and remove line 349 to 433.

Declare a dictionary inside a static class

Create a static constructor to add values in the Dictionary

enum Commands
{
    StudentDetail
}
public static class Quires
{
    public static Dictionary<Commands, String> quire
        = new Dictionary<Commands, String>();
    static Quires()
    {
        quire.add(Commands.StudentDetail,@"SELECT * FROM student_b");
    }
}

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

I've faced with this problem on Windows 10. I tried several solutions but none of them worked.
Here is what I did to solve my problem:

  • Uninstalled Android Studio, SDK, .android and .AndroidStudio folders in %USERPROFILE%, Android folder in %LOCALAPPDATA%.
  • Uninstalled Java.
  • Downloaded latest Java JDK:
    https://www.oracle.com/technetwork/java/javase/downloads/jdk13-downloads-5672538.html

    and set PATH Environment Variable:
    https://docs.oracle.com/en/java/javase/11/install/installation-jdk-microsoft-windows-platforms.html#GUID-96EB3876-8C7A-4A25-9F3A-A2983FEC016A
  • I created new Windows 10 local user using LATIN CHARACTERS with admin priviledges.
  • Switched to the new user and installed Android Studio.
  • When the setup wizard was shown, I selected Custom option and checked Android emulator to be installed. I left all location folders as DEFAULT.


Now everything works fine on my new user account.

Angular 2 filter/search list

HTML

<input [(ngModel)] = "searchTerm" (ngModelChange) = "search()"/>
<div *ngFor = "let item of items">{{item.name}}</div>

Component

search(): void {
    let term = this.searchTerm;
    this.items = this.itemsCopy.filter(function(tag) {
        return tag.name.indexOf(term) >= 0;
    }); 
}

Note that this.itemsCopy is equal to this.items and should be set before doing the search.

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you used a raw socket (SOCK_RAW) and re-implemented TCP in userland, I think the answer is limited in this case only by the number of (local address, source port, destination address, destination port) tuples (~2^64 per local address).

It would of course take a lot of memory to keep the state of all those connections, and I think you would have to set up some iptables rules to keep the kernel TCP stack from getting upset &/or responding on your behalf.

How to change letter spacing in a Textview?

For embedding HTML text in your textview you can use Html.fromHTML() syntax. More information you will get from http://developer.android.com/reference/android/text/Html.html#fromHtml%28java.lang.String%29

error: Libtool library used but 'LIBTOOL' is undefined

Fixed it. I needed to run libtoolize in the directory, then re-run:

  • aclocal

  • autoheader

Excel VBA If cell.Value =... then

I think it would make more sense to use "Find" function in Excel instead of For Each loop. It works much much faster and it's designed for such actions. Try this:

 Sub FindSomeCells(strSearchQuery As String)   

    Set SearchRange = Worksheets("Sheet1").Range("A1:A100")
    FindWhat = strSearchQuery
    Set FoundCells = FindAll(SearchRange:=SearchRange, _
                            FindWhat:=FindWhat, _
                            LookIn:=xlValues, _
                            LookAt:=xlWhole, _
                            SearchOrder:=xlByColumns, _
                            MatchCase:=False, _
                            BeginsWith:=vbNullString, _
                            EndsWith:=vbNullString, _
                            BeginEndCompare:=vbTextCompare)
    If FoundCells Is Nothing Then
        Debug.Print "Value Not Found"
    Else
        For Each FoundCell In FoundCells
            FoundCell.Interior.Color = XlRgbColor.rgbLightGreen
        Next FoundCell
    End If

End Sub

That subroutine searches for some string and returns a collections of cells fullfilling your search criteria. Then you can do whatever you want with the cells in that collection. Forgot to add the FindAll function definition:

Function FindAll(SearchRange As Range, _
                FindWhat As Variant, _
               Optional LookIn As XlFindLookIn = xlValues, _
                Optional LookAt As XlLookAt = xlWhole, _
                Optional SearchOrder As XlSearchOrder = xlByRows, _
                Optional MatchCase As Boolean = False, _
                Optional BeginsWith As String = vbNullString, _
                Optional EndsWith As String = vbNullString, _
                Optional BeginEndCompare As VbCompareMethod = vbTextCompare) As Range
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' FindAll
' This searches the range specified by SearchRange and returns a Range object
' that contains all the cells in which FindWhat was found. The search parameters to
' this function have the same meaning and effect as they do with the
' Range.Find method. If the value was not found, the function return Nothing. If
' BeginsWith is not an empty string, only those cells that begin with BeginWith
' are included in the result. If EndsWith is not an empty string, only those cells
' that end with EndsWith are included in the result. Note that if a cell contains
' a single word that matches either BeginsWith or EndsWith, it is included in the
' result.  If BeginsWith or EndsWith is not an empty string, the LookAt parameter
' is automatically changed to xlPart. The tests for BeginsWith and EndsWith may be
' case-sensitive by setting BeginEndCompare to vbBinaryCompare. For case-insensitive
' comparisons, set BeginEndCompare to vbTextCompare. If this parameter is omitted,
' it defaults to vbTextCompare. The comparisons for BeginsWith and EndsWith are
' in an OR relationship. That is, if both BeginsWith and EndsWith are provided,
' a match if found if the text begins with BeginsWith OR the text ends with EndsWith.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Dim FoundCell As Range
Dim FirstFound As Range
Dim LastCell As Range
Dim ResultRange As Range
Dim XLookAt As XlLookAt
Dim Include As Boolean
Dim CompMode As VbCompareMethod
Dim Area As Range
Dim MaxRow As Long
Dim MaxCol As Long
Dim BeginB As Boolean
Dim EndB As Boolean
CompMode = BeginEndCompare
If BeginsWith <> vbNullString Or EndsWith <> vbNullString Then
    XLookAt = xlPart
Else
    XLookAt = LookAt
End If
' this loop in Areas is to find the last cell
' of all the areas. That is, the cell whose row
' and column are greater than or equal to any cell
' in any Area.

For Each Area In SearchRange.Areas
    With Area
        If .Cells(.Cells.Count).Row > MaxRow Then
            MaxRow = .Cells(.Cells.Count).Row
        End If
        If .Cells(.Cells.Count).Column > MaxCol Then
            MaxCol = .Cells(.Cells.Count).Column
        End If
    End With
Next Area
Set LastCell = SearchRange.Worksheet.Cells(MaxRow, MaxCol)
On Error GoTo 0
Set FoundCell = SearchRange.Find(what:=FindWhat, _
        after:=LastCell, _
        LookIn:=LookIn, _
        LookAt:=XLookAt, _
        SearchOrder:=SearchOrder, _
        MatchCase:=MatchCase)
If Not FoundCell Is Nothing Then
    Set FirstFound = FoundCell
    Do Until False ' Loop forever. We'll "Exit Do" when necessary.
        Include = False
        If BeginsWith = vbNullString And EndsWith = vbNullString Then
            Include = True
        Else
            If BeginsWith <> vbNullString Then
                If StrComp(Left(FoundCell.Text, Len(BeginsWith)), BeginsWith, BeginEndCompare) = 0 Then
                    Include = True
                End If
            End If
            If EndsWith <> vbNullString Then
                If StrComp(Right(FoundCell.Text, Len(EndsWith)), EndsWith, BeginEndCompare) = 0 Then
                    Include = True
                End If
            End If
        End If
        If Include = True Then
            If ResultRange Is Nothing Then
                Set ResultRange = FoundCell
            Else
                Set ResultRange = Application.Union(ResultRange, FoundCell)
            End If
        End If
        Set FoundCell = SearchRange.FindNext(after:=FoundCell)
        If (FoundCell Is Nothing) Then
            Exit Do
        End If
        If (FoundCell.Address = FirstFound.Address) Then
            Exit Do
        End If
    Loop
End If
Set FindAll = ResultRange
End Function

What is it exactly a BLOB in a DBMS context

This may seem like a silly question, but what do you actually want to use a RDBMS for ?

If you just want to store files, then the operating system's filesystem is generally adequate. An RDBMS is generally used for structured data and (except for embedded ones like SQLite) handling concurrent manipulation of that data (locking etc). Other useful features are security (handling access to the data) and backup/recovery. In the latter, the primary advantage over a regular filesystem backup is being able to recover to a point in time between backups by applying some form of log files.

BLOBs are, as far as the database concerned, unstructured and opaque. Oracle does have some specific ORDSYS types for multi-media objects (eg images) that also have a bunch of metadata attached, and have associated methods (eg rescaling or recolouring an image).

CodeIgniter activerecord, retrieve last insert id?

Try this.

public function insert_data_function($your_data)
{
    $this->db->insert("your_table",$your_data);
    $last_id = $this->db->insert_id();
    return $last_id;
}

What is the convention for word separator in Java package names?

The official naming conventions aren't that strict, they don't even 'forbid' camel case notation except for prefix (com in your example).

But I personally would avoid upper case letters and hyphenations, even numbers. I'd choose com.stackoverflow.mypackage like Bragboy suggested too.

(hyphenations '-' are not legal in package names)

EDIT

Interesting - the language specification has something to say about naming conventions too.

In Chapter 7.7 Unique Package Names we see examples with package names that consist of upper case letters (so CamelCase notation would be OK) and they suggest to replace hyphonation by an underscore ("mary-lou" -> "mary_lou") and prefix java keywords with an underscore ("com.example.enum" -> "com.example._enum")

Some more examples for upper case letters in package names can be found in chapter 6.8.1 Package Names.

Error in file(file, "rt") : cannot open the connection

Use setwd() to change to appropriate directory. Use only filename to access any file in the working directory. Navigate a folder above by using "../<filename>".

LINQ - Full Outer Join

I really hate these linq expressions, this is why SQL exists:

select isnull(fn.id, ln.id) as id, fn.firstname, ln.lastname
   from firstnames fn
   full join lastnames ln on ln.id=fn.id

Create this as sql view in database and import it as entity.

Of course, (distinct) union of left and right joins will make it too, but it is stupid.

Update value of a nested dictionary of varying depth

Minor improvements to @Alex's answer that enables updating of dictionaries of differing depths as well as limiting the depth that the update dives into the original nested dictionary (but the updating dictionary depth is not limited). Only a few cases have been tested:

def update(d, u, depth=-1):
    """
    Recursively merge or update dict-like objects. 
    >>> update({'k1': {'k2': 2}}, {'k1': {'k2': {'k3': 3}}, 'k4': 4})
    {'k1': {'k2': {'k3': 3}}, 'k4': 4}
    """

    for k, v in u.iteritems():
        if isinstance(v, Mapping) and not depth == 0:
            r = update(d.get(k, {}), v, depth=max(depth - 1, -1))
            d[k] = r
        elif isinstance(d, Mapping):
            d[k] = u[k]
        else:
            d = {k: u[k]}
    return d

How does the ARM architecture differ from x86?

Neither has anything specific to keyboard or mobile, other than the fact that for years ARM has had a pretty substantial advantage in terms of power consumption, which made it attractive for all sorts of battery operated devices.

As far as the actual differences: ARM has more registers, supported predication for most instructions long before Intel added it, and has long incorporated all sorts of techniques (call them "tricks", if you prefer) to save power almost everywhere it could.

There's also a considerable difference in how the two encode instructions. Intel uses a fairly complex variable-length encoding in which an instruction can occupy anywhere from 1 up to 15 byte. This allows programs to be quite small, but makes instruction decoding relatively difficult (as in: decoding instructions fast in parallel is more like a complete nightmare).

ARM has two different instruction encoding modes: ARM and THUMB. In ARM mode, you get access to all instructions, and the encoding is extremely simple and fast to decode. Unfortunately, ARM mode code tends to be fairly large, so it's fairly common for a program to occupy around twice as much memory as Intel code would. Thumb mode attempts to mitigate that. It still uses quite a regular instruction encoding, but reduces most instructions from 32 bits to 16 bits, such as by reducing the number of registers, eliminating predication from most instructions, and reducing the range of branches. At least in my experience, this still doesn't usually give quite as dense of coding as x86 code can get, but it's fairly close, and decoding is still fairly simple and straightforward. Lower code density means you generally need at least a little more memory and (generally more seriously) a larger cache to get equivalent performance.

At one time Intel put a lot more emphasis on speed than power consumption. They started emphasizing power consumption primarily on the context of laptops. For laptops their typical power goal was on the order of 6 watts for a fairly small laptop. More recently (much more recently) they've started to target mobile devices (phones, tablets, etc.) For this market, they're looking at a couple of watts or so at most. They seem to be doing pretty well at that, though their approach has been substantially different from ARM's, emphasizing fabrication technology where ARM has mostly emphasized micro-architecture (not surprising, considering that ARM sells designs, and leaves fabrication to others).

Depending on the situation, a CPU's energy consumption is often more important than its power consumption though. At least as I'm using the terms, power consumption refers to power usage on a (more or less) instantaneous basis. Energy consumption, however, normalizes for speed, so if (for example) CPU A consumes 1 watt for 2 seconds to do a job, and CPU B consumes 2 watts for 1 second to do the same job, both CPUs consume the same total amount of energy (two watt seconds) to do that job--but with CPU B, you get results twice as fast.

ARM processors tend to do very well in terms of power consumption. So if you need something that needs a processor's "presence" almost constantly, but isn't really doing much work, they can work out pretty well. For example, if you're doing video conferencing, you gather a few milliseconds of data, compress it, send it, receive data from others, decompress it, play it back, and repeat. Even a really fast processor can't spend much time sleeping, so for tasks like this, ARM does really well.

Intel's processors (especially their Atom processors, which are actually intended for low power applications) are extremely competitive in terms of energy consumption. While they're running close to their full speed, they will consume more power than most ARM processors--but they also finish work quickly, so they can go back to sleep sooner. As a result, they can combine good battery life with good performance.

So, when comparing the two, you have to be careful about what you measure, to be sure that it reflects what you honestly care about. ARM does very well at power consumption, but depending on the situation you may easily care more about energy consumption than instantaneous power consumption.

Extract values in Pandas value_counts()

If anyone missed it out in the comments, try this:

dataframe[column].value_counts().to_frame()

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

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

How can I make text appear on next line instead of overflowing?

Try the <wbr> tag - not as elegant as the word-wrap property that others suggested, but it's a working solution until all major browsers (read IE) implement CSS3.

Get img thumbnails from Vimeo?

2020 solution:

I wrote a PHP function which uses the Vimeo Oembed API.

/**
 * Get Vimeo.com video thumbnail URL
 *
 * Set the referer parameter if your video is domain restricted.
 * 
 * @param  int    $videoid   Video id
 * @param  URL    $referer   Your website domain
 * @return bool/string       Thumbnail URL or false if can't access the video
 */
function get_vimeo_thumbnail_url( $videoid, $referer=null ){

    // if referer set, create context
    $ctx = null;
    if( isset($referer) ){
        $ctxa = array(
            'http' => array(
                'header' => array("Referer: $referer\r\n"),
                'request_fulluri' => true,
            ),
        );
        $ctx = stream_context_create($ctxa);
    }

    $resp = @file_get_contents("https://vimeo.com/api/oembed.json?url=https://vimeo.com/$videoid", False, $ctx);
    $resp = json_decode($resp, true);

return $resp["thumbnail_url"]??false;
}

Usage:

echo get_vimeo_thumbnail_url("1084537");

ionic 2 - Error Could not find an installed version of Gradle either in Android Studio

I moved Android folder path to another path and taked this error.

I resolved to this problem in below.

I was changed to Gradle path in system variables. But not path in user variables. You must change to path in system variables

Screenshot this

Alternative Screenshot this

How to declare a variable in a PostgreSQL query

There is no such feature in PostgreSQL. You can do it only in pl/PgSQL (or other pl/*), but not in plain SQL.

An exception is WITH () query which can work as a variable, or even tuple of variables. It allows you to return a table of temporary values.

WITH master_user AS (
    SELECT
      login,
      registration_date
    FROM users
    WHERE ...
)

SELECT *
FROM users
WHERE master_login = (SELECT login
                      FROM master_user)
      AND (SELECT registration_date
           FROM master_user) > ...;

How to develop Desktop Apps using HTML/CSS/JavaScript?

Awesomium makes it easy to use HTML UI in your C++ or .NET app

Update

My previous answer is now outdated. These days you would be crazy not to look into using Electron for this. Many popular desktop apps have been developed on top of it.

Best way to repeat a character in C#

The best version is certainly to use the builtin way:

string Tabs(int len) { return new string('\t', len); }

Of the other solutions, prefer the easiest; only if this is proving too slow, strive for a more efficient solution.

If you use a StringBuilder and know its resulting length in advance, then also use an appropriate constructor, this is much more efficient because it means that only one time-consuming allocation takes place, and no unnecessary copying of data. Nonsense: of course the above code is more efficient.

replacing NA's with 0's in R dataframe

What Tyler Rinker says is correct:

AQ2 <- airquality
AQ2[is.na(AQ2)] <- 0

will do just this.

What you are originally doing is that you are taking from airquality all those rows (cases) that are complete. So, all the cases that do not have any NA's in them, and keep only those.

Updates were rejected because the tip of your current branch is behind its remote counterpart

The command I used with Azure DevOps when I encountered the message "updates were rejected because the tip of your current branch is behind" was/is this command:

git pull origin master

(or can start with a new folder and do a Clone) ..

This answer doesn't address the question posed, specifically, Keif has answered this above, but it does answer the question's title/heading text and this will be a common question for Azure DevOps users.

I noted comment: "You'd always want to make sure that you do a pull before pushing" in answer from Keif above !

I have also used Git Gui tool in addition to Git command line tool.

(I wasn't sure how to do the equivalent of the command line command "git pull origin master" within Git Gui so I'm back to command line to do this).

A diagram that shows various git commands for various actions that you might want to undertake is this one:

enter image description here

How does PHP 'foreach' actually work?

foreach supports iteration over three different kinds of values:

In the following, I will try to explain precisely how iteration works in different cases. By far the simplest case is Traversable objects, as for these foreach is essentially only syntax sugar for code along these lines:

foreach ($it as $k => $v) { /* ... */ }

/* translates to: */

if ($it instanceof IteratorAggregate) {
    $it = $it->getIterator();
}
for ($it->rewind(); $it->valid(); $it->next()) {
    $v = $it->current();
    $k = $it->key();
    /* ... */
}

For internal classes, actual method calls are avoided by using an internal API that essentially just mirrors the Iterator interface on the C level.

Iteration of arrays and plain objects is significantly more complicated. First of all, it should be noted that in PHP "arrays" are really ordered dictionaries and they will be traversed according to this order (which matches the insertion order as long as you didn't use something like sort). This is opposed to iterating by the natural order of the keys (how lists in other languages often work) or having no defined order at all (how dictionaries in other languages often work).

The same also applies to objects, as the object properties can be seen as another (ordered) dictionary mapping property names to their values, plus some visibility handling. In the majority of cases, the object properties are not actually stored in this rather inefficient way. However, if you start iterating over an object, the packed representation that is normally used will be converted to a real dictionary. At that point, iteration of plain objects becomes very similar to iteration of arrays (which is why I'm not discussing plain-object iteration much in here).

So far, so good. Iterating over a dictionary can't be too hard, right? The problems begin when you realize that an array/object can change during iteration. There are multiple ways this can happen:

  • If you iterate by reference using foreach ($arr as &$v) then $arr is turned into a reference and you can change it during iteration.
  • In PHP 5 the same applies even if you iterate by value, but the array was a reference beforehand: $ref =& $arr; foreach ($ref as $v)
  • Objects have by-handle passing semantics, which for most practical purposes means that they behave like references. So objects can always be changed during iteration.

The problem with allowing modifications during iteration is the case where the element you are currently on is removed. Say you use a pointer to keep track of which array element you are currently at. If this element is now freed, you are left with a dangling pointer (usually resulting in a segfault).

There are different ways of solving this issue. PHP 5 and PHP 7 differ significantly in this regard and I'll describe both behaviors in the following. The summary is that PHP 5's approach was rather dumb and lead to all kinds of weird edge-case issues, while PHP 7's more involved approach results in more predictable and consistent behavior.

As a last preliminary, it should be noted that PHP uses reference counting and copy-on-write to manage memory. This means that if you "copy" a value, you actually just reuse the old value and increment its reference count (refcount). Only once you perform some kind of modification a real copy (called a "duplication") will be done. See You're being lied to for a more extensive introduction on this topic.

PHP 5

Internal array pointer and HashPointer

Arrays in PHP 5 have one dedicated "internal array pointer" (IAP), which properly supports modifications: Whenever an element is removed, there will be a check whether the IAP points to this element. If it does, it is advanced to the next element instead.

While foreach does make use of the IAP, there is an additional complication: There is only one IAP, but one array can be part of multiple foreach loops:

// Using by-ref iteration here to make sure that it's really
// the same array in both loops and not a copy
foreach ($arr as &$v1) {
    foreach ($arr as &$v) {
        // ...
    }
}

To support two simultaneous loops with only one internal array pointer, foreach performs the following shenanigans: Before the loop body is executed, foreach will back up a pointer to the current element and its hash into a per-foreach HashPointer. After the loop body runs, the IAP will be set back to this element if it still exists. If however the element has been removed, we'll just use wherever the IAP is currently at. This scheme mostly-kinda-sort of works, but there's a lot of weird behavior you can get out of it, some of which I'll demonstrate below.

Array duplication

The IAP is a visible feature of an array (exposed through the current family of functions), as such changes to the IAP count as modifications under copy-on-write semantics. This, unfortunately, means that foreach is in many cases forced to duplicate the array it is iterating over. The precise conditions are:

  1. The array is not a reference (is_ref=0). If it's a reference, then changes to it are supposed to propagate, so it should not be duplicated.
  2. The array has refcount>1. If refcount is 1, then the array is not shared and we're free to modify it directly.

If the array is not duplicated (is_ref=0, refcount=1), then only its refcount will be incremented (*). Additionally, if foreach by reference is used, then the (potentially duplicated) array will be turned into a reference.

Consider this code as an example where duplication occurs:

function iterate($arr) {
    foreach ($arr as $v) {}
}

$outerArr = [0, 1, 2, 3, 4];
iterate($outerArr);

Here, $arr will be duplicated to prevent IAP changes on $arr from leaking to $outerArr. In terms of the conditions above, the array is not a reference (is_ref=0) and is used in two places (refcount=2). This requirement is unfortunate and an artifact of the suboptimal implementation (there is no concern of modification during iteration here, so we don't really need to use the IAP in the first place).

(*) Incrementing the refcount here sounds innocuous, but violates copy-on-write (COW) semantics: This means that we are going to modify the IAP of a refcount=2 array, while COW dictates that modifications can only be performed on refcount=1 values. This violation results in user-visible behavior change (while a COW is normally transparent) because the IAP change on the iterated array will be observable -- but only until the first non-IAP modification on the array. Instead, the three "valid" options would have been a) to always duplicate, b) do not increment the refcount and thus allowing the iterated array to be arbitrarily modified in the loop or c) don't use the IAP at all (the PHP 7 solution).

Position advancement order

There is one last implementation detail that you have to be aware of to properly understand the code samples below. The "normal" way of looping through some data structure would look something like this in pseudocode:

reset(arr);
while (get_current_data(arr, &data) == SUCCESS) {
    code();
    move_forward(arr);
}

However foreach, being a rather special snowflake, chooses to do things slightly differently:

reset(arr);
while (get_current_data(arr, &data) == SUCCESS) {
    move_forward(arr);
    code();
}

Namely, the array pointer is already moved forward before the loop body runs. This means that while the loop body is working on element $i, the IAP is already at element $i+1. This is the reason why code samples showing modification during iteration will always unset the next element, rather than the current one.

Examples: Your test cases

The three aspects described above should provide you with a mostly complete impression of the idiosyncrasies of the foreach implementation and we can move on to discuss some examples.

The behavior of your test cases is simple to explain at this point:

  • In test cases 1 and 2 $array starts off with refcount=1, so it will not be duplicated by foreach: Only the refcount is incremented. When the loop body subsequently modifies the array (which has refcount=2 at that point), the duplication will occur at that point. Foreach will continue working on an unmodified copy of $array.

  • In test case 3, once again the array is not duplicated, thus foreach will be modifying the IAP of the $array variable. At the end of the iteration, the IAP is NULL (meaning iteration has done), which each indicates by returning false.

  • In test cases 4 and 5 both each and reset are by-reference functions. The $array has a refcount=2 when it is passed to them, so it has to be duplicated. As such foreach will be working on a separate array again.

Examples: Effects of current in foreach

A good way to show the various duplication behaviors is to observe the behavior of the current() function inside a foreach loop. Consider this example:

foreach ($array as $val) {
    var_dump(current($array));
}
/* Output: 2 2 2 2 2 */

Here you should know that current() is a by-ref function (actually: prefer-ref), even though it does not modify the array. It has to be in order to play nice with all the other functions like next which are all by-ref. By-reference passing implies that the array has to be separated and thus $array and the foreach-array will be different. The reason you get 2 instead of 1 is also mentioned above: foreach advances the array pointer before running the user code, not after. So even though the code is at the first element, foreach already advanced the pointer to the second.

Now lets try a small modification:

$ref = &$array;
foreach ($array as $val) {
    var_dump(current($array));
}
/* Output: 2 3 4 5 false */

Here we have the is_ref=1 case, so the array is not copied (just like above). But now that it is a reference, the array no longer has to be duplicated when passing to the by-ref current() function. Thus current() and foreach work on the same array. You still see the off-by-one behavior though, due to the way foreach advances the pointer.

You get the same behavior when doing by-ref iteration:

foreach ($array as &$val) {
    var_dump(current($array));
}
/* Output: 2 3 4 5 false */

Here the important part is that foreach will make $array an is_ref=1 when it is iterated by reference, so basically you have the same situation as above.

Another small variation, this time we'll assign the array to another variable:

$foo = $array;
foreach ($array as $val) {
    var_dump(current($array));
}
/* Output: 1 1 1 1 1 */

Here the refcount of the $array is 2 when the loop is started, so for once we actually have to do the duplication upfront. Thus $array and the array used by foreach will be completely separate from the outset. That's why you get the position of the IAP wherever it was before the loop (in this case it was at the first position).

Examples: Modification during iteration

Trying to account for modifications during iteration is where all our foreach troubles originated, so it serves to consider some examples for this case.

Consider these nested loops over the same array (where by-ref iteration is used to make sure it really is the same one):

foreach ($array as &$v1) {
    foreach ($array as &$v2) {
        if ($v1 == 1 && $v2 == 1) {
            unset($array[1]);
        }
        echo "($v1, $v2)\n";
    }
}

// Output: (1, 1) (1, 3) (1, 4) (1, 5)

The expected part here is that (1, 2) is missing from the output because element 1 was removed. What's probably unexpected is that the outer loop stops after the first element. Why is that?

The reason behind this is the nested-loop hack described above: Before the loop body runs, the current IAP position and hash is backed up into a HashPointer. After the loop body it will be restored, but only if the element still exists, otherwise the current IAP position (whatever it may be) is used instead. In the example above this is exactly the case: The current element of the outer loop has been removed, so it will use the IAP, which has already been marked as finished by the inner loop!

Another consequence of the HashPointer backup+restore mechanism is that changes to the IAP through reset() etc. usually do not impact foreach. For example, the following code executes as if the reset() were not present at all:

$array = [1, 2, 3, 4, 5];
foreach ($array as &$value) {
    var_dump($value);
    reset($array);
}
// output: 1, 2, 3, 4, 5

The reason is that, while reset() temporarily modifies the IAP, it will be restored to the current foreach element after the loop body. To force reset() to make an effect on the loop, you have to additionally remove the current element, so that the backup/restore mechanism fails:

$array = [1, 2, 3, 4, 5];
$ref =& $array;
foreach ($array as $value) {
    var_dump($value);
    unset($array[1]);
    reset($array);
}
// output: 1, 1, 3, 4, 5

But, those examples are still sane. The real fun starts if you remember that the HashPointer restore uses a pointer to the element and its hash to determine whether it still exists. But: Hashes have collisions, and pointers can be reused! This means that, with a careful choice of array keys, we can make foreach believe that an element that has been removed still exists, so it will jump directly to it. An example:

$array = ['EzEz' => 1, 'EzFY' => 2, 'FYEz' => 3];
$ref =& $array;
foreach ($array as $value) {
    unset($array['EzFY']);
    $array['FYFY'] = 4;
    reset($array);
    var_dump($value);
}
// output: 1, 4

Here we should normally expect the output 1, 1, 3, 4 according to the previous rules. How what happens is that 'FYFY' has the same hash as the removed element 'EzFY', and the allocator happens to reuse the same memory location to store the element. So foreach ends up directly jumping to the newly inserted element, thus short-cutting the loop.

Substituting the iterated entity during the loop

One last odd case that I'd like to mention, it is that PHP allows you to substitute the iterated entity during the loop. So you can start iterating on one array and then replace it with another array halfway through. Or start iterating on an array and then replace it with an object:

$arr = [1, 2, 3, 4, 5];
$obj = (object) [6, 7, 8, 9, 10];

$ref =& $arr;
foreach ($ref as $val) {
    echo "$val\n";
    if ($val == 3) {
        $ref = $obj;
    }
}
/* Output: 1 2 3 6 7 8 9 10 */

As you can see in this case PHP will just start iterating the other entity from the start once the substitution has happened.

PHP 7

Hashtable iterators

If you still remember, the main problem with array iteration was how to handle removal of elements mid-iteration. PHP 5 used a single internal array pointer (IAP) for this purpose, which was somewhat suboptimal, as one array pointer had to be stretched to support multiple simultaneous foreach loops and interaction with reset() etc. on top of that.

PHP 7 uses a different approach, namely, it supports creating an arbitrary amount of external, safe hashtable iterators. These iterators have to be registered in the array, from which point on they have the same semantics as the IAP: If an array element is removed, all hashtable iterators pointing to that element will be advanced to the next element.

This means that foreach will no longer use the IAP at all. The foreach loop will be absolutely no effect on the results of current() etc. and its own behavior will never be influenced by functions like reset() etc.

Array duplication

Another important change between PHP 5 and PHP 7 relates to array duplication. Now that the IAP is no longer used, by-value array iteration will only do a refcount increment (instead of duplication the array) in all cases. If the array is modified during the foreach loop, at that point a duplication will occur (according to copy-on-write) and foreach will keep working on the old array.

In most cases, this change is transparent and has no other effect than better performance. However, there is one occasion where it results in different behavior, namely the case where the array was a reference beforehand:

$array = [1, 2, 3, 4, 5];
$ref = &$array;
foreach ($array as $val) {
    var_dump($val);
    $array[2] = 0;
}
/* Old output: 1, 2, 0, 4, 5 */
/* New output: 1, 2, 3, 4, 5 */

Previously by-value iteration of reference-arrays was special cases. In this case, no duplication occurred, so all modifications of the array during iteration would be reflected by the loop. In PHP 7 this special case is gone: A by-value iteration of an array will always keep working on the original elements, disregarding any modifications during the loop.

This, of course, does not apply to by-reference iteration. If you iterate by-reference all modifications will be reflected by the loop. Interestingly, the same is true for by-value iteration of plain objects:

$obj = new stdClass;
$obj->foo = 1;
$obj->bar = 2;
foreach ($obj as $val) {
    var_dump($val);
    $obj->bar = 42;
}
/* Old and new output: 1, 42 */

This reflects the by-handle semantics of objects (i.e. they behave reference-like even in by-value contexts).

Examples

Let's consider a few examples, starting with your test cases:

  • Test cases 1 and 2 retain the same output: By-value array iteration always keep working on the original elements. (In this case, even refcounting and duplication behavior is exactly the same between PHP 5 and PHP 7).

  • Test case 3 changes: Foreach no longer uses the IAP, so each() is not affected by the loop. It will have the same output before and after.

  • Test cases 4 and 5 stay the same: each() and reset() will duplicate the array before changing the IAP, while foreach still uses the original array. (Not that the IAP change would have mattered, even if the array was shared.)

The second set of examples was related to the behavior of current() under different reference/refcounting configurations. This no longer makes sense, as current() is completely unaffected by the loop, so its return value always stays the same.

However, we get some interesting changes when considering modifications during iteration. I hope you will find the new behavior saner. The first example:

$array = [1, 2, 3, 4, 5];
foreach ($array as &$v1) {
    foreach ($array as &$v2) {
        if ($v1 == 1 && $v2 == 1) {
            unset($array[1]);
        }
        echo "($v1, $v2)\n";
    }
}

// Old output: (1, 1) (1, 3) (1, 4) (1, 5)
// New output: (1, 1) (1, 3) (1, 4) (1, 5)
//             (3, 1) (3, 3) (3, 4) (3, 5)
//             (4, 1) (4, 3) (4, 4) (4, 5)
//             (5, 1) (5, 3) (5, 4) (5, 5) 

As you can see, the outer loop no longer aborts after the first iteration. The reason is that both loops now have entirely separate hashtable iterators, and there is no longer any cross-contamination of both loops through a shared IAP.

Another weird edge case that is fixed now, is the odd effect you get when you remove and add elements that happen to have the same hash:

$array = ['EzEz' => 1, 'EzFY' => 2, 'FYEz' => 3];
foreach ($array as &$value) {
    unset($array['EzFY']);
    $array['FYFY'] = 4;
    var_dump($value);
}
// Old output: 1, 4
// New output: 1, 3, 4

Previously the HashPointer restore mechanism jumped right to the new element because it "looked" like it's the same as the removed element (due to colliding hash and pointer). As we no longer rely on the element hash for anything, this is no longer an issue.

onclick event pass <li> id or value

Try like this...

<script>
function getPaging(str) {
  $("#loading-content").load("dataSearch.php?"+str, hideLoader);
}
</script>

<li onclick="getPaging(this.id)" id="1">1</li>
<li onclick="getPaging(this.id)" id="2">2</li>

or unobtrusively

$(function() {
  $("li").on("click",function() {
    showLoader();
    $("#loading-content").load("dataSearch.php?"+this.id, hideLoader);
  });
});

using just

<li id="1">1</li>
<li id="2">2</li>

Typing the Enter/Return key using Python and Selenium

search = browser.find_element_by_xpath("//*[@type='text']")
search.send_keys(u'\ue007')

#ENTER = u'\ue007'

Refer to Selenium's documentation 'Special Keys'.

How to parse JSON without JSON.NET library?

For those who do not have 4.5, Here is my library function that reads json. It requires a project reference to System.Web.Extensions.

using System.Web.Script.Serialization;

public object DeserializeJson<T>(string Json)
{
    JavaScriptSerializer JavaScriptSerializer = new JavaScriptSerializer();
    return JavaScriptSerializer.Deserialize<T>(Json);
}

Usually, json is written out based on a contract. That contract can and usually will be codified in a class (T). Sometimes you can take a word from the json and search the object browser to find that type.

Example usage:

Given the json

{"logEntries":[],"value":"My Code","text":"My Text","enabled":true,"checkedIndices":[],"checkedItemsTextOverflows":false}

You could parse it into a RadComboBoxClientState object like this:

string ClientStateJson = Page.Request.Form("ReportGrid1_cboReportType_ClientState");
RadComboBoxClientState RadComboBoxClientState = DeserializeJson<RadComboBoxClientState>(ClientStateJson);
return RadComboBoxClientState.Value;

How to fix warning from date() in PHP"

You could also use this:

ini_alter('date.timezone','Asia/Calcutta');

You should call this before calling any date function. It accepts the key as the first parameter to alter PHP settings during runtime and the second parameter is the value.

I had done these things before I figured out this:

  1. Changed the PHP.timezone to "Asia/Calcutta" - but did not work
  2. Changed the lat and long parameters in the ini - did not work
  3. Used date_default_timezone_set("Asia/Calcutta"); - did not work
  4. Used ini_alter() - IT WORKED
  5. Commented date_default_timezone_set("Asia/Calcutta"); - IT WORKED
  6. Reverted the changes made to the PHP.ini - IT WORKED

For me the init_alter() method got it all working.

I am running Apache 2 (pre-installed), PHP 5.3 on OSX mountain lion

How do I install cURL on Windows?

I agree with Erroid, you must add PHP directory into PATH environment.

PATH=%PATH%;<Your_PHP_Path>

Example

PATH=%PATH%;C:\php

It worked for me. Thank you.

Make Frequency Histogram for Factor Variables

Country is a categorical variable and I want to see how many occurences of country exist in the data set. In other words, how many records/attendees are from each Country

barplot(summary(df$Country))

How to access elements of a JArray (or iterate over them)

Once you have a JArray you can treat it just like any other Enumerable object, and using linq you can access them, check them, verify them, and select them.

var str = @"[1, 2, 3]";
var jArray = JArray.Parse(str);
Console.WriteLine(String.Join("-", jArray.Where(i => (int)i > 1).Select(i => i.ToString())));

How to use custom packages

another solution:
add src/myproject to $GOPATH.

Then import "mylib" will compile.

How can I go back/route-back on vue-router?

Use router.back() directly to go back/route-back programmatic on vue-router.

How to Apply Corner Radius to LinearLayout

Layout

<LinearLayout 
    android:id="@+id/linearLayout"
    android:layout_width="300dp"
    android:gravity="center"
    android:layout_height="300dp"
    android:layout_centerInParent="true"
    android:background="@drawable/rounded_edge">
 </LinearLayout>

Drawable folder rounded_edge.xml

<shape 
xmlns:android="http://schemas.android.com/apk/res/android">
    <solid 
        android:color="@android:color/darker_gray">
    </solid>
    <stroke 
         android:width="0dp" 
         android:color="#424242">
    </stroke>
    <corners 
         android:topLeftRadius="100dip"
         android:topRightRadius="100dip"
         android:bottomLeftRadius="100dip"
         android:bottomRightRadius="100dip">
    </corners>
</shape>

UTF-8 byte[] to String

String has a constructor that takes byte[] and charsetname as parameters :)

How do you change the formatting options in Visual Studio Code?

A solution that works for me (July 2017), is to utilize ESLint. As everybody knows, you can use the linter in multiple ways, globally or locally. I use it locally and with the google style guide. They way I set it up is as follow...

  • cd to your working directory
  • npm init
  • npm install --save-dev eslint
  • node_modules/.bin/eslint --init
  • I use google style and json config file

Now you will have a .eslintrc.json file the root of your working directory. You can open that file and modify as you please utilizing the eslint rules. Next cmd+, to open vscode system preferences. In the search bar type eslint and look for "eslint.autoFixOnSave": false. Copy the setting and pasted in the user settings file and change false to true. Hope this can help someone utilizing vscode.

Different ways of clearing lists

If you're clearing the list, you, obviously, don't need the list anymore. If so, you can just delete the entire list by simple del method.

a = [1, 3, 5, 6]
del a # This will entirely delete a(the list).

But in case, you need it again, you can reinitialize it. Or just simply clear its elements by

del a[:]

Spring Boot - Loading Initial Data

As suggestion try this:

@Bean
public CommandLineRunner loadData(CustomerRepository repository) {
    return (args) -> {
        // save a couple of customers
        repository.save(new Customer("Jack", "Bauer"));
        repository.save(new Customer("Chloe", "O'Brian"));
        repository.save(new Customer("Kim", "Bauer"));
        repository.save(new Customer("David", "Palmer"));
        repository.save(new Customer("Michelle", "Dessler"));

        // fetch all customers
        log.info("Customers found with findAll():");
        log.info("-------------------------------");
        for (Customer customer : repository.findAll()) {
            log.info(customer.toString());
        }
        log.info("");

        // fetch an individual customer by ID
        Customer customer = repository.findOne(1L);
        log.info("Customer found with findOne(1L):");
        log.info("--------------------------------");
        log.info(customer.toString());
        log.info("");

        // fetch customers by last name
        log.info("Customer found with findByLastNameStartsWithIgnoreCase('Bauer'):");
        log.info("--------------------------------------------");
        for (Customer bauer : repository
                .findByLastNameStartsWithIgnoreCase("Bauer")) {
            log.info(bauer.toString());
        }
        log.info("");
    }
}

Option 2: Initialize with schema and data scripts

Prerequisites: in application.properties you have to mention this:

spring.jpa.hibernate.ddl-auto=none (otherwise scripts will be ignored by hibernate, and it will scan project for @Entity and/or @Table annotated classes)

Then, in your MyApplication class paste this:

@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("org.h2.Driver");
    dataSource.setUrl("jdbc:h2:~/myDB;MV_STORE=false");
    dataSource.setUsername("sa");
    dataSource.setPassword("");

    // schema init
    Resource initSchema = new ClassPathResource("scripts/schema-h2.sql");
    Resource initData = new ClassPathResource("scripts/data-h2.sql");
    DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema, initData);
    DatabasePopulatorUtils.execute(databasePopulator, dataSource);

    return dataSource;
}

Where scripts folder is located under resources folder (IntelliJ Idea)

Hope it helps someone

How to reference a .css file on a razor view?

You can this structure in Layout.cshtml file

<link href="~/YourCssFolder/YourCssStyle.css" rel="stylesheet" type="text/css" />

Hover and Active only when not disabled

One way is to add a partcular class while disabling buttons and overriding the hover and active states for that class in css. Or removing a class when disabling and specifying the hover and active pseudo properties on that class only in css. Either way, it likely cannot be done purely with css, you'll need to use a bit of js.

A url resource that is a dot (%2E)

It's actually not really clearly stated in the standard (RFC 3986) whether a percent-encoded version of . or .. is supposed to have the same this-folder/up-a-folder meaning as the unescaped version. Section 3.3 only talks about “The path segments . and ..”, without clarifying whether they match . and .. before or after pct-encoding.

Personally I find Firefox's interpretation that %2E does not mean . most practical, but unfortunately all the other browsers disagree. This would mean that you can't have a path component containing only . or ...

I think the only possible suggestion is “don't do that”! There are other path components that are troublesome too, typically due to server limitations: %2F, %00 and %5C sequences in paths may also be blocked by some web servers, and the empty path segment can also cause problems. So in general it's not possible to fit all possible byte sequences into a path component.

Creating watermark using html and css

I would recommend everyone look into CSS grids. It has been supported by most browsers now since about 2017. Here is a link to some documentation: https://css-tricks.com/snippets/css/complete-guide-grid/ . It is so much easier to keep your page elements where you want them, especially when it comes to responsiveness. It took me all of 20 minutes to learn how to do it, and I'm a newbie!

<div class="grid-div">
    <p class="hello">Hello</p>
    <p class="world">World</p>
</div>


//begin css//

.grid-div {
    display: grid;
    grid-template-columns: 50% 50%;
    grid-template-rows: 50% 50%;
}

.hello {
    grid-column-start: 2;
    grid-row-start: 2;
}

.world {
    grid-column-start: 1;
    grid-row-start: 2;
}

This code will split the page into 4 equal quadrants, placing the "Hello" in the bottom right, and the "World" in the bottom left without having to change their positioning or playing with margins.

This can be extrapolated into very complex grid layouts with overlapping, infinite grids of all sizes, and even grids nested inside grids, without losing control of your elements every time something changes (MS Word I'm looking at you).

Hope this helps whoever still needs it!

<div> cannot appear as a descendant of <p>

The warning appears only because the demo code has:

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box p={3}>  // <==NOTE P TAG HERE
          <Typography>{children}</Typography>
        </Box>
      )}
    </div>
  );
}

Changing it like this takes care of it:

function TabPanel(props) {
    const {children, value, index, classes, ...other} = props;

    return (
        <div
            role="tabpanel"
            hidden={value !== index}
            id={`simple-tabpanel-${index}`}
            aria-labelledby={`simple-tab-${index}`}
            {...other}
        >
            {value === index && (
                <Container>
                    <Box>   // <== P TAG REMOVED
                        {children}
                    </Box>
                </Container>
            )}
        </div>
    );
}

How to select distinct query using symfony2 doctrine query builder?

you could write

select DISTINCT f from t;

as

select f from t group by f;

thing is, I am just currently myself getting into Doctrine, so I cannot give you a real answer. but you could as shown above, simulate a distinct with group by and transform that into Doctrine. if you want add further filtering then use HAVING after group by.

How to pass parameters to maven build using pom.xml?

If we have parameter like below in our POM XML

<version>${project.version}.${svn.version}</version>
  <packaging>war</packaging>

I run maven command line as follows :

mvn clean install package -Dproject.version=10 -Dsvn.version=1

How to obtain the number of CPUs/cores in Linux from the command line?

It is very simple. Just use this command:

lscpu

jquery select element by xpath

document.evaluate() (DOM Level 3 XPath) is supported in Firefox, Chrome, Safari and Opera - the only major browser missing is MSIE. Nevertheless, jQuery supports basic XPath expressions: http://docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors (moved into a plugin in the current jQuery version, see https://plugins.jquery.com/xpath/). It simply converts XPath expressions into equivalent CSS selectors however.

What does the ??!??! operator do in C?

Well, why this exists in general is probably different than why it exists in your example.

It all started half a century ago with repurposing hardcopy communication terminals as computer user interfaces. In the initial Unix and C era that was the ASR-33 Teletype.

This device was slow (10 cps) and noisy and ugly and its view of the ASCII character set ended at 0x5f, so it had (look closely at the pic) none of the keys:

{ | } ~ 

The trigraphs were defined to fix a specific problem. The idea was that C programs could use the ASCII subset found on the ASR-33 and in other environments missing the high ASCII values.

Your example is actually two of ??!, each meaning |, so the result is ||.

However, people writing C code almost by definition had modern equipment,1 so my guess is: someone showing off or amusing themself, leaving a kind of Easter egg in the code for you to find.

It sure worked, it led to a wildly popular SO question.

ASR-33 Teletype

                                            ASR-33 Teletype


1. For that matter, the trigraphs were invented by the ANSI committee, which first met after C become a runaway success, so none of the original C code or coders would have used them.

Regex select all text between tags

You can use Pattern pattern = Pattern.compile( "[^<'tagname'/>]" );

Python Progress Bar

@Massagran: It works well in my programs. Furthermore, we need to add a counter to indicate the loop times. This counter plays as the argument of the method update. For example: read all lines of a test file and treat them on something. Suppose that the function dosth() do not concern in the variable i.

lines = open(sys.argv[1]).readlines()
i = 0
widgets=[Percentage(), Bar()]
pbar = ProgressBar(widgets=widgets,maxval=len(lines)).start()
pbar.start()
for line in lines:<pre>
    dosth();
    i += 1
    pbar.update(i)</pre>
pbar.finish()

The variable i controls the status of pbar via the method update

How to convert dataframe into time series?

R has multiple ways of represeting time series. Since you're working with daily prices of stocks, you may wish to consider that financial markets are closed on weekends and business holidays so that trading days and calendar days are not the same. However, you may need to work with your times series in terms of both trading days and calendar days. For example, daily returns are calculated from sequential daily closing prices regardless of whether a weekend intervenes. But you may also want to do calendar-based reporting such as weekly price summaries. For these reasons the xts package, an extension of zoo, is commonly used with financial data in R. An example of how it could be used with your data follows.

Assuming the data shown in your example is in the dataframe df

  library(xts)
  stocks <- xts(df[,-1], order.by=as.Date(df[,1], "%m/%d/%Y"))
#
#  daily returns
#
   returns <- diff(stocks, arithmetic=FALSE ) - 1
#
#  weekly open, high, low, close reports
#
   to.weekly(stocks$Hero_close, name="Hero")

which gives the output

           Hero.Open Hero.High Hero.Low Hero.Close
2013-03-15    1669.1   1684.45   1669.1    1684.45
2013-03-22    1690.5   1690.50   1623.3    1659.60
2013-03-28    1617.7   1617.70   1542.0    1542.00

How to use PDO to fetch results array in PHP?

Take a look at the PDOStatement.fetchAll method. You could also use fetch in an iterator pattern.

Code sample for fetchAll, from the PHP documentation:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);

Results:

Array
(
    [0] => Array
        (
            [NAME] => pear
            [COLOUR] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [COLOUR] => pink
        )
)

Measure string size in Bytes in php

Do you mean byte size or string length?

Byte size is measured with strlen(), whereas string length is queried using mb_strlen(). You can use substr() to trim a string to X bytes (note that this will break the string if it has a multi-byte encoding - as pointed out by Darhazer in the comments) and mb_substr() to trim it to X characters in the encoding of the string.

How to download dependencies in gradle

Downloading java dependencies is possible, if you actually really need to download them into a folder.

Example:

apply plugin: 'java'

dependencies {
  runtime group: 'com.netflix.exhibitor', name: 'exhibitor-standalone', version: '1.5.2'
  runtime group: 'org.apache.zookeeper',  name: 'zookeeper', version: '3.4.6'
}

repositories { mavenCentral() }

task getDeps(type: Copy) {
  from sourceSets.main.runtimeClasspath
  into 'runtime/'
}

Download the dependencies (and their dependencies) into the folder runtime when you execute gradle getDeps.

Using wget to recursively fetch a directory with arbitrary files in it

You have to pass the -np/--no-parent option to wget (in addition to -r/--recursive, of course), otherwise it will follow the link in the directory index on my site to the parent directory. So the command would look like this:

wget --recursive --no-parent http://example.com/configs/.vim/

To avoid downloading the auto-generated index.html files, use the -R/--reject option:

wget -r -np -R "index.html*" http://example.com/configs/.vim/

How to bind multiple values to a single WPF TextBlock?

You can use a MultiBinding combined with the StringFormat property. Usage would resemble the following:

<TextBlock>
    <TextBlock.Text>    
        <MultiBinding StringFormat="{}{0} + {1}">
            <Binding Path="Name" />
            <Binding Path="ID" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Giving Name a value of Foo and ID a value of 1, your output in the TextBlock would then be Foo + 1.

Note: that this is only supported in .NET 3.5 SP1 and 3.0 SP2 or later.

Getting the count of unique values in a column in bash

The GNU site suggests this nice awk script, which prints both the words and their frequency.

Possible changes:

  • You can pipe through sort -nr (and reverse word and freq[word]) to see the result in descending order.
  • If you want a specific column, you can omit the for loop and simply write freq[3]++ - replace 3 with the column number.

Here goes:

 # wordfreq.awk --- print list of word frequencies

 {
     $0 = tolower($0)    # remove case distinctions
     # remove punctuation
     gsub(/[^[:alnum:]_[:blank:]]/, "", $0)
     for (i = 1; i <= NF; i++)
         freq[$i]++
 }

 END {
     for (word in freq)
         printf "%s\t%d\n", word, freq[word]
 }

How to resolve "Server Error in '/' Application" error?

The error message is quite clear: you have a configuration element in a web.config file in a subfolder of your web app that is not allowed at that level - OR you forgot to configure your web application as IIS application.

Example: you try to override application level settings like forms authentication parameters in a web.config in a subfolder of your application

How to work offline with TFS

plundberg: The "disconnect" button is only available for the TFS provider starting in VS 2008. Even then, I'm not sure if it's officially supported. The recommended way to use the Go Offline feature is to [re]open the solution.

Martin Pritchard: if you get stuck mid-operation, you can force VS to timeout by pulling the network plug (literally) or running ipconfig /release.

Once you're marked offline, here's a step by step guide to working in that mode: http://teamfoundation.blogspot.com/2007/12/offline-and-back-again-in-vs2008.html

More detailed info on tweaking the behind-the-scenes behavior: http://blogs.msdn.com/benryan/archive/2007/12/12/when-and-how-does-my-solution-go-offline.aspx http://blogs.msdn.com/benryan/archive/2007/12/12/how-to-make-tfs-offline-strictly-solution-based.aspx

Does HTML5 <video> playback support the .avi format?

The HTML specification never specifies any content formats. That's not its job. There's plenty of standards organizations that are more qualified than the W3C to specify video formats.

That's what content negotiation is for.

  • The HTML specification doesn't specify any image formats for the <img> element.
  • The HTML specification doesn't specify any style sheet languages for the <style> element.
  • The HTML specification doesn't specify any scripting languages for the <script> element.
  • The HTML specification doesn't specify any object formats for the <object> and embed elements.
  • The HTML specification doesn't specify any audio formats for the <audio> element.

Why should it specify one for the <video> element?

Automatically get loop index in foreach loop in Perl

perldoc perlvar does not seem to suggest any such variable.

Invalid default value for 'create_date' timestamp field

To disable strict SQL mode

Create disable_strict_mode.cnf file at /etc/mysql/conf.d/

In the file, enter these two lines:

[mysqld]
sql_mode=IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Finally, restart MySQL with this command:

sudo service mysql restart

Adding Counter in shell script

You may do this with a for loop instead of a while:

max_loop=20
for ((count = 0; count < max_loop; count++)); do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       break
  else
       echo "Sleeping for half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

if [ "$count" -eq "$max_loop" ]; then
  echo "Maximum number of trials reached" >&2
  exit 1
fi

Reading Excel file using node.js

Useful link

https://ciphertrick.com/read-excel-files-convert-json-node-js/

 var express = require('express'); 
    var app = express(); 
    var bodyParser = require('body-parser');
    var multer = require('multer');
    var xlstojson = require("xls-to-json-lc");
    var xlsxtojson = require("xlsx-to-json-lc");
    app.use(bodyParser.json());
    var storage = multer.diskStorage({ //multers disk storage settings
        destination: function (req, file, cb) {
            cb(null, './uploads/')
        },
        filename: function (req, file, cb) {
            var datetimestamp = Date.now();
            cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
        }
    });
    var upload = multer({ //multer settings
                    storage: storage,
                    fileFilter : function(req, file, callback) { //file filter
                        if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
                            return callback(new Error('Wrong extension type'));
                        }
                        callback(null, true);
                    }
                }).single('file');
    /** API path that will upload the files */
    app.post('/upload', function(req, res) {
        var exceltojson;
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
            /** Multer gives us file info in req.file object */
            if(!req.file){
                res.json({error_code:1,err_desc:"No file passed"});
                return;
            }
            /** Check the extension of the incoming file and 
             *  use the appropriate module
             */
            if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
                exceltojson = xlsxtojson;
            } else {
                exceltojson = xlstojson;
            }
            try {
                exceltojson({
                    input: req.file.path,
                    output: null, //since we don't need output.json
                    lowerCaseHeaders:true
                }, function(err,result){
                    if(err) {
                        return res.json({error_code:1,err_desc:err, data: null});
                    } 
                    res.json({error_code:0,err_desc:null, data: result});
                });
            } catch (e){
                res.json({error_code:1,err_desc:"Corupted excel file"});
            }
        })
    }); 
    app.get('/',function(req,res){
        res.sendFile(__dirname + "/index.html");
    });
    app.listen('3000', function(){
        console.log('running on 3000...');
    });

Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista

Output on Windows 10

Fonts: C:\Windows\Fonts
CommonStartMenu: C:\ProgramData\Microsoft\Windows\Start Menu
CommonPrograms: C:\ProgramData\Microsoft\Windows\Start Menu\Programs
CommonStartup: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
CommonDesktopDirectory: C:\Users\Public\Desktop
CommonApplicationData: C:\ProgramData
Windows: C:\Windows
System: C:\Windows\system32
ProgramFiles: C:\Program Files (x86)
SystemX86: C:\Windows\SysWOW64
ProgramFilesX86: C:\Program Files (x86)
CommonProgramFiles: C:\Program Files (x86)\Common Files
CommonProgramFilesX86: C:\Program Files (x86)\Common Files
CommonTemplates: C:\ProgramData\Microsoft\Windows\Templates
CommonDocuments: C:\Users\Public\Documents
CommonAdminTools: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools
CommonMusic: C:\Users\Public\Music
CommonPictures: C:\Users\Public\Pictures
CommonVideos: C:\Users\Public\Videos
Resources: C:\Windows\resources
LocalizedResources:
CommonOemLinks:

Code Snippet if you want to log your own

foreach(Environment.SpecialFolder f in Enum.GetValues(typeof(Environment.SpecialFolder)))
{
    string commonAppData = Environment.GetFolderPath(f);
    Console.WriteLine("{0}: {1}", f, commonAppData);
}
Console.ReadLine();

Failed to install Python Cryptography package with PIP and setup.py

For those of you running OS X, here is what worked for me:

brew install openssl
env ARCHFLAGS="-arch x86_64" LDFLAGS="-L/usr/local/opt/openssl/lib" CFLAGS="-I/usr/local/opt/openssl/include"
pip install cryptography

(Running 10.9 Mavericks)

You may also want to try merging the flags and pip commands to the following per the comment below:

brew install openssl
env ARCHFLAGS="-arch x86_64" LDFLAGS="-L/usr/local/opt/openssl/lib" CFLAGS="-I/usr/local/opt/openssl/include" pip install cryptography

Html5 Full screen video

    if (vi_video[0].exitFullScreen) vi_video[0].exitFullScreen();
    else if (vi_video[0].webkitExitFullScreen) vi_video[0].webkitExitFullScreen();
    else if (vi_video[0].mozExitFullScreen) vi_video[0].mozExitFullScreen();
    else if (vi_video[0].oExitFullScreen) vi_video[0].oExitFullScreen();
    else if (vi_video[0].msExitFullScreen) vi_video[0].msExitFullScreen();
    else { vi_video.parent().append(vi_video.remove()); }

Centering floating divs within another div

First, remove the float attribute on the inner divs. Then, put text-align: center on the main outer div. And for the inner divs, use display: inline-block. Might also be wise to give them explicit widths too.


<div style="margin: auto 1.5em; display: inline-block;">
  <img title="Nadia Bjorlin" alt="Nadia Bjorlin" src="headshot.nadia.png"/>
  <br/>
  Nadia Bjorlin
</div>

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

this helped me

git checkout -b newbranch
git checkout master
git merge newbranch
git branch -d newbranch

Select entries between dates in doctrine 2

Look how I format my date $jour in the parameters. It depends if you use a expr()->like or a expr()->lte

$qb
        ->select('e')
        ->from('LdbPlanningBundle:EventEntity', 'e')
        ->where(
            $qb->expr()->andX(
                $qb->expr()->orX(
                    $qb->expr()->like('e.start', ':jour1'),
                    $qb->expr()->like('e.end', ':jour1'),
                    $qb->expr()->andX(
                        $qb->expr()->lte('e.start', ':jour2'),
                        $qb->expr()->gte('e.end', ':jour2')
                    )
                ),
                $qb->expr()->eq('e.user', ':user')
            )
        )
        ->andWhere('e.user = :user ')
        ->setParameter('user', $user)
        ->setParameter('jour1', '%'.$jour->format('Y-m-d').'%')
        ->setParameter('jour2', $jour->format('Y-m-d'))
        ->getQuery()
        ->getArrayResult()
    ;

What is the runtime performance cost of a Docker container?

An excellent 2014 IBM research paper “An Updated Performance Comparison of Virtual Machines and Linux Containers” by Felter et al. provides a comparison between bare metal, KVM, and Docker containers. The general result is: Docker is nearly identical to native performance and faster than KVM in every category.

The exception to this is Docker’s NAT — if you use port mapping (e.g., docker run -p 8080:8080), then you can expect a minor hit in latency, as shown below. However, you can now use the host network stack (e.g., docker run --net=host) when launching a Docker container, which will perform identically to the Native column (as shown in the Redis latency results lower down).

Docker NAT overhead

They also ran latency tests on a few specific services, such as Redis. You can see that above 20 client threads, highest latency overhead goes Docker NAT, then KVM, then a rough tie between Docker host/native.

Docker Redis Latency Overhead

Just because it’s a really useful paper, here are some other figures. Please download it for full access.

Taking a look at Disk I/O:

Docker vs. KVM vs. Native I/O Performance

Now looking at CPU overhead:

Docker CPU Overhead

Now some examples of memory (read the paper for details, memory can be extra tricky):

Docker Memory Comparison

Breaking a list into multiple columns in Latex

I've had multenum for "Multi-column enumerated lists" recommended to me, but I've never actually used it myself, yet.

Edit: The syntax doesn't exactly look like you could easily copy+paste lists into the LaTeX code. So, it may not be the best solution for your use case!

Excel - Sum column if condition is met by checking other column in same table

SUMIF didn't worked for me, had to use SUMIFS.

=SUMIFS(TableAmount,TableMonth,"January")

TableAmount is the table to sum the values, TableMonth the table where we search the condition and January, of course, the condition to meet.

Hope this can help someone!

How do I update a Linq to SQL dbml file?

Here is the complete step-by-step method that worked for me in order to update the LINQ to SQL dbml and associated files to include a new column that I added to one of the database tables.

You need to make the changes to your design surface as suggested by other above; however, you need to do some extra steps. These are the complete steps:

  1. Drag your updated table from Server Explorer onto the design surface

  2. Copy the new column from this "new" table to the "old" table (see M463 answer for details on this step)

  3. Delete the "new" table that you just dragged over

  4. Click and highlight the stored procedure, then delete it

  5. Drag the new stored procedure and drop into place.

  6. Delete the .designer.vb file in the code-behind of the .dbml (if you do not delete this, your code-behind containing the schema will not update even if you rebuild and the new table field will not be included)

  7. Clean and Rebuild the solution (this will rebuild the .designer.vb file to include all the new changes!).

How to generate access token using refresh token through google drive API?

If you are using web api then you should make a http POST call to URL : https://www.googleapis.com/oauth2/v4/token with following request body

client_id: <YOUR_CLIENT_ID>
client_secret: <YOUR_CLIENT_SECRET>
refresh_token: <REFRESH_TOKEN_FOR_THE_USER>
grant_type: refresh_token

refresh token never expires so you can use it any number of times. The response will be a JSON like this:

{
  "access_token": "your refreshed access token",
  "expires_in": 3599,
  "scope": "Set of scope which you have given",
  "token_type": "Bearer"
}

HTML 5 Video "autoplay" not automatically starting in CHROME

Try this when i tried giving muted , check this demo in codpen

    <video width="320" height="240" controls autoplay muted id="videoId">
  <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>

script

function toggleMute() {

  var video=document.getElementById("videoId");

  if(video.muted){
    video.muted = false;
  } else {
    debugger;
    video.muted = true;
    video.play()
  }

}

$(document).ready(function(){
  setTimeout(toggleMute,3000);
})

edited attribute content

autoplay muted playsinline

https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

How may I reference the script tag that loaded the currently-executing script?

An approach for dealing with async & deferred scripts is to leverage the onload handler- set an onload handler for all script tags and the first one which executes should be yours.

function getCurrentScript(callback) {
  if (document.currentScript) {
    callback(document.currentScript);
    return;
  }
  var scripts = document.scripts;
  function onLoad() {
    for (var i = 0; i < scripts.length; ++i) {
      scripts[i].removeEventListener('load', onLoad, false);
    }
    callback(event.target);
  }
  for (var i = 0; i < scripts.length; ++i) {
    scripts[i].addEventListener('load', onLoad, false);
  }
}

getCurrentScript(function(currentScript) {
  window.console.log(currentScript.src);
});

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

You want to convert mdb to mysql (direct transfer to mysql or mysql dump)?

Try a software called Access to MySQL.

Access to MySQL is a small program that will convert Microsoft Access Databases to MySQL.

  • Wizard interface.
  • Transfer data directly from one server to another.
  • Create a dump file.
  • Select tables to transfer.
  • Select fields to transfer.
  • Transfer password protected databases.
  • Supports both shared security and user-level security.
  • Optional transfer of indexes.
  • Optional transfer of records.
  • Optional transfer of default values in field definitions.
  • Identifies and transfers auto number field types.
  • Command line interface.
  • Easy install, uninstall and upgrade.

See the aforementioned link for a step-by-step tutorial with screenshots.

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

We face this issue but had different reason, here is the reason:

In our project found multiple bean entry with same bean name. 1 in applicationcontext.xml & 1 in dispatcherServlet.xml

Example:

<bean name="dataService" class="com.app.DataServiceImpl">
<bean name="dataService" class="com.app.DataServiceController">

& we are trying to autowired by dataService name.

Solution: we changed the bean name & its solved.

Implement touch using Python?

For a more low-level solution one can use

os.close(os.open("file.txt", os.O_CREAT))

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

For .NET CORE 3.1

I was using https redirection just before adding cors middleware and able to fix the issue by changing order of them

What i mean is:

change this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

      ...
        
        app.UseHttpsRedirection();  

        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

      ...

     }

to this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

      ...
        
        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

        app.UseHttpsRedirection(); 

      ...

     }

By the way, allowing requests from any origins and methods may not be a good idea for production stage, you should write your own cors policies at production.

How do I "break" out of an if statement?

You can't break break out of an if statement, unless you use goto.

if (true)
{
      int var = 0;
      var++;
      if (var == 1)
          goto finished;
      var++;
}

finished:
printf("var = %d\n", var);

This would give "var = 1" as output

How to check if Location Services are enabled?

You may use this code to direct users to Settings, where they can enable GPS:

    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    if( !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ) {
        new AlertDialog.Builder(context)
            .setTitle(R.string.gps_not_found_title)  // GPS not found
            .setMessage(R.string.gps_not_found_message) // Want to enable?
            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {
                    owner.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton(R.string.no, null)
            .show();
    }

how to convert string to numerical values in mongodb

Here is a pure MongoDB based solution for this problem which I just wrote for fun. It's effectively a server-side string-to-number parser which supports positive and negative numbers as well as decimals:

db.collection.aggregate({
    $addFields: {
        "moop": {
            $reduce: {
                "input": {
                    $map: { // split string into char array so we can loop over individual characters
                        "input": {
                            $range: [ 0, { $strLenCP: "$moop" } ] // using an array of all numbers from 0 to the length of the string
                        },
                        "in":{
                            $substrCP: [ "$moop", "$$this", 1 ] // return the nth character as the mapped value for the current index
                        }
                    }
                },
                "initialValue": { // initialize the parser with a 0 value
                    "n": 0, // the current number
                    "sign": 1, // used for positive/negative numbers
                    "div": null, // used for shifting on the right side of the decimal separator "."
                    "mult": 10 // used for shifting on the left side of the decimal separator "."
                }, // start with a zero
                "in": {
                    $let: {
                        "vars": {
                            "n": {
                                $switch: { // char-to-number mapping
                                    branches: [
                                        { "case": { $eq: [ "$$this", "1" ] }, "then": 1 },
                                        { "case": { $eq: [ "$$this", "2" ] }, "then": 2 },
                                        { "case": { $eq: [ "$$this", "3" ] }, "then": 3 },
                                        { "case": { $eq: [ "$$this", "4" ] }, "then": 4 },
                                        { "case": { $eq: [ "$$this", "5" ] }, "then": 5 },
                                        { "case": { $eq: [ "$$this", "6" ] }, "then": 6 },
                                        { "case": { $eq: [ "$$this", "7" ] }, "then": 7 },
                                        { "case": { $eq: [ "$$this", "8" ] }, "then": 8 },
                                        { "case": { $eq: [ "$$this", "9" ] }, "then": 9 },
                                        { "case": { $eq: [ "$$this", "0" ] }, "then": 0 },
                                        { "case": { $and: [ { $eq: [ "$$this", "-" ] }, { $eq: [ "$$value.n", 0 ] } ] }, "then": "-" }, // we allow a minus sign at the start
                                        { "case": { $eq: [ "$$this", "." ] }, "then": "." }
                                    ],
                                    default: null // marker to skip the current character
                                } 
                            }
                        },
                        "in": {
                            $switch: {
                                "branches": [
                                    {
                                        "case": { $eq: [ "$$n", "-" ] },
                                        "then": { // handle negative numbers
                                            "sign": -1, // set sign to -1, the rest stays untouched
                                            "n": "$$value.n",
                                            "div": "$$value.div",
                                            "mult": "$$value.mult",
                                        },
                                    },
                                    {
                                        "case": { $eq: [ "$$n", null ] }, // null is the "ignore this character" marker
                                        "then": "$$value" // no change to current value
                                    }, 
                                    {
                                        "case": { $eq: [ "$$n", "." ] },
                                        "then": { // handle decimals
                                            "n": "$$value.n",
                                            "sign": "$$value.sign",
                                            "div": 10, // from the decimal separator "." onwards, we start dividing new numbers by some divisor which starts at 10 initially
                                            "mult": 1, // and we stop multiplying the current value by ten
                                        },
                                    }, 
                                ],
                                "default": {
                                    "n": {
                                        $add: [
                                            { $multiply: [ "$$value.n", "$$value.mult" ] }, // multiply the already parsed number by 10 because we're moving one step to the right or by one once we're hitting the decimals section
                                            { $divide: [ "$$n", { $ifNull: [ "$$value.div", 1 ] } ] } // add the respective numerical value of what we look at currently, potentially divided by a divisor
                                        ]
                                    },
                                    "sign": "$$value.sign",
                                    "div": { $multiply: [ "$$value.div" , 10 ] },
                                    "mult": "$$value.mult"
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}, {
    $addFields: { // fix sign
        "moop": { $multiply: [ "$moop.n", "$moop.sign" ] }
    }
})

I am certainly not advertising this as the bee's knees or anything and it might have severe performance implications for larger datasets over a client based solutions but there might be cases where it comes in handy...

The above pipeline will transform the following documents:

{ "moop": "12345" } --> { "moop": 12345 }

and

{ "moop": "123.45" } --> { "moop": 123.45 }

and

{ "moop": "-123.45" } --> { "moop": -123.45 }

and

{ "moop": "2018-01-03" } --> { "moop": 20180103.0 }

SQL: capitalize first letter only

select replace(wm_concat(new),',','-') exp_res from (select distinct initcap(substr(name,decode(level,1,1,instr(name,'-',1,level-1)+1),decode(level,(length(name)-length(replace(name,'-','')))+1,9999,instr(name,'-',1,level)-1-decode(level,1,0,instr(name,'-',1,level-1))))) new from table;
connect by level<= (select (length(name)-length(replace(name,'-','')))+1 from table));

How to Set Focus on JTextField?

In my case nothing above worked untill I called requestFocus() AFTER my constructor has returned.

MyPanel panel = new MyPanel(...);
frame.add(panel);
panel.initFocus();

MyPanel.initFocus() would have:

myTextField.requestFocus();

And it works.

Getting XML Node text value with Java DOM

If you are open to vtd-xml, which excels at both performance and memory efficiency, below is the code to do what you are looking for...in both XPath and manual navigation... the overall code is much concise and easier to understand ...

import com.ximpleware.*;
public class queryText {
    public static void main(String[] s) throws VTDException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", true))
            return;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        // first manually navigate
        if(vn.toElement(VTDNav.FC,"tag")){
            int i= vn.getText();
            if (i!=-1){
                System.out.println("text ===>"+vn.toString(i));
            }
            if (vn.toElement(VTDNav.NS,"tag")){
                i=vn.getText();
                System.out.println("text ===>"+vn.toString(i));
            }
        }

        // second version use XPath
        ap.selectXPath("/add/tag/text()");
        int i=0;
        while((i=ap.evalXPath())!= -1){
            System.out.println("text node ====>"+vn.toString(i));
        }
    }
}

How to convert Json array to list of objects in c#

This is possible too:

using System.Web.Helpers;
var listOfObjectsResult = Json.Decode<List<DataType>>(JsonData);

How do I set a column value to NULL in SQL Server Management Studio?

CTRL+0 doesn't seem to work when connected to an Azure DB.

However, to create an empty string, you can always just hit 'anykey then delete' inside a cell.

Changing Locale within the app itself

In Android M the top solution won't work. I've written a helper class to fix that which you should call from your Application class and all Activities (I would suggest creating a BaseActivity and then make all the Activities inherit from it.

Note: This will also support properly RTL layout direction.

Helper class:

public class LocaleUtils {

    private static Locale sLocale;

    public static void setLocale(Locale locale) {
        sLocale = locale;
        if(sLocale != null) {
            Locale.setDefault(sLocale);
        }
    }

    public static void updateConfig(ContextThemeWrapper wrapper) {
        if(sLocale != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Configuration configuration = new Configuration();
            configuration.setLocale(sLocale);
            wrapper.applyOverrideConfiguration(configuration);
        }
    }

    public static void updateConfig(Application app, Configuration configuration) {
        if (sLocale != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
            //Wrapping the configuration to avoid Activity endless loop
            Configuration config = new Configuration(configuration);
            // We must use the now-deprecated config.locale and res.updateConfiguration here,
            // because the replacements aren't available till API level 24 and 17 respectively.
            config.locale = sLocale;
            Resources res = app.getBaseContext().getResources();
            res.updateConfiguration(config, res.getDisplayMetrics());
        }
    }
}

Application:

public class App extends Application {
    public void onCreate(){
        super.onCreate();

        LocaleUtils.setLocale(new Locale("iw"));
        LocaleUtils.updateConfig(this, getBaseContext().getResources().getConfiguration());
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        LocaleUtils.updateConfig(this, newConfig);
    }
}

BaseActivity:

public class BaseActivity extends Activity {
    public BaseActivity() {
        LocaleUtils.updateConfig(this);
    }
}

Using Chrome, how to find to which events are bound to an element

(Latest as of 2020) For version Chrome Version 83.0.4103.61 :

Chrome Developer Tools - Event Listener

  1. Select the element you want to inspect

  2. Choose the Event Listeners tab

  3. Make sure to check the Framework listeners to show the real javascript file instead of the jquery function.

Creating stored procedure and SQLite?

SQLite has had to sacrifice other characteristics that some people find useful, such as high concurrency, fine-grained access control, a rich set of built-in functions, stored procedures, esoteric SQL language features, XML and/or Java extensions, tera- or peta-byte scalability, and so forth

Source : Appropriate Uses For SQLite

What is the Python equivalent of Matlab's tic and toc functions?

I have just created a module [tictoc.py] for achieving nested tic tocs, which is what Matlab does.

from time import time

tics = []

def tic():
    tics.append(time())

def toc():
    if len(tics)==0:
        return None
    else:
        return time()-tics.pop()

And it works this way:

from tictoc import tic, toc

# This keeps track of the whole process
tic()

# Timing a small portion of code (maybe a loop)
tic()

# -- Nested code here --

# End
toc()  # This returns the elapse time (in seconds) since the last invocation of tic()
toc()  # This does the same for the first tic()

I hope it helps.

How to add subject alernative name to ssl certs?

When generating CSR is possible to specify -ext attribute again to have it inserted in the CSR

keytool -certreq -file test.csr -keystore test.jks -alias testAlias -ext SAN=dns:test.example.com

complete example here: How to create CSR with SANs using keytool

How to debug PDO database queries?

You say this :

I never see the final query as it's sent to the database

Well, actually, when using prepared statements, there is no such thing as a "final query" :

  • First, a statement is sent to the DB, and prepared there
    • The database parses the query, and builds an internal representation of it
  • And, when you bind variables and execute the statement, only the variables are sent to the database
    • And the database "injects" the values into its internal representation of the statement


So, to answer your question :

Is there a way capture the complete SQL query sent by PDO to the database and log it to a file?

No : as there is no "complete SQL query" anywhere, there is no way to capture it.


The best thing you can do, for debugging purposes, is "re-construct" an "real" SQL query, by injecting the values into the SQL string of the statement.

What I usually do, in this kind of situations, is :

  • echo the SQL code that corresponds to the statement, with placeholders
  • and use var_dump (or an equivalent) just after, to display the values of the parameters
  • This is generally enough to see a possible error, even if you don't have any "real" query that you can execute.

This is not great, when it comes to debugging -- but that's the price of prepared statements and the advantages they bring.

Flutter - Wrap text on overflow, like insert ellipsis or fade

Wrap the Container with Expanded()

Expanded (child: Container(
                  padding: new EdgeInsets.only(right: 24.0),
                  child: new CircleAvatar(
                    backgroundColor: new Color(0xFFF5F5F5),
                    radius: 16.0,
                  )
                ),
                new Container(
                  padding: new EdgeInsets.only(right: 13.0),
                  child: new Text(
                    'Text lar...',
                    overflow: TextOverflow.ellipsis,
                    style: new TextStyle(
                      fontSize: 13.0,
                      fontFamily: 'Roboto',
                      color: new Color(0xFF212121),
                      fontWeight: FontWeight.bold,
                    ),
                  ),
),

How to check whether a file is empty or not?

If you are using Python3 with pathlib you can access os.stat() information using the Path.stat() method, which has the attribute st_size(file size in bytes):

>>> from pathlib import Path 
>>> mypath = Path("path/to/my/file")
>>> mypath.stat().st_size == 0 # True if empty

Converting between strings and ArrayBuffers

Although Dennis and gengkev solutions of using Blob/FileReader work, I wouldn't suggest taking that approach. It is an async approach to a simple problem, and it is much slower than a direct solution. I've made a post in html5rocks with a simpler and (much faster) solution: http://updates.html5rocks.com/2012/06/How-to-convert-ArrayBuffer-to-and-from-String

And the solution is:

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}

function str2ab(str) {
  var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
  var bufView = new Uint16Array(buf);
  for (var i=0, strLen=str.length; i<strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

EDIT:

The Encoding API helps solving the string conversion problem. Check out the response from Jeff Posnik on Html5Rocks.com to the above original article.

Excerpt:

The Encoding API makes it simple to translate between raw bytes and native JavaScript strings, regardless of which of the many standard encodings you need to work with.

<pre id="results"></pre>

<script>
  if ('TextDecoder' in window) {
    // The local files to be fetched, mapped to the encoding that they're using.
    var filesToEncoding = {
      'utf8.bin': 'utf-8',
      'utf16le.bin': 'utf-16le',
      'macintosh.bin': 'macintosh'
    };

    Object.keys(filesToEncoding).forEach(function(file) {
      fetchAndDecode(file, filesToEncoding[file]);
    });
  } else {
    document.querySelector('#results').textContent = 'Your browser does not support the Encoding API.'
  }

  // Use XHR to fetch `file` and interpret its contents as being encoded with `encoding`.
  function fetchAndDecode(file, encoding) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file);
    // Using 'arraybuffer' as the responseType ensures that the raw data is returned,
    // rather than letting XMLHttpRequest decode the data first.
    xhr.responseType = 'arraybuffer';
    xhr.onload = function() {
      if (this.status == 200) {
        // The decode() method takes a DataView as a parameter, which is a wrapper on top of the ArrayBuffer.
        var dataView = new DataView(this.response);
        // The TextDecoder interface is documented at http://encoding.spec.whatwg.org/#interface-textdecoder
        var decoder = new TextDecoder(encoding);
        var decodedString = decoder.decode(dataView);
        // Add the decoded file's text to the <pre> element on the page.
        document.querySelector('#results').textContent += decodedString + '\n';
      } else {
        console.error('Error while requesting', file, this);
      }
    };
    xhr.send();
  }
</script>

Refresh certain row of UITableView based on Int in Swift

Swift 4.1

use it when you delete row using selectedTag of row.

self.tableView.beginUpdates()

        self.yourArray.remove(at:  self.selectedTag)
        print(self.allGroups)

        let indexPath = NSIndexPath.init(row:  self.selectedTag, section: 0)

        self.tableView.deleteRows(at: [indexPath as IndexPath], with: .automatic)

        self.tableView.endUpdates()

        self.tableView.reloadRows(at: self.tableView.indexPathsForVisibleRows!, with: .automatic)

How to check if another instance of my shell script is running

Here's how I do it in a bash script:

if ps ax | grep $0 | grep -v $$ | grep bash | grep -v grep
then
    echo "The script is already running."
    exit 1
fi

This allows me to use this snippet for any bash script. I needed to grep bash because when using with cron, it creates another process that executes it using /bin/sh.

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

Since the question asked for either jQuery or vanilla JS, here's an answer with vanilla JS.

I've added some CSS to the demo below to change the button's font color to red when its aria-expanded is set to true

_x000D_
_x000D_
const button = document.querySelector('button');_x000D_
_x000D_
button.addEventListener('click', () => {_x000D_
  button.ariaExpanded = !JSON.parse(button.ariaExpanded);_x000D_
})
_x000D_
button[aria-expanded="true"] {_x000D_
  color: red;_x000D_
}
_x000D_
<button type="button" aria-expanded="false">Click me!</button>
_x000D_
_x000D_
_x000D_

ThreeJS: Remove object from scene

clearScene: function() {
    var objsToRemove = _.rest(scene.children, 1);
    _.each(objsToRemove, function( object ) {
          scene.remove(object);
    });
},

this uses undescore.js to iterrate over all children (except the first) in a scene (it's part of code I use to clear a scene). just make sure you render the scene at least once after deleting, because otherwise the canvas does not change! There is no need for a "special" obj flag or anything like this.

Also you don't delete the object by name, just by the object itself, so calling

scene.remove(object); 

instead of scene.remove(object.name); can be enough

PS: _.each is a function of underscore.js

Best way to center a <div> on a page vertically and horizontally?

Using display:grid on parent and setting margin:auto to the centrerd elemnt will do the trick :

See below snippet :

_x000D_
_x000D_
html,body {_x000D_
  width :100%;_x000D_
  height:100%;_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  display:grid;_x000D_
  height:90%;_x000D_
  background-color:blue;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  margin:auto;_x000D_
  color:white;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="content"> cented div  here</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Need to perform Wildcard (*,?, etc) search on a string using Regex

All upper code is not correct to the end.

This is because when searching zz*foo* or zz* you will not get correct results.

And if you search "abcd*" in "abcd" in TotalCommander will he find a abcd file so all upper code is wrong.

Here is the correct code.

public string WildcardToRegex(string pattern)
{             
    string result= Regex.Escape(pattern).
        Replace(@"\*", ".+?").
        Replace(@"\?", "."); 

    if (result.EndsWith(".+?"))
    {
        result = result.Remove(result.Length - 3, 3);
        result += ".*";
    }

    return result;
}

PostgreSQL: Drop PostgreSQL database through command line

This worked for me:

select pg_terminate_backend(pid) from pg_stat_activity where datname='YourDatabase';

for postgresql earlier than 9.2 replace pid with procpid

DROP DATABASE "YourDatabase";

http://blog.gahooa.com/2010/11/03/how-to-force-drop-a-postgresql-database-by-killing-off-connection-processes/

Substring in excel

What about using Replace all? Just replace All on bracket to space. And comma to space. And I think you can achieve it.

Tools: replace not replacing in Android manifest

I was receiving a similar error on a project I was importing:

Multiple entries with same key: android:icon=REPLACE and tools:icon=REPLACE

Fixed after changing the below line within the application tag:

tools:replace="icon, label, theme"

to

tools:replace="android:icon, android:label, android:theme"

How to add SHA-1 to android application

Open a terminal and run the keytool utility provided with Java to get the SHA-1 fingerprint of the certificate. You should get both the release and debug certificate fingerprints.

To get the release certificate fingerprint: keytool -exportcert -list -v \ -alias -keystore

Sleeping in a batch file

Even more lightweight than the Python solution is a Perl one-liner.

To sleep for seven seconds put this in the BAT script:

perl -e "sleep 7"

This solution only provides a resolution of one second.

If you need higher resolution then use the Time::HiRes module from CPAN. It provides usleep() which sleeps in microseconds and nanosleep() which sleeps in nanoseconds (both functions takes only integer arguments). See the Stack Overflow question How do I sleep for a millisecond in Perl? for further details.

I have used ActivePerl for many years. It is very easy to install.

What is difference between cacerts and keystore?

'cacerts' is a truststore. A trust store is used to authenticate peers. A keystore is used to authenticate yourself.

How to trim white space from all elements in array?

String val = "hi hello prince";
String arr[] = val.split(" ");

for (int i = 0; i < arr.length; i++)
{   
     System.out.print(arr[i]);
}

How do I get the HTTP status code with jQuery?

The third argument is the XMLHttpRequest object, so you can do whatever you want.

$.ajax({
  url  : 'http://example.com',
  type : 'post',
  data : 'a=b'
}).done(function(data, statusText, xhr){
  var status = xhr.status;                //200
  var head = xhr.getAllResponseHeaders(); //Detail header info
});

How do I get the old value of a changed cell in Excel VBA?

I had to do it too. I found the solution from "Chris R" really good, but thought it could be more compatible in not adding any references. Chris, you talked about using Collection. So here is another solution using Collection. And it's not that slow, in my case. Also, with this solution, in adding the event "_SelectionChange", it's always working (no need of workbook_open).

Dim OldValues As New Collection

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    'Copy old values
    Set OldValues = Nothing
    Dim c As Range
    For Each c In Target
        OldValues.Add c.Value, c.Address
    Next c
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    On Local Error Resume Next  ' To avoid error if the old value of the cell address you're looking for has not been copied
    Dim c As Range
    For Each c In Target
        Debug.Print "New value of " & c.Address & " is " & c.Value & "; old value was " & OldValues(c.Address)
    Next c
    'Copy old values (in case you made any changes in previous lines of code)
    Set OldValues = Nothing
    For Each c In Target
        OldValues.Add c.Value, c.Address
    Next c
End Sub

SQL Server Regular expressions in T-SQL

There is some basic pattern matching available through using LIKE, where % matches any number and combination of characters, _ matches any one character, and [abc] could match a, b, or c... There is more info on the MSDN site.

SyntaxError: unexpected EOF while parsing

Maybe this is what you mean to do:

import random

x = 0
z = input('Please Enter an integer: ')
z = int(z) # you need to capture the result of the expressioin: int(z) and assign it backk to z

def main():
    for i in range(x,z):
        n1 = random.randrange(1,3)
        n2 = random.randrange(1,3)
        t1 = n1+n2
        print('{0}+{1}={2}'.format(n1,n2,t1))

main()
  1. do z = int(z)
  2. Add the missing closing parenthesis on the last line of code in your listing.
  3. And have a for-loop that will iterate from x to z-1

Here's a link on the range() function: http://docs.python.org/release/1.5.1p1/tut/range.html

Newline in markdown table?

Use <br/> . For example:

Change log, upgrade version

Dependency | Old version | New version |
---------- | ----------- | -----------
Spring Boot | `1.3.5.RELEASE` | `1.4.3.RELEASE`
Gradle | `2.13` | `3.2.1`
Gradle plugin <br/>`com.gorylenko.gradle-git-properties` | `1.4.16` | `1.4.17`
`org.webjars:requirejs` | `2.2.0` | `2.3.2`
`org.webjars.npm:stompjs` | `2.3.3` | `2.3.3`
`org.webjars.bower:sockjs-client` | `1.1.0` | `1.1.1`

URL: https://github.com/donhuvy/lsb/wiki

How can I decode HTML characters in C#?

It is also worth mentioning that if you're using HtmlAgilityPack like I was, you should use HtmlAgilityPack.HtmlEntity.DeEntitize(). It takes a string and returns a string.