Programs & Examples On #Splistitem

Making a request to a RESTful API using python

So you want to pass data in body of a GET request, better would be to do it in POST call. You can achieve this by using both Requests.

Raw Request

GET http://ES_search_demo.com/document/record/_search?pretty=true HTTP/1.1
Host: ES_search_demo.com
Content-Length: 183
User-Agent: python-requests/2.9.0
Connection: keep-alive
Accept: */*
Accept-Encoding: gzip, deflate

{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}

Sample call with Requests

import requests

def consumeGETRequestSync():
data = '{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}'
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
headers = {"Accept": "application/json"}
# call get service with headers and params
response = requests.get(url,data = data)
print "code:"+ str(response.status_code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "content:"+ str(response.text)

consumeGETRequestSync()

PostgreSQL delete all content

The content of the table/tables in PostgreSQL database can be deleted in several ways.

Deleting table content using sql:

Deleting content of one table:

TRUNCATE table_name;
DELETE FROM table_name;

Deleting content of all named tables:

TRUNCATE table_a, table_b, …, table_z;

Deleting content of named tables and tables that reference to them (I will explain it in more details later in this answer):

TRUNCATE table_a, table_b CASCADE;

Deleting table content using pgAdmin:

Deleting content of one table:

Right click on the table -> Truncate

Deleting content of table and tables that reference to it:

Right click on the table -> Truncate Cascaded

Difference between delete and truncate:

From the documentation:

DELETE deletes rows that satisfy the WHERE clause from the specified table. If the WHERE clause is absent, the effect is to delete all rows in the table. http://www.postgresql.org/docs/9.3/static/sql-delete.html

TRUNCATE is a PostgreSQL extension that provides a faster mechanism to remove all rows from a table. TRUNCATE quickly removes all rows from a set of tables. It has the same effect as an unqualified DELETE on each table, but since it does not actually scan the tables it is faster. Furthermore, it reclaims disk space immediately, rather than requiring a subsequent VACUUM operation. This is most useful on large tables. http://www.postgresql.org/docs/9.1/static/sql-truncate.html

Working with table that is referenced from other table:

When you have database that has more than one table the tables have probably relationship. As an example there are three tables:

create table customers (
customer_id int not null,
name varchar(20),
surname varchar(30),
constraint pk_customer primary key (customer_id)
);

create table orders (
order_id int not null,
number int not null,
customer_id int not null,
constraint pk_order primary key (order_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);

create table loyalty_cards (
card_id int not null,
card_number varchar(10) not null,
customer_id int not null,
constraint pk_card primary key (card_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);

And some prepared data for these tables:

insert into customers values (1, 'John', 'Smith');

insert into orders values 
(10, 1000, 1),
(11, 1009, 1),
(12, 1010, 1);        

insert into loyalty_cards values (100, 'A123456789', 1);

Table orders references table customers and table loyalty_cards references table customers. When you try to TRUNCATE / DELETE FROM the table that is referenced by other table/s (the other table/s has foreign key constraint to the named table) you get an error. To delete content from all three tables you have to name all these tables (the order is not important)

TRUNCATE customers, loyalty_cards, orders;

or just the table that is referenced with CASCADE key word (you can name more tables than just one)

TRUNCATE customers CASCADE;

The same applies for pgAdmin. Right click on customers table and choose Truncate Cascaded.

Manually Triggering Form Validation using jQuery

You can't trigger the native validation UI (see edit below), but you can easily take advantage of the validation API on arbitrary input elements:

$('input').blur(function(event) {
    event.target.checkValidity();
}).bind('invalid', function(event) {
    setTimeout(function() { $(event.target).focus();}, 50);
});

The first event fires checkValidity on every input element as soon as it loses focus, if the element is invalid then the corresponding event will be fired and trapped by the second event handler. This one sets the focus back to the element, but that could be quite annoying, I assume you have a better solution for notifying about the errors. Here's a working example of my code above.

EDIT: All modern browsers support the reportValidity() method for native HTML5 validation, per this answer.

Javascript - How to extract filename from a file input control

I assume you want to strip all extensions, i.e. /tmp/test/somefile.tar.gz to somefile.

Direct approach with regex:

var filename = filepath.match(/^.*?([^\\/.]*)[^\\/]*$/)[1];

Alternative approach with regex and array operation:

var filename = filepath.split(/[\\/]/g).pop().split('.')[0];

Command line to remove an environment variable from the OS level configuration

I agree with CupawnTae.

SET is not useful for changes to the master environment.

FYI: System variables are in HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment (a good deal longer than user vars).

The full command for a system var named FOOBAR therefore is:

REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR

(Note the quotes required to handle the space.)

It is too bad the setx command doesn't support a delete syntax. :(

PS: Use responsibly - If you kill your path variable, don't blame me!

Set element width or height in Standards Mode

The style property lets you specify values for CSS properties.

The CSS width property takes a length as its value.

Lengths require units. In quirks mode, browsers tend to assume pixels if provided with an integer instead of a length. Specify units.

e1.style.width = "400px";

Visual Studio Copy Project

Just create a template;

From your project choose: Project - Export Template

The wizard will let you define

  • Template name
  • Template Description
  • Icon
  • Preview image

Then it zips up your project into 'My Exported Templates' directory. You also have the option to make your template available when you create a new project.

When you use your template to create a new project, the namespace will be correct for 'your_new_project_name' throughout every file, all references correct, everything perfecto :)

You can send the .zip file to anybody, and they must copy (not unzip) the .zip file into Templates\ProjectTemplates directory for them to use too.

I made an ASP.NET MVC template with folders, layout page, viewmodels etc arranged just how I like them.

NOTE:
If you have an empty folder in your project, it WON'T be added to the template, so I just added an empty class appropriate to each folder, and a sample picture for images folder.

how to use Blob datatype in Postgres

I think this is the most comprehensive answer on the PostgreSQL wiki itself: https://wiki.postgresql.org/wiki/BinaryFilesInDB

Read the part with the title 'What is the best way to store the files in the Database?'

How do I access (read, write) Google Sheets spreadsheets with Python?

Take a look at gspread port for api v4 - pygsheets. It should be very easy to use rather than the google client.

Sample example

import pygsheets

gc = pygsheets.authorize()

# Open spreadsheet and then workseet
sh = gc.open('my new ssheet')
wks = sh.sheet1

# Update a cell with value (just to let him know values is updated ;) )
wks.update_cell('A1', "Hey yank this numpy array")

# update the sheet with array
wks.update_cells('A2', my_nparray.to_list())

# share the sheet with your friend
sh.share("[email protected]")

See the docs here.

Author here.

Android center view in FrameLayout doesn't work

We can align a view in center of the FrameLayout by setting the layout_gravity of the child view.

In XML:

android:layout_gravity="center"

In Java code:

FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;

Note: use FrameLayout.LayoutParams not the others existing LayoutParams

font size in html code

I suggest you use CSS instead, seems like you're going to repeat those lines later on. But to answer your question:

<html>
  <head>
  <style type="text/css">
    td.randname {
        padding-left: 5px;
        padding-bottom:3px;
        font-size:35px;
    }
  </style>
  </head>
  <body>
  <table>
  <tr>
  <td class="randname"> <b>Datum:</b><br/>
                            November 2010 </td></tr>
                            </table>
  </body>
</html>

vertical-align image in div

If you have a fixed height in your container, you can set line-height to be the same as height, and it will center vertically. Then just add text-align to center horizontally.

Here's an example: http://jsfiddle.net/Cthulhu/QHEnL/1/

EDIT

Your code should look like this:

.img_thumb {
    float: left;
    height: 120px;
    margin-bottom: 5px;
    margin-left: 9px;
    position: relative;
    width: 147px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 3px;
    line-height:120px;
    text-align:center;
}

.img_thumb img {
    vertical-align: middle;
}

The images will always be centered horizontally and vertically, no matter what their size is. Here's 2 more examples with images with different dimensions:

http://jsfiddle.net/Cthulhu/QHEnL/6/

http://jsfiddle.net/Cthulhu/QHEnL/7/

UPDATE

It's now 2016 (the future!) and looks like a few things are changing (finally!!).

Back in 2014, Microsoft announced that it will stop supporting IE8 in all versions of Windows and will encourage all users to update to IE11 or Edge. Well, this is supposed to happen next Tuesday (12th January).

Why does this matter? With the announced death of IE8, we can finally start using CSS3 magic.

With that being said, here's an updated way of aligning elements, both horizontally and vertically:

.container {
    position: relative;
}

.container .element {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
}

Using this transform: translate(); method, you don't even need to have a fixed height in your container, it's fully dynamic. Your element has fixed height or width? Your container as well? No? It doesn't matter, it will always be centered because all centering properties are fixed on the child, it's independent from the parent. Thank you CSS3.

If you only need to center in one dimension, you can use translateY or translateX. Just try it for a while and you'll see how it works. Also, try to change the values of the translate, you will find it useful for a bunch of different situations.

Here, have a new fiddle: https://jsfiddle.net/Cthulhu/1xjbhsr4/

For more information on transform, here's a good resource.

Happy coding.

An explicit value for the identity column in table can only be specified when a column list is used and IDENTITY_INSERT is ON SQL Server

SET IDENTITY_INSERT tableA ON

INSERT Into tableA ([id], [c2], [c3], [c4], [c5] ) 
SELECT [id], [c2], [c3], [c4], [c5] FROM tableB

Not like this

INSERT INTO tableA
SELECT * FROM tableB

SET IDENTITY_INSERT tableA OFF

XPath to select multiple tags

Not sure if this helps, but with XSL, I'd do something like:

<xsl:for-each select="a/b">
    <xsl:value-of select="c"/>
    <xsl:value-of select="d"/>
    <xsl:value-of select="e"/>
</xsl:for-each>

and won't this XPath select all children of B nodes:

a/b/*

Update a column in MySQL

if you want to fill all the column:

update 'column' set 'info' where keyID!=0;

Convert hours:minutes:seconds into total minutes in excel

The only way is to use a formula or to format cells. The method i will use will be the following: Add another column next to these values. Then use the following formula:

=HOUR(A1)*60+MINUTE(A1)+SECOND(A1)/60

enter image description here

How do I search within an array of hashes by hash values in ruby?

this will return first match

@fathers.detect {|f| f["age"] > 35 }

What is the JavaScript version of sleep()?

I have searched/googled quite a few webpages on javascript sleep/wait... and there is NO answer if you want javascript to "RUN, DELAY, RUN"... what most people got was either, "RUN, RUN(useless stuff), RUN" or "RUN, RUN + delayed RUN"....

So I ate some burgers and got thinking::: here is a solution that works... but you have to chop up your running codes...::: yes, I know, this is just an easier to read refactoring... still...

//......................................... //example1:

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setInterval
var i = 0;

function run() {
    //pieces of codes to run
    if (i==0){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
    if (i==1){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
    if (i==2){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
    if (i >2){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
    if (i==5){document.getElementById("id1").innerHTML= "<p>all code segment finished running</p>"; clearInterval(t); } //end interval, stops run
    i++; //segment of code finished running, next...
}

run();
t=setInterval("run()",1000);

</script>
</body>
</html>

//.................................... //example2:

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setTimeout
var i = 0;

function run() {
    //pieces of codes to run, can use switch statement
    if (i==0){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>"; sleep(1000);}
    if (i==1){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>"; sleep(2000);}
    if (i==2){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>"; sleep(3000);}
    if (i==3){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>";} //stops automatically
    i++;
}

function sleep(dur) {t=setTimeout("run()",dur);} //starts flow control again after dur

run(); //starts
</script>
</body>
</html>

//................. example3:

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setTimeout
var i = 0;

function flow() {
    run(i);
    i++; //code segment finished running, increment i; can put elsewhere
    sleep(1000);
    if (i==5) {clearTimeout(t);} //stops flow, must be after sleep()
}

function run(segment) {
    //pieces of codes to run, can use switch statement
    if (segment==0){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment==1){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment==2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment >2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
}

function sleep(dur) {t=setTimeout("flow()",dur);} //starts flow control again after dur

flow(); //starts flow
</script>
</body>
</html>

//.............. example4:

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setTimeout, switch
var i = 0;

function flow() {
    switch(i)
    {
        case 0:
            run(i);
            sleep(1000);
            break;
        case 1:
            run(i);
            sleep(2000);
            break;
        case 5:
            run(i);
            clearTimeout(t); //stops flow
            break;
        default:
            run(i);
            sleep(3000);
            break;
    }
}

function run(segment) {
    //pieces of codes to run, can use switch statement
    if (segment==0){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment==1){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment==2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment >2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    i++; //current segment of code finished running, next...
}

function sleep(dur) {t=setTimeout("flow()",dur);} //starts flow control again after dur

flow(); //starts flow control for first time...
</script>
</body>
</html>

Check If array is null or not in php

I understand what you want. You want to check every data of the array if all of it is empty or at least 1 is not empty

Empty array

Array ( [Tags] => SimpleXMLElement Object ( [0] => ) )

Not an Empty array

Array ( [Tags] => SimpleXMLElement Object ( [0] =>,[1] => "s" ) )


I hope I am right. You can use this function to check every data of an array if at least 1 of them has a value.

/*
 return true if the array is not empty
 return false if it is empty
*/
function is_array_empty($arr){
  if(is_array($arr)){     
      foreach($arr $key => $value){
          if(!empty($value) || $value != NULL || $value != ""){
              return true;
              break;//stop the process we have seen that at least 1 of the array has value so its not empty
          }
      }
      return false;
  }
}

if(is_array_empty($result['Tags'])){
    //array is not empty
}else{
    //array is empty
}

Hope that helps.

set font size in jquery

You can try another way like that:

<div class="content">
        Australia
    </div>

jQuery code:

$(".content").css({
    background: "#d1d1d1",
    fontSize: "30px"
})

Now you can add more css property as you want.

Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

function humanTiming ($time)
        {

            $time = time() - $time; // to get the time since that moment
            $time = ($time<1)? 1 : $time;
            $tokens = array (
                31536000 => 'year',
                2592000 => 'month',
                604800 => 'week',
                86400 => 'day',
                3600 => 'hour',
                60 => 'minute',
                1 => 'second'
            );

            foreach ($tokens as $unit => $text) {
                if ($time < $unit) continue;
                $numberOfUnits = floor($time / $unit);
                return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
            }

        }

echo humanTiming( strtotime($mytimestring) );

No provider for Http StaticInjectorError

Update: Angular v6+

For Apps converted from older versions (Angular v2 - v5): HttpModule is now deprecated and you need to replace it with HttpClientModule or else you will get the error too.

  1. In your app.module.ts replace import { HttpModule } from '@angular/http'; with the new HttpClientModule import { HttpClientModule} from "@angular/common/http"; Note: Be sure to then update the modules imports[] array by removing the old HttpModule and replacing it with the new HttpClientModule.
  2. In any of your services that used HttpModule replace import { Http } from '@angular/http'; with the new HttpClient import { HttpClient } from '@angular/common/http';
  3. Update how you handle your Http response. For example - If you have code that looks like this

    http.get('people.json').subscribe((res:Response) => this.people = res.json());

The above code example will result in an error. We no longer need to parse the response, because it already comes back as JSON in the config object.

The subscription callback copies the data fields into the component's config object, which is data-bound in the component template for display.

For more information please see the - Angular HttpClientModule - Official Documentation

Bootstrap 3 unable to display glyphicon properly

First of all, I try to install the glyphicons fonts by the "oficial" way, with the zip file. I could not do it.

This is my step-by-step solution:

  1. Go to the web page of Bootstrap and then to the "Components" section.
  2. Open the browser console. In Chrome, Ctrl+Shift+C.
  3. In section Resources, inside Frames/getbootstrap.com/Fonts you will find the font that actually is running the glyphicons. It's recommended to use the private mode to evade cache.
  4. With URL of the font file (right-click on the file showed on resources list), copy it in a new tab, and press ENTER. This will download the font file.
  5. Copy another time the URL in a tab and change the font extension to eot, ttf, svg or woff, ass you like.

However, for a more easy acces, this is the link of the woff file.

http://getbootstrap.com/dist/fonts/glyphicons-halflings-regular.woff

Twitter Bootstrap hide css class and jQuery

As dfsq said i just had to use removeClass("hide") instead of toggle()

How do you format code in Visual Studio Code (VSCode)

Select the text, right click on the selection, and select the option "command palette":

Enter image description here

A new window opens. Search for "format" and select the option which has formatting as per the requirement.

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

The compiler will start doing very clever things with optimisations turned on. The debugger will show the code jumping forward and backwards alot due to the optimized way variables are stored in registers. This is probably the reason why you can't set your variable (or in some cases see its value) as it has been cleverly distributed between registers for speed, rather than having a direct memory location that the debugger can access.

Compile without optimisations?

Access VBA | How to replace parts of a string with another string

Use Access's VBA function Replace(text, find, replacement):

Dim result As String

result = Replace("Some sentence containing Avenue in it.", "Avenue", "Ave")

updating table rows in postgres using subquery

@Mayur "4.2 [Using query with complex JOIN]" with Common Table Expressions (CTEs) did the trick for me.

WITH cte AS (
SELECT e.id, e.postcode
FROM employees e
LEFT JOIN locations lc ON lc.postcode=cte.postcode
WHERE e.id=1
)
UPDATE employee_location SET lat=lc.lat, longitude=lc.longi
FROM cte
WHERE employee_location.id=cte.id;

Hope this helps... :D

Programmatically Hide/Show Android Soft Keyboard

Try this code.

For showing Softkeyboard:

InputMethodManager imm = (InputMethodManager)
                                 getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    }

For Hiding SoftKeyboard -

InputMethodManager imm = (InputMethodManager)
                                  getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

Equivalent of LIMIT for DB2

Support for OFFSET and LIMIT was recently added to DB2 for i 7.1 and 7.2. You need the following DB PTF group levels to get this support:

  • SF99702 level 9 for IBM i 7.2
  • SF99701 level 38 for IBM i 7.1

See here for more information: OFFSET and LIMIT documentation, DB2 for i Enhancement Wiki

Regex Last occurrence?

I used below regex to get that result also when its finished by a \

(\\[^\\]+)\\?$

[Regex Demo]

Creating a REST API using PHP

In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:

  1. validating the data POSTed
  2. make sure your API is sending the Content-Type header to tell the client to expect a JSON response:

    header('Content-Type: application/json');
    echo json_encode($response);
    

Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.

If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController with an add() action/method.

There are a few starting point projects for RESTful APIs on GitHub that are worth a look.

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

Wunderbart's post worked for me combined with statler's improvements. Adding a few more comments and syntax cleanup, and also passing back the orientation value and I have the following code feel free to use. Just call readImageFile() function below and you get back the transformed image and the original orientation.

const JpegOrientation = [
    "NOT_JPEG",
    "NORMAL",
    "FLIP-HORIZ",
    "ROT180",
    "FLIP-HORIZ-ROT180",
    "FLIP-HORIZ-ROT270",
    "ROT270",
    "FLIP-HORIZ-ROT90",
    "ROT90"
];


//Provided a image file, determines the orientation of the file based on the EXIF information.
//Calls the "callback" function with an index into the JpegOrientation array. 
//If the image is not a JPEG, returns 0. If  the orientation value cannot be read (corrupted file?) return -1.
function getOrientation(file, callback) {
    
    const reader = new FileReader();
    reader.onload = (e) => {

        const view = new DataView(e.target.result);
        
        if (view.getUint16(0, false) !== 0xFFD8) {
            return callback(0);  //NOT A JPEG FILE
        }
        
        const length = view.byteLength;
        let offset = 2;
        while (offset < length) {
            
            if (view.getUint16(offset+2, false) <= 8)   //unknown?
                return callback(-1);
            
            const marker = view.getUint16(offset, false);
            offset += 2;
            if (marker === 0xFFE1) {
                
                if (view.getUint32(offset += 2, false) !== 0x45786966) 
                    return callback(-1); //unknown?
                

                const little = view.getUint16(offset += 6, false) === 0x4949;
                offset += view.getUint32(offset + 4, little);
                const tags = view.getUint16(offset, little);
                offset += 2;
                for (var i = 0; i < tags; i++) {
                    if (view.getUint16(offset + (i * 12), little) === 0x0112) {
                        return callback(view.getUint16(offset + (i * 12) + 8, little));   //found orientation code
                    }
                }
            }
            else if ((marker & 0xFF00) !== 0xFF00) {
                break;
            }
            else { 
                offset += view.getUint16(offset, false);
            }
        }
        
        return callback(-1); //unknown?
    };
    reader.readAsArrayBuffer(file);
}

//Takes a jpeg image file as base64 and transforms it back to original, providing the
//transformed image in callback.  If the image is not a jpeg or is already in normal orientation,
//just calls the callback directly with the source.
//Set type to the desired output type if transformed, default is image/jpeg for speed.
function resetOrientation(srcBase64, srcOrientation, callback, type = "image/jpeg") {
    
    if (srcOrientation <= 1) {  //no transform needed
        callback(srcBase64);
        return;
    }
    
    const img = new Image();    

    img.onload = () => {
        const width = img.width;
        const height = img.height;
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext("2d");

        // set proper canvas dimensions before transform & export
        if (4 < srcOrientation && srcOrientation < 9) {
            canvas.width = height;
            canvas.height = width;
        } else {
            canvas.width = width;
            canvas.height = height;
        }

        // transform context before drawing image
        switch (srcOrientation) {
              
              //case 1: normal, no transform needed
              
              case 2:  
                  ctx.transform(-1, 0, 0, 1, width, 0); 
                  break;
              case 3:
                  ctx.transform(-1, 0, 0, -1, width, height); 
                  break;
              case 4: 
                  ctx.transform(1, 0, 0, -1, 0, height); 
                  break;
              case 5: 
                  ctx.transform(0, 1, 1, 0, 0, 0); 
                  break;
              case 6: 
                  ctx.transform(0, 1, -1, 0, height, 0); 
                  break;
              case 7: 
                  ctx.transform(0, -1, -1, 0, height, width); 
                  break;
              case 8: 
                  ctx.transform(0, -1, 1, 0, 0, width); 
                  break;
              default: 
                  break;
        }

        // draw image
        ctx.drawImage(img, 0, 0);

        //export base64
        callback(canvas.toDataURL(type), srcOrientation);
    };

    img.src = srcBase64;
};


//Read an image file, providing the returned data to callback. If the image is jpeg
//and is transformed according to EXIF info, transform it first.
//The callback function receives the image data and the orientation value (index into JpegOrientation)
export function readImageFile(file, callback) {

    getOrientation(file, (orientation) => {

        console.log("Read file \"" + file.name + "\" with orientation: " + JpegOrientation[orientation]);

        const reader = new FileReader();
        reader.onload = () => {  //when reading complete

            const img = reader.result;
            resetOrientation(img, orientation, callback);
        };
        reader.readAsDataURL(file);  //start read
        
    });
}

How can I get browser to prompt to save password?

Using a cookie would probably be the best way to do this.

You could have a checkbox for 'Remember me?' and have the form create a cookie to store the //user's login// info. EDIT: User Session Information

To create a cookie, you'll need to process the login form with PHP.

android.widget.Switch - on/off event listener?

Switch inherits CompoundButton's attributes, so I would recommend the OnCheckedChangeListener

mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // do something, the isChecked will be
        // true if the switch is in the On position
    }
});

Unrecognized escape sequence for path string containing backslashes

string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";

This will work, or the previous examples will, too. @"..." means treat everything between the quote marks literally, so you can do

@"Hello
world"

To include a literal newline. I'm more old school and prefer to escape "\" with "\\"

Where does this come from: -*- coding: utf-8 -*-

This is so called file local variables, that are understood by Emacs and set correspondingly. See corresponding section in Emacs manual - you can define them either in header or in footer of file

Why is “while ( !feof (file) )” always wrong?

feof() is not very intuitive. In my very humble opinion, the FILE's end-of-file state should be set to true if any read operation results in the end of file being reached. Instead, you have to manually check if the end of file has been reached after each read operation. For example, something like this will work if reading from a text file using fgetc():

#include <stdio.h>

int main(int argc, char *argv[])
{
  FILE *in = fopen("testfile.txt", "r");

  while(1) {
    char c = fgetc(in);
    if (feof(in)) break;
    printf("%c", c);
  }

  fclose(in);
  return 0;
}

It would be great if something like this would work instead:

#include <stdio.h>

int main(int argc, char *argv[])
{
  FILE *in = fopen("testfile.txt", "r");

  while(!feof(in)) {
    printf("%c", fgetc(in));
  }

  fclose(in);
  return 0;
}

HTML-Tooltip position relative to mouse pointer

This CAN be done with pure html and css. It may not be the best way but we all have different limitations. There are 3 ways that could be useful depending on what your specific circumstances are.

  1. The first involves overlaying an invisible table over top of your link with a hover action on each cell that displays an image.

_x000D_
_x000D_
#imagehover td:hover::after{_x000D_
  content: "             ";_x000D_
  white-space: pre;_x000D_
  background-image: url("http://www.google.com/images/srpr/logo4w.png");_x000D_
  position: relative;_x000D_
  left: 5px;_x000D_
  top: 5px;_x000D_
  font-size: 20px;_x000D_
  background-color: transparent;_x000D_
  background-position: 0px 0px;_x000D_
  background-size: 60px 20px;_x000D_
  background-repeat: no-repeat;_x000D_
  _x000D_
}_x000D_
_x000D_
_x000D_
#imagehover table, #imagehover th, #imagehover td {_x000D_
  border: 0px;_x000D_
  border-spacing: 0px;_x000D_
}
_x000D_
<a href="https://www.google.com">_x000D_
<table id="imagehover" style="width:50px;height:10px;z-index:9999;position:absolute" cellspacing="0">_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
_x000D_
</table>_x000D_
Google</a>
_x000D_
_x000D_
_x000D_

  1. The second relies on being able to create your own cursor image

_x000D_
_x000D_
#googleLink{_x000D_
_x000D_
cursor: url(https://winter-bush-d06c.sto.workers.dev/cursor-extern.php?id=98272),url(https://9dc1a5c00e8109665645209c2d036b1c.cloudflareworkers.com/cursor-extern.php?id=98272),auto;_x000D_
_x000D_
}
_x000D_
<a href="https://www.google.com" id="googleLink">Google</a>
_x000D_
_x000D_
_x000D_

  1. While the normal title tooltip doesn't technically allow images it does allow any unicode characters including block letters and emojis which may suite your needs.

_x000D_
_x000D_
<a href="https://www.google.com" title="??" alt="??">Google</a>
_x000D_
_x000D_
_x000D_

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

Use java.sql.Timestamp.toString if you want to get fractional seconds in text representation. The difference betwen Timestamp from DB and Java Date is that DB precision is nanoseconds while Java Date precision is milliseconds.

SQL query for extracting year from a date

just pass the columnName as parameter of YEAR

SELECT YEAR(ASOFDATE) from PSASOFDATE;

another is to use DATE_FORMAT

SELECT DATE_FORMAT(ASOFDATE, '%Y') from PSASOFDATE;

UPDATE 1

I bet the value is varchar with the format MM/dd/YYYY, it that's the case,

SELECT YEAR(STR_TO_DATE('11/15/2012', '%m/%d/%Y'));

LAST RESORT if all the queries fail

use SUBSTRING

SELECT SUBSTRING('11/15/2012', 7, 4)

R: how to label the x-axis of a boxplot

If you read the help file for ?boxplot, you'll see there is a names= parameter.

     boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))

enter image description here

What is the argument for printf that formats a long?

I think you mean:

unsigned long n;
printf("%lu", n);   // unsigned long

or

long n;
printf("%ld", n);   // signed long

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

See this answer about the No overload for method 'ToString' takes 1 arguments error.

You cannot format a nullable DateTime - you have to use the DateTime.Value property.

@Model.AuditDate.HasValue ? Model.AuditDate.Value.ToString("mm/dd/yyyy") : string.Empty

Tip: It is always helpful to work this stuff out in a standard class with intellisense before putting it into a view. In this case, you would get a compile error which would be easy to spot in a class.

Python: json.loads returns items prefixing with 'u'

I kept running into this problem when trying to capture JSON data in the log with the Python logging library, for debugging and troubleshooting purposes. Getting the u character is a real nuisance when you want to copy the text and paste it into your code somewhere.

As everyone will tell you, this is because it is a Unicode representation, and it could come from the fact that you’ve used json.loads() to load in the data from a string in the first place.

If you want the JSON representation in the log, without the u prefix, the trick is to use json.dumps() before logging it out. For example:

import json
import logging

# Prepare the data
json_data = json.loads('{"key": "value"}')

# Log normally and get the Unicode indicator
logging.warning('data: {}'.format(json_data))
>>> WARNING:root:data: {u'key': u'value'}

# Dump to a string before logging and get clean output!
logging.warning('data: {}'.format(json.dumps(json_data)))
>>> WARNING:root:data: {'key': 'value'}

How to define constants in ReactJS

If you want to keep the constants in the React component, use statics property, like the example below. Otherwise, use the answer given by @Jim

var MyComponent = React.createClass({
    statics: {
        sizeToLetterMap: {
            small_square: 's',
            large_square: 'q',
            thumbnail: 't',
            small_240: 'm',
            small_320: 'n',
            medium_640: 'z',
            medium_800: 'c',
            large_1024: 'b',
            large_1600: 'h',
            large_2048: 'k',
            original: 'o'
        },
        someOtherStatic: 100
    },

    photoUrl: function (image, size_text) {
        var size = MyComponent.sizeToLetterMap[size_text];
    }

How to make a flat list out of list of lists?

This is a play on the original poster's code. (He wasn't far off)

f = []
list(map(f.extend, l))

Why do I have ORA-00904 even when the column is present?

Its due to mismatch between column name defined in entity and the column name of table (in SQL db )

java.sql.SQLException: ORA-00904: "table_name"."column_name": invalid identifier e.g.java.sql.SQLException: ORA-00904: "STUDENT"."NAME": invalid identifier

issue can be like in Student.java(entity file) 
You have mentioned column name as "NAME" only.
But in STUDENT table ,column name is lets say "NMAE"

iPhone/iPad browser simulator?

Both Chrome and Firefox now have built-in emulators. They aren't perfect but are good enough that can get you almost all of the way before testing on an actual device. The best part is if you like the browser's developer tools (Chrome, Firefox), you can use them while emulating.

To get the emulator: [Ctrl+Shift+M] and select the device that you want to emulate. You might have to refresh the page, esp if you have anything that depends on script that executes on page load.

Google Chrome Emulation mode

Internet Explorer also has a device emulation mode. F12, then CTRL+8. It's not quite as straight forward as the Chrome Mobile Device emulation, but does allow you to simulate geolocation:

Internet Explorer Emulation mode

Reactjs setState() with a dynamic key name?

When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.

For example:

_x000D_
_x000D_
inputChangeHandler(event) {_x000D_
  this.setState({ [event.target.name]: event.target.value });_x000D_
}
_x000D_
_x000D_
_x000D_

How to get request url in a jQuery $.get/ajax request

I can't get it to work on $.get() because it has no complete event.

I suggest to use $.ajax() like this,

$.ajax({
    url: 'http://www.example.org',
    data: {'a':1,'b':2,'c':3},
    dataType: 'xml',
    complete : function(){
        alert(this.url)
    },
    success: function(xml){
    }
});

craz demo

Error handling with PHPMailer

You can get more info about the error with the method $mail->ErrorInfo. For example:

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

This is an alternative to the exception model that you need to active with new PHPMailer(true). But if can use exception model, use it as @Phil Rykoff answer.

This comes from the main page of PHPMailer on github https://github.com/PHPMailer/PHPMailer.

DynamoDB vs MongoDB NoSQL

I have worked on both and kind of fan of both.

But you need to understand when to use what and for what purpose.

I don't think It's a great idea to move all your database to DynamoDB, reason being querying is difficult except on primary and secondary keys, Indexing is limited and scanning in DynamoDB is painful.

I would go for a hybrid sort of DB, where extensive query-able data should be there is MongoDB, with all it's feature you would never feel constrained to provide enhancements or modifications.

DynamoDB is lightning fast (faster than MongoDB) so DynamoDB is often used as an alternative to sessions in scalable applications. DynamoDB best practices also suggests that if there are plenty of data which are less being used, move it to other table.

So suppose you have a articles or feeds. People are more likely to look for last week stuff or this month's stuff. chances are really rare for people to visit two year old data. For these purposes DynamoDB prefers to have data stored by month or years in different tables.

DynamoDB is seemlessly scalable, something you will have to do manually in MongoDB. however you would lose on performance of DynamoDB, if you don't understand about throughput partition and how scaling works behind the scene.

DynamoDB should be used where speed is critical, MongoDB on the other hand has too many hands and features, something DynamoDB lacks.

for example, you can have a replica set of MongoDB in such a way that one of the replica holds data instance of 8(or whatever) hours old. Really useful, if you messed up something big time in your DB and want to get the data as it is before.

That's my opinion though.

What does the regex \S mean in JavaScript?

\s matches whitespace (spaces, tabs and new lines). \S is negated \s.

Pipe subprocess standard output to a variable

With a = subprocess.Popen("cdrecord --help",stdout = subprocess.PIPE) , you need to either use a list or use shell=True;

Either of these will work. The former is preferable.

a = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE)

a = subprocess.Popen('cdrecord --help', shell=True, stdout=subprocess.PIPE)

Also, instead of using Popen.stdout.read/Popen.stderr.read, you should use .communicate() (refer to the subprocess documentation for why).

proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()

Python Iterate Dictionary by Index

When I need to keep the order, I use a list and a companion dict:

color = ['red','green','orange']
fruit = {'apple':0,'mango':1,'orange':2}
color[fruit['apple']]
for i in range(0,len(fruit)): # or len(color)
    color[i]

The inconvenience is I don't get easily the fruit from the index. When I need it, I use a tuple:

fruitcolor = [('apple','red'),('mango','green'),('orange','orange')]
index = {'apple':0,'mango':1,'orange':2}
fruitcolor[index['apple']][1]
for i in range(0,len(fruitcolor)): 
    fruitcolor[i][1]
for f, c in fruitcolor:
    c

Your data structures should be designed to fit your algorithm needs, so that it remains clean, readable and elegant.

What is the equivalent of "!=" in Excel VBA?

Just a note. If you want to compare a string with "" ,in your case, use

If LEN(str) > 0 Then

or even just

If LEN(str) Then

instead.

How to open a workbook specifying its path

You can also open a required file through a prompt, This helps when you want to select file from different path and different file.

Sub openwb()
Dim wkbk As Workbook
Dim NewFile As Variant

NewFile = Application.GetOpenFilename("microsoft excel files (*.xlsm*), *.xlsm*")

If NewFile <> False Then
Set wkbk = Workbooks.Open(NewFile)
End If
End Sub

Is there a difference between "throw" and "throw ex"?

When you do throw ex, that thrown exception becomes the "original" one. So all previous stack trace will not be there.

If you do throw, the exception just goes down the line and you'll get the full stack trace.

How do you make div elements display inline?

Just use a wrapper div with "float: left" and put boxes inside also containing float: left:

CSS:

wrapperline{
width: 300px;
float: left;
height: 60px;
background-color:#CCCCCC;}

.boxinside{
width: 50px;
float: left;
height: 50px;
margin: 5px;
background-color:#9C0;
float:left;}

HTML:

<div class="wrapperline">
<div class="boxinside">Box 1</div>
<div class="boxinside">Box 1</div>
<div class="boxinside">Box 1</div>
<div class="boxinside">Box 1</div>
<div class="boxinside">Box 1</div>
</div>

Convert PDF to clean SVG?

You can use Inkscape on the commandline only, without opening a GUI. Try this:

inkscape \
  --without-gui \
  --file=input.pdf \
  --export-plain-svg=output.svg 

For a complete list of all commandline options, run inkscape --help.

Border Height on CSS

No, there isn't. The border will always be as tall as the element.

You can achieve the same effect by wrapping the contents of the cell in a <span>, and applying height/border styles to that. Or by drawing a short vertical line in an 1 pixel wide PNG which is the correct height, and applying it as a background to the cell:

background:url(line.png) bottom right no-repeat;

find vs find_by vs where

Both #2s in your lists are being deprecated. You can still use find(params[:id]) though.

Generally, where() works in most situations.

Here's a great post: https://web.archive.org/web/20150206131559/http://m.onkey.org/active-record-query-interface

How to Consume WCF Service with Android

Another option might be to avoid WCF all-together and just use a .NET HttpHandler. The HttpHandler can grab the query-string variables from your GET and just write back a response to the Java code.

what is the difference between json and xml

The fundamental difference, which no other answer seems to have mentioned, is that XML is a markup language (as it actually says in its name), whereas JSON is a way of representing objects (as also noted in its name).

A markup language is a way of adding extra information to free-flowing plain text, e.g

Here is some text.

With XML (using a certain element vocabulary) you can put:

<Document>
    <Paragraph Align="Center">
        Here <Bold>is</Bold> some text.
    </Paragraph>
</Document>

This is what makes markup languages so useful for representing documents.

An object notation like JSON is not as flexible. But this is usually a good thing. When you're representing objects, you simply don't need the extra flexibility. To represent the above example in JSON, you'd actually have to solve some problems manually that XML solves for you.

{
    "Paragraphs": [
        {
            "align": "center",
            "content": [
                "Here ", {
                    "style" : "bold",
                    "content": [ "is" ]
                },
                " some text."
            ]
        }
    ]
}

It's not as nice as the XML, and the reason is that we're trying to do markup with an object notation. So we have to invent a way to scatter snippets of plain text around our objects, using "content" arrays that can hold a mixture of strings and nested objects.

On the other hand, if you have typical a hierarchy of objects and you want to represent them in a stream, JSON is better suited to this task than HTML.

{
    "firstName": "Homer",
    "lastName": "Simpson",
    "relatives": [ "Grandpa", "Marge", "The Boy", "Lisa", "I think that's all of them" ]
} 

Here's the logically equivalent XML:

<Person>
    <FirstName>Homer</FirstName>
    <LastName>Simpsons</LastName>
    <Relatives>
        <Relative>Grandpa</Relative>
        <Relative>Marge</Relative>
        <Relative>The Boy</Relative>
        <Relative>Lisa</Relative>
        <Relative>I think that's all of them</Relative>
    </Relatives>
</Person>

JSON looks more like the data structures we declare in programming languages. Also it has less redundant repetition of names.

But most importantly of all, it has a defined way of distinguishing between a "record" (items unordered, identified by names) and a "list" (items ordered, identified by position). An object notation is practically useless without such a distinction. And XML has no such distinction! In my XML example <Person> is a record and <Relatives> is a list, but they are not identified as such by the syntax.

Instead, XML has "elements" versus "attributes". This looks like the same kind of distinction, but it's not, because attributes can only have string values. They cannot be nested objects. So I couldn't have applied this idea to <Person>, because I shouldn't have to turn <Relatives> into a single string.

By using an external schema, or extra user-defined attributes, you can formalise a distinction between lists and records in XML. The advantage of JSON is that the low-level syntax has that distinction built into it, so it's very succinct and universal. This means that JSON is more "self describing" by default, which is an important goal of both formats.

So JSON should be the first choice for object notation, where XML's sweet spot is document markup.

Unfortunately for XML, we already have HTML as the world's number one rich text markup language. An attempt was made to reformulate HTML in terms of XML, but there isn't much advantage in this.

So XML should (in my opinion) have been a pretty limited niche technology, best suited only for inventing your own rich text markup languages if you don't want to use HTML for some reason. The problem was that in 1998 there was still a lot of hype about the Web, and XML became popular due to its superficial resemblance to HTML. It was a strange design choice to try to apply to hierarchical data a syntax actually designed for convenient markup.

How to use Angular4 to set focus by element id

This helped to me (in ionic, but idea is the same) https://mhartington.io/post/setting-input-focus/

in template:

<ion-item>
      <ion-label>Home</ion-label>
      <ion-input #input type="text"></ion-input>
</ion-item>
<button (click)="focusInput(input)">Focus</button>

in controller:

  focusInput(input) {
    input.setFocus();
  }

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

BUILDING Again on Nathan and JB's Answer:

How To Launch App From url w/o Extra Click If you prefer a solution that does not include the interim step of clicking a link, the following can be used. With this javascript, I was able to return a Httpresponse object from Django/Python that successfully launches an app if it is installed or alternatively launches the app store in the case of a time out. Note I also needed to adjust the timeout period from 500 to 100 in order for this to work on an iPhone 4S. Test and tweak to get it right for your situation.

<html>
<head>
   <meta name="viewport" content="width=device-width" />
</head>
<body>

<script type="text/javascript">

// To avoid the "protocol not supported" alert, fail must open another app.
var appstorefail = "itms://itunes.apple.com/us/app/facebook/id284882215?mt=8&uo=6";

var loadedAt = +new Date;
setTimeout(
  function(){
    if (+new Date - loadedAt < 2000){
      window.location = appstorefail;
    }
  }
,100);

function LaunchApp(){
  window.open("unknown://nowhere","_self");
};
LaunchApp()
</script>
</body>
</html>

How to create a connection string in asp.net c#

string connectionstring="DataSource=severname;InitialCatlog=databasename;Uid=; password=;"
SqlConnection con=new SqlConnection(connectionstring)

How to check if IsNumeric

There's a slightly better way:

int valueParsed;
if(Int32.TryParse(txtMyText.Text.Trim(), out valueParsed))
{ ... }

If you try to parse the text and it can't be parsed, the Int32.Parse method will raise an exception. I think it is better for you to use the TryParse method which will capture the exception and let you know as a boolean if any exception was encountered.

There are lot of complications in parsing text which Int32.Parse takes into account. It is foolish to duplicate the effort. As such, this is very likely the approach taken by VB's IsNumeric. You can also customize the parsing rules through the NumberStyles enumeration to allow hex, decimal, currency, and a few other styles.

Another common approach for non-web based applications is to restrict the input of the text box to only accept characters which would be parseable into an integer.

EDIT: You can accept a larger variety of input formats, such as money values ("$100") and exponents ("1E4"), by specifying the specific NumberStyles:

int valueParsed;
if(Int32.TryParse(txtMyText.Text.Trim(), NumberStyles.AllowCurrencySymbol | NumberStyles.AllowExponent, CultureInfo.CurrentCulture, out valueParsed))
{ ... }

... or by allowing any kind of supported formatting:

int valueParsed;
if(Int32.TryParse(txtMyText.Text.Trim(), NumberStyles.Any, CultureInfo.CurrentCulture, out valueParsed))
{ ... }

Copy map values to vector in STL

Old question, new answer. With C++11 we have the fancy new for loop:

for (const auto &s : schemas)
   names.push_back(s.first);

where schemas is a std::map and names is an std::vector.

This populates the array (names) with keys from the map (schemas); change s.first to s.second to get an array of values.

Regular Expression to get all characters before "-"

Find all word and space characters up to and including a -

^[\w ]+-

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

Pelo Hyper-V:

private PerformanceCounter theMemCounter = new PerformanceCounter(
    "Hyper-v Dynamic Memory VM",
    "Physical Memory",
    Process.GetCurrentProcess().ProcessName); 

Is it possible to pull just one file in Git?

Yes, here is the process:

# Navigate to a directory and initiate a local repository
git init        

# Add remote repository to be tracked for changes:   
git remote add origin https://github.com/username/repository_name.git

# Track all changes made on above remote repository
# This will show files on remote repository not available on local repository
git fetch

# Add file present in staging area for checkout
git check origin/master -m /path/to/file
# NOTE: /path/to/file is a relative path from repository_name
git add /path/to/file

# Verify track of file(s) being committed to local repository
git status

# Commit to local repository
git commit -m "commit message"

# You may perform a final check of the staging area again with git status

Firebase: how to generate a unique numeric ID for key?

Adding to the @htafoya answer. The code snippet will be

const getTimeEpoch = () => {
    return new Date().getTime().toString();                             
}

Check if cookies are enabled

Cookies are Client-side and cannot be tested properly using PHP. That's the baseline and every solution is a wrap-around for this problem.

Meaning if you are looking a solution for your cookie problem, you are on the wrong way. Don'y use PHP, use a client language like Javascript.

Can you use cookies using PHP? Yes, but you have to reload to make the settings to PHP 'visible'.

For instance: Is a test possible to see if the browser can set Cookies with plain PHP'. The only correct answer is 'NO'.

Can you read an already set Cookie: 'YES' use the predefined $_COOKIE (A copy of the settings before you started PHP-App).

Running Node.js in apache?

The common method for doing what you're looking to do is to run them side by side, and either proxy requests from apache to node.js based on domain / url, or simply have your node.js content be pulled from the node.js port. This later method works very well for having things like socket.io powered widgets on your site and such.


If you're going to be doing all of your dynamic content generation in node however, you might as well just use node.js as your primary webserver too, it does a very good job at serving both static and dynamic http requests.

See:

http://expressjs.com/

https://github.com/joyent/node/wiki/modules

Regular expression to find URLs within a string

If you have the url pattern, you should be able to search for it in your string. Just make sure that the pattern doesnt have ^ and $ marking beginning and end of the url string. So if P is the pattern for URL, look for matches for P.

Read from file or stdin

You may want to look at how this is done in the cat utility, for example.

See code here. If there is no filename as argument, or it is "-", then stdin is used for input. stdin will be there, even if no data is pushed to it (but then, your read call may wait forever).

How to reset par(mfrow) in R

You can reset the mfrow parameter

par(mfrow=c(1,1))

Url decode UTF-8 in Python

The data is UTF-8 encoded bytes escaped with URL quoting, so you want to decode, with urllib.parse.unquote(), which handles decoding from percent-encoded data to UTF-8 bytes and then to text, transparently:

from urllib.parse import unquote

url = unquote(url)

Demo:

>>> from urllib.parse import unquote
>>> url = 'example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0'
>>> unquote(url)
'example.com?title=????????+??????'

The Python 2 equivalent is urllib.unquote(), but this returns a bytestring, so you'd have to decode manually:

from urllib import unquote

url = unquote(url).decode('utf8')

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

Think about it: the database really has to go to every row to do that. In a multi-user environment my COUNT(*) could be different from your COUNT(*). It would be impractical to have a different counter for each and every session so you have literally to count the rows. Most of the time anyway you would have a WHERE clause or a JOIN in your query so your hypothetical counter would be of litte practical value.

There are ways to speed up things however: if you have an INDEX on a NOT NULL column Oracle will count the rows of the index instead of the table. In a proper relational model all tables have a primary key so the COUNT(*) will use the index of the primary key.

Bitmap index have entries for NULL rows so a COUNT(*) will use a bitmap index if there is one available.

mysql_config not found when installing mysqldb python interface

I got the same error while trying to install mysql-python.

This is how I fixed it.

sudo PATH=/usr/local/mysql/bin/:$PATH pip install mysql-python

The problem was that the installer could not find the mysql_config in the default path. Now it can ..and it worked..

 15 warnings generated.
    clang -bundle -undefined dynamic_lookup -Wl,-F. build/temp.macosx-10.8-intel-2.7/_mysql.o -L/usr/local/mysql/lib -lmysqlclient_r -lz -lm -lmygcc -o build/lib.macosx-10.8-intel-2.7/_mysql.so -arch x86_64

Successfully installed mysql-python
Cleaning up...

Hope this helps.

Thanks.

How to get started with Windows 7 gadgets

Combining and organizing all the current answers into one answer, then adding my own research:

Brief summary of Microsoft gadget development:

What are they written in? Windows Vista/Seven gadgets are developed in a mix of XML, HTML, CSS, and some IE scripting language. It is also possible to use C# with the latest release of Script#.

How are they packaged/deployed? The actual gadgets are stored in *.gadget files, which are simply the text source files listed above compressed into a single zip file.

Useful references for gadget development:

where do I start? Good introductory references to Windows Vista/Seven gadget development:

If you are willing to use offline resources, this book appears to be an excellent resource:

What do I need to know? Some other useful references; not necessarily instructional


Update: Well, this has proven to be a popular answer~ Sharing my own recent experience with Windows 7 gadget development:

Perhaps the easiest way to get started with Windows 7 gadget development is to modify a gadget that has already been developed. I recently did this myself because I wanted a larger clock gadget. Unable to find any, I tinkered with a copy of the standard Windows clock gadget until it was twice as large. I recommend starting with the clock gadget because it is fairly small and well-written. Here is the process I used:

  1. Locate the gadget you wish to modify. They are located in several different places. Search for folders named *.gadget. Example: C:\Program Files\Windows Sidebar\Gadgets\Clock.Gadget\
  2. Make a copy of this folder (installed gadgets are not wrapped in zip files.)
  3. Rename some key parts:
    1. The folder name
    2. The name inside the gadget.xml file. It looks like:<name>Clock</name> This is the name that will be displayed in the "Gadgets Gallery" window.
  4. Zip up the entire *.gadget directory.
  5. Change the file extension from "zip" to "gadget" (Probably just need to remove the ".zip" extension.)
  6. Install your new copy of the gadget by double clicking the new *.gadget file. You can now add your gadget like any other gadget (right click desktop->Gadgets)
  7. Locate where this gadget is installed (probably to %LOCALAPPDATA%\Microsoft\Windows Sidebar\)
  8. Modify the files in this directory. The gadget is very similar to a web page: HTML, CSS, JS, and image files. The gadget.xml file specifies which file is opened as the "index" page for the gadget.
  9. After you save the changes, view the results by installing a new instance of the gadget. You can also debug the JavaScript (The rest of that article is pretty informative, too).

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

If you are trying to take a value from the same array and trying to update it, you can use the following code.

{  'condition': { 
                     'ts': [   '5a81625ba0ff65023c729022',
                               '5a8161ada0ff65023c728f51',
                               '5a815fb4a0ff65023c728dcd']}

If the collection is userData['condition']['ts'] and we need to

    for i,supplier in enumerate(userData['condition']['ts']): 
        supplier = ObjectId(supplier)
        userData['condition']['ts'][i] = supplier

The output will be

{'condition': {   'ts': [   ObjectId('5a81625ba0ff65023c729022'),
                            ObjectId('5a8161ada0ff65023c728f51'),
                            ObjectId('5a815fb4a0ff65023c728dcd')]}

Append to the end of a Char array in C++

If your arrays are character arrays(which seems to be the case), You need a strcat().
Your destination array should have enough space to accommodate the appended data though.

In C++, You are much better off using std::string and then you can use std::string::append()

Multiple radio button groups in one form

Set equal name attributes to create a group;

_x000D_
_x000D_
<form>_x000D_
  <fieldset id="group1">_x000D_
    <input type="radio" value="value1" name="group1">_x000D_
    <input type="radio" value="value2" name="group1">_x000D_
  </fieldset>_x000D_
_x000D_
  <fieldset id="group2">_x000D_
    <input type="radio" value="value1" name="group2">_x000D_
    <input type="radio" value="value2" name="group2">_x000D_
    <input type="radio" value="value3" name="group2">_x000D_
  </fieldset>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Check whether a variable is a string in Ruby

I think you are looking for instance_of?. is_a? and kind_of? will return true for instances from derived classes.

class X < String
end

foo = X.new

foo.is_a? String         # true
foo.kind_of? String      # true
foo.instance_of? String  # false
foo.instance_of? X       # true

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

I see this topic, but in my case I was looking for a way to improve the format. Using UFormat and adding -1 day

(get-date (get-date).addDays(-1) -UFormat "%Y%m%d-%H%M")

What are all the different ways to create an object in Java?

Also, you can de-serialize data into an object. This doesn't go through the class Constructor !


UPDATED : Thanks Tom for pointing that out in your comment ! And Michael also experimented.

It goes through the constructor of the most derived non-serializable superclass.
And when that class has no no-args constructor, a InvalidClassException is thrown upon de-serialization.

Please see Tom's answer for a complete treatment of all cases ;-)
is there any other way of creating an object without using "new" keyword in java

Convert string to float?

Try this:

String yourVal = "20.5";
float a = (Float.valueOf(yourVal)).floatValue(); 
System.out.println(a);

How to parse a string to an int in C++?

You can use the a stringstream from the C++ standard libraray:

stringstream ss(str);
int x;
ss >> x;

if(ss) { // <-- error handling
  // use x
} else {
  // not a number
}

The stream state will be set to fail if a non-digit is encountered when trying to read an integer.

See Stream pitfalls for pitfalls of errorhandling and streams in C++.

What is /dev/null 2>&1?

This is the way to execute a program quietly, and hide all its output.

/dev/null is a special filesystem object that discards everything written into it. Redirecting a stream into it means hiding your program's output.

The 2>&1 part means "redirect the error stream into the output stream", so when you redirect the output stream, error stream gets redirected as well. Even if your program writes to stderr now, that output would be discarded as well.

How do I get the fragment identifier (value after hash #) from a URL?

You may do it by using following code:

var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);

SEE DEMO

How to convert xml into array in php?

XML To Array

More Details Visit https://github.com/sapankumarmohanty/lamp/blob/master/Crate-XML-2-Array

//Convert XML to array and SOAP XML to array

function xml2array($contents, $get_attributes = 1, $priority = 'tag')
    {
        if (!$contents) return array();
        if (!function_exists('xml_parser_create')) {
            // print "'xml_parser_create()' function not found!";
            return array();
        }
        // Get the XML parser of PHP - PHP must have this module for the parser to work
        $parser = xml_parser_create('');
        xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($parser, trim($contents) , $xml_values);
        xml_parser_free($parser);
        if (!$xml_values) return; //Hmm...
        // Initializations
        $xml_array = array();
        $parents = array();
        $opened_tags = array();
        $arr = array();
        $current = & $xml_array; //Refference
        // Go through the tags.
        $repeated_tag_index = array(); //Multiple tags with same name will be turned into an array
        foreach($xml_values as $data) {
            unset($attributes, $value); //Remove existing values, or there will be trouble
            // This command will extract these variables into the foreach scope
            // tag(string), type(string), level(int), attributes(array).
            extract($data); //We could use the array by itself, but this cooler.
            $result = array();
            $attributes_data = array();
            if (isset($value)) {
                if ($priority == 'tag') $result = $value;
                else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode
            }
            // Set the attributes too.
            if (isset($attributes) and $get_attributes) {
                foreach($attributes as $attr => $val) {                                   
                                    if ( $attr == 'ResStatus' ) {
                                        $current[$attr][] = $val;
                                    }
                    if ($priority == 'tag') $attributes_data[$attr] = $val;
                    else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
                }
            }
            // See tag status and do the needed.
                        //echo"<br/> Type:".$type;
            if ($type == "open") { //The starting of the tag '<tag>'
                $parent[$level - 1] = & $current;
                if (!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
                    $current[$tag] = $result;
                    if ($attributes_data) $current[$tag . '_attr'] = $attributes_data;
                                        //print_r($current[$tag . '_attr']);
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    $current = & $current[$tag];
                }
                else { //There was another element with the same tag name
                    if (isset($current[$tag][0])) { //If there is a 0th element it is already an array
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                        $repeated_tag_index[$tag . '_' . $level]++;
                    }
                    else { //This section will make the value an array if multiple tags with the same name appear together
                        $current[$tag] = array(
                            $current[$tag],
                            $result
                        ); //This will combine the existing item and the new item together to make an array
                        $repeated_tag_index[$tag . '_' . $level] = 2;
                        if (isset($current[$tag . '_attr'])) { //The attribute of the last(0th) tag must be moved as well
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                            unset($current[$tag . '_attr']);
                        }
                    }
                    $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
                    $current = & $current[$tag][$last_item_index];
                }
            }
            elseif ($type == "complete") { //Tags that ends in 1 line '<tag />'
                // See if the key is already taken.
                if (!isset($current[$tag])) { //New Key
                    $current[$tag] = $result;
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    if ($priority == 'tag' and $attributes_data) $current[$tag . '_attr'] = $attributes_data;
                }
                else { //If taken, put all things inside a list(array)
                    if (isset($current[$tag][0]) and is_array($current[$tag])) { //If it is already an array...
                        // ...push the new element into that array.
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                        if ($priority == 'tag' and $get_attributes and $attributes_data) {
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                        }
                        $repeated_tag_index[$tag . '_' . $level]++;
                    }
                    else { //If it is not an array...
                        $current[$tag] = array(
                            $current[$tag],
                            $result
                        ); //...Make it an array using using the existing value and the new value
                        $repeated_tag_index[$tag . '_' . $level] = 1;
                        if ($priority == 'tag' and $get_attributes) {
                            if (isset($current[$tag . '_attr'])) { //The attribute of the last(0th) tag must be moved as well
                                $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                                unset($current[$tag . '_attr']);
                            }
                            if ($attributes_data) {
                                $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                            }
                        }
                        $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
                    }
                }
            }
            elseif ($type == 'close') { //End of tag '</tag>'
                $current = & $parent[$level - 1];
            }
        }
        return ($xml_array);
    }
    
    // Let's call the this above function xml2array
    
    xml2array($xmlContent, $get_attributes = 3, $priority = 'tag'); // it will work 100% if not ping me @skype: sapan.mohannty
    
//  Enjoy coding

Read file-contents into a string in C++

Here's an iterator-based method.

ifstream file("file", ios::binary);
string fileStr;

istreambuf_iterator<char> inputIt(file), emptyInputIt
back_insert_iterator<string> stringInsert(fileStr);

copy(inputIt, emptyInputIt, stringInsert);

Populating a ListView using an ArrayList?

Here's an example of how you could implement a list view:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //We have our list view
    final ListView dynamic = findViewById(R.id.dynamic);

    //Create an array of elements
    final ArrayList<String> classes = new ArrayList<>();
    classes.add("Data Structures");
    classes.add("Assembly Language");
    classes.add("Calculus 3");
    classes.add("Switching Systems");
    classes.add("Analysis Tools");

    //Create adapter for ArrayList
    final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, classes);

    //Insert Adapter into List
    dynamic.setAdapter(adapter);

    //set click functionality for each list item
    dynamic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.i("User clicked ", classes.get(position));
        }
    });



}

Centering controls within a form in .NET (Winforms)?

In addition, if you want to align it to the center of another control:

//The "ctrlParent" is the one on which you want to align "ctrlToCenter".
//"ctrlParent" can be your "form name" or any other control such as "grid name" and etc.
ctrlToCenter.Parent = ctrlParent;

ctrlToCenter.Left = (ctrlToCenter.Parent.Width - ctrlToCenter.Width) / 2;
ctrlToCenter.Top = (ctrlToCenter.Parent.Height - ctrlToCenter.Height) / 2;

CodeIgniter activerecord, retrieve last insert id?

Last insert id means you can get inserted auto increment id by using this method in active record,

$this->db->insert_id() 
// it can be return insert id it is 
// similar to the mysql_insert_id in core PHP

You can refer this link you can find some more stuff.

Information from executing a query

Code to loop through all records in MS Access

In "References", import DAO 3.6 object reference.

private sub showTableData

dim db as dao.database
dim rs as dao.recordset

set db = currentDb
set rs = db.OpenRecordSet("myTable") 'myTable is a MS-Access table created previously

'populate the table
rs.movelast
rs.movefirst

do while not rs.EOF
   debug.print(rs!myField) 'myField is a field name in table myTable
   rs.movenext             'press Ctrl+G to see debuG window beneath
loop

msgbox("End of Table")

end sub

You can interate data objects like queries and filtered tables in different ways:

Trhough query:

private sub showQueryData

dim db as dao.database
dim rs as dao.recordset
dim sqlStr as string

sqlStr = "SELECT * FROM customers as c WHERE c.country='Brazil'"

set db = currentDb
set rs = db.openRecordset(sqlStr)

rs.movefirst

do while not rs.EOF
  debug.print("cust ID: " & rs!id & " cust name: " & rs!name)
  rs.movenext
loop

msgbox("End of customers from Brazil")

end sub

You should also look for "Filter" property of the recordset object to filter only the desired records and then interact with them in the same way (see VB6 Help in MS-Access code window), or create a "QueryDef" object to run a query and use it as a recordset too (a little bit more tricky). Tell me if you want another aproach.

I hope I've helped.

How to sort a collection by date in MongoDB?

Sorting by date doesn't require anything special. Just sort by the desired date field of the collection.

Updated for the 1.4.28 node.js native driver, you can sort ascending on datefield using any of the following ways:

collection.find().sort({datefield: 1}).toArray(function(err, docs) {...});
collection.find().sort('datefield', 1).toArray(function(err, docs) {...});
collection.find().sort([['datefield', 1]]).toArray(function(err, docs) {...});
collection.find({}, {sort: {datefield: 1}}).toArray(function(err, docs) {...});
collection.find({}, {sort: [['datefield', 1]]}).toArray(function(err, docs) {...});

'asc' or 'ascending' can also be used in place of the 1.

To sort descending, use 'desc', 'descending', or -1 in place of the 1.

TypeError: 'int' object is not subscriptable

sumall = summ + sumd + sumy

Your sumall is an integer. If you want the individual characters from it, convert it to a string first.

Getting "TypeError: failed to fetch" when the request hasn't actually failed

I understand this question might have a React-specific cause, but it shows up first in search results for "Typeerror: Failed to fetch" and I wanted to lay out all possible causes here.

The Fetch spec lists times when you throw a TypeError from the Fetch API: https://fetch.spec.whatwg.org/#fetch-api

Relevant passages as of January 2021 are below. These are excerpts from the text.

4.6 HTTP-network fetch

To perform an HTTP-network fetch using request with an optional credentials flag, run these steps:
...
16. Run these steps in parallel:
...
2. If aborted, then:
...
3. Otherwise, if stream is readable, error stream with a TypeError.

To append a name/value name/value pair to a Headers object (headers), run these steps:

  1. Normalize value.
  2. If name is not a name or value is not a value, then throw a TypeError.
  3. If headers’s guard is "immutable", then throw a TypeError.

Filling Headers object headers with a given object object:

To fill a Headers object headers with a given object object, run these steps:

  1. If object is a sequence, then for each header in object:
    1. If header does not contain exactly two items, then throw a TypeError.

Method steps sometimes throw TypeError:

The delete(name) method steps are:

  1. If name is not a name, then throw a TypeError.
  2. If this’s guard is "immutable", then throw a TypeError.

The get(name) method steps are:

  1. If name is not a name, then throw a TypeError.
  2. Return the result of getting name from this’s header list.

The has(name) method steps are:

  1. If name is not a name, then throw a TypeError.

The set(name, value) method steps are:

  1. Normalize value.
  2. If name is not a name or value is not a value, then throw a TypeError.
  3. If this’s guard is "immutable", then throw a TypeError.

To extract a body and a Content-Type value from object, with an optional boolean keepalive (default false), run these steps:
...
5. Switch on object:
...
ReadableStream
If keepalive is true, then throw a TypeError.
If object is disturbed or locked, then throw a TypeError.

In the section "Body mixin" if you are using FormData there are several ways to throw a TypeError. I haven't listed them here because it would make this answer very long. Relevant passages: https://fetch.spec.whatwg.org/#body-mixin

In the section "Request Class" the new Request(input, init) constructor is a minefield of potential TypeErrors:

The new Request(input, init) constructor steps are:
...
6. If input is a string, then:
...
2. If parsedURL is a failure, then throw a TypeError.
3. IF parsedURL includes credentials, then throw a TypeError.
...
11. If init["window"] exists and is non-null, then throw a TypeError.
...
15. If init["referrer" exists, then:
...
1. Let referrer be init["referrer"].
2. If referrer is the empty string, then set request’s referrer to "no-referrer".
3. Otherwise:
1. Let parsedReferrer be the result of parsing referrer with baseURL.
2. If parsedReferrer is failure, then throw a TypeError.
...
18. If mode is "navigate", then throw a TypeError.
...
23. If request's cache mode is "only-if-cached" and request's mode is not "same-origin" then throw a TypeError.
...
27. If init["method"] exists, then:
...
2. If method is not a method or method is a forbidden method, then throw a TypeError.
...
32. If this’s request’s mode is "no-cors", then:
1. If this’s request’s method is not a CORS-safelisted method, then throw a TypeError.
...
35. If either init["body"] exists and is non-null or inputBody is non-null, and request’s method is GET or HEAD, then throw a TypeError.
...
38. If body is non-null and body's source is null, then:
1. If this’s request’s mode is neither "same-origin" nor "cors", then throw a TypeError.
...
39. If inputBody is body and input is disturbed or locked, then throw a TypeError.

The clone() method steps are:

  1. If this is disturbed or locked, then throw a TypeError.

In the Response class:

The new Response(body, init) constructor steps are:
...
2. If init["statusText"] does not match the reason-phrase token production, then throw a TypeError.
...
8. If body is non-null, then:
1. If init["status"] is a null body status, then throw a TypeError.
...

The static redirect(url, status) method steps are:
...
2. If parsedURL is failure, then throw a TypeError.

The clone() method steps are:

  1. If this is disturbed or locked, then throw a TypeError.

In section "The Fetch method"

The fetch(input, init) method steps are:
...
9. Run the following in parallel:
To process response for response, run these substeps:
...
3. If response is a network error, then reject p with a TypeError and terminate these substeps.

In addition to these potential problems, there are some browser-specific behaviors which can throw a TypeError. For instance, if you set keepalive to true and have a payload > 64 KB you'll get a TypeError on Chrome, but the same request can work in Firefox. These behaviors aren't documented in the spec, but you can find information about them by Googling for limitations for each option you're setting in fetch.

Can HTML be embedded inside PHP "if" statement?

I know this is an old post, but I really hate that there is only one answer here that suggests not mixing html and php. Instead of mixing content one should use template systems, or create a basic template system themselves.

In the php

<?php 
  $var1 = 'Alice'; $var2 = 'apples'; $var3 = 'lunch'; $var4 = 'Bob';

  if ($var1 == 'Alice') {
    $html = file_get_contents('/path/to/file.html'); //get the html template
    $template_placeholders = array('##variable1##', '##variable2##', '##variable3##', '##variable4##'); // variable placeholders inside the template
    $template_replace_variables = array($var1, $var2, $var3, $var4); // the variables to pass to the template
    $html_output = str_replace($template_placeholders, $template_replace_variables, $html); // replace the placeholders with the actual variable values.
  }

  echo $html_output;
?>

In the html (/path/to/file.html)

<p>##variable1## ate ##variable2## for ##variable3## with ##variable4##.</p>

The output of this would be:

Alice ate apples for lunch with Bob.

Git: copy all files in a directory from another branch

If there are no spaces in paths, and you are interested, like I was, in files of specific extension only, you can use

git checkout otherBranch -- $(git ls-tree --name-only -r otherBranch | egrep '*.java')

How to get JSON objects value if its name contains dots?

in javascript, object properties can be accessed with . operator or with associative array indexing using []. ie. object.property is equivalent to object["property"]

this should do the trick

var smth = mydata.list[0]["points.bean.pointsBase"][0].time;

Where can I find error log files?

I am using Cent OS 6.6 with Apache and for me error log files are in

/usr/local/apache/log

How to position a div in bottom right corner of a browser?

I don't have IE8 to test this out, but I'm pretty sure it should work:

<div class="screen">
   <!-- code -->
   <div class="innerdiv">
      text or other content
   </div>
</div>

and the css:

.screen{
position: relative;
}
.innerdiv {
position: absolute;
bottom: 0;
right: 0;
}

This should place the .innerdiv in the bottom-right corner of the .screen class. I hope this helps :)

Best way to return a value from a python script

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

Return values (from a wrapping-function)

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

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

Exit codes as indicators

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

import sys
# calculate and stuff
sys.exit(100)

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

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

Stdout as your relay

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

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

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

Files as conveyors

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

# calculate
with open('finish.txt', 'wb') as fh:
    fh.write(str(5)+'\n')

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

Sockets as conveyors

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

How to get everything after last slash in a URL?

urlparse is fine to use if you want to (say, to get rid of any query string parameters).

import urllib.parse

urls = [
    'http://www.test.com/TEST1',
    'http://www.test.com/page/TEST2',
    'http://www.test.com/page/page/12345',
    'http://www.test.com/page/page/12345?abc=123'
]

for i in urls:
    url_parts = urllib.parse.urlparse(i)
    path_parts = url_parts[2].rpartition('/')
    print('URL: {}\nreturns: {}\n'.format(i, path_parts[2]))

Output:

URL: http://www.test.com/TEST1
returns: TEST1

URL: http://www.test.com/page/TEST2
returns: TEST2

URL: http://www.test.com/page/page/12345
returns: 12345

URL: http://www.test.com/page/page/12345?abc=123
returns: 12345

Close Bootstrap Modal

In my case, main page from where bootstrap modal was triggered started to not responding after using $("#modal").modal('toggle'); way, but started responding in the following way:

$("#submitBtn").on("click",function(){
  $("#submitBtn").attr("data-dismiss","modal");
});

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

You can make use of ::marker pseudo element. This is useful in situations when you need to have different character entities for each list item.

ul li::marker {
  content: " "; /* Your symbol here */
}

_x000D_
_x000D_
ul li:nth-child(1)::marker {
  content: "\26BD   ";
}

ul li:nth-child(2)::marker {
  content: "\26C5   ";
}

ul li:nth-child(3)::marker {
  content: "\26F3   ";
}

ul li::marker {
  font-size: 20px;
}

ul li {
  margin: 15px 0;
  font-family: sans-serif;
  background: #BADA55;
  color: black;
  padding-bottom: 10px;
  padding-left: 10px;
  padding-top: 5px;
}
_x000D_
<ul>
  <li>France Vs Croatia</li>
  <li>Cloudy with sunshine</li>
  <li>Golf session ahead</li>
</ul>
_x000D_
_x000D_
_x000D_

Tick symbol in HTML/XHTML

The client machine needs a proper font that has a glyph for this character to display it. But Times New Roman doesn’t. Try Arial Unicode MS or Lucida Grande instead:

<span style="font-family: Arial Unicode MS, Lucida Grande">
    &#10003; &#10004;
</span>

This works for me on Windows XP in IE 5.5, IE 6.0, FF 3.0.6.

Accessing JSON elements

Just for more one option...You can do it this way too:

MYJSON = {
    'username': 'gula_gut',
    'pics': '/0/myfavourite.jpeg',
    'id': '1'
}

#changing username
MYJSON['username'] = 'calixto'
print(MYJSON['username'])

I hope this can help.

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

There are a couple of things you could look at. Based on your question, it looks like the function owner is different from the table owner.

1) Grants via a role : In order to create stored procedures and functions on another user's objects, you need direct access to the objects (instead of access through a role).

2)

By default, stored procedures and SQL methods execute with the privileges of their owner, not their current user.

If you created a table in Schema A and the function in Schema B, you should take a look at Oracle's Invoker/Definer Rights concepts to understand what might be causing the issue.

http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/subprograms.htm#LNPLS00809

How to generate classes from wsdl using Maven and wsimport?

Even though this is bit late response, may be helpful for someone. Look like you have used pluginManagement. If you use pluginManagement , it will not pick the plug-in execution.

It should be under

<build>
<plugins>           
        <plugin> 

npm not working - "read ECONNRESET"

If you're using Windows you should follow up on Advanced System Settings to check the env vars declared over there, you should notice that the proxy configuration may lie within environment variables, like in the picture below:

Windows env vars

So if your proxy server is not available or is blocking traffic from npm you might notice the aforementioned error in this topic. Maybe you don't need any proxy at all, in this case, just remove this HTTP_PROXY env variables.

I had turned all proxy configurations off in my Windows and npm settings, however, npm was still getting timeout and connection errors while downloading resources, then I figured out there was still a proxy configuration left on env variables, which was causing all the trouble.

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

Got the same problem, to save the data with utf8mb4 needs to make sure:

  1. character_set_client, character_set_connection, character_set_results are utf8mb4: character_set_client and character_set_connection indicate the character set in which statements are sent by the client, character_set_results indicates the character set in which the server returns query results to the client.
    See charset-connection.

  2. the table and column encoding is utf8mb4

For JDBC, there are two solutions:

Solution 1 (need to restart MySQL):

  1. modify my.cnf like the following and restart MySQL:

    [mysql]
    default-character-set=utf8mb4
    
    [mysqld]
    character-set-server=utf8mb4
    collation-server=utf8mb4_unicode_ci
    

this can make sure the database and character_set_client, character_set_connection, character_set_results are utf8mb4 by default.

  1. restart MySQL

  2. change the table and column encoding to utf8mb4

  3. STOP specifying characterEncoding=UTF-8 and characterSetResults=UTF-8 in the jdbc connector,cause this will override character_set_client, character_set_connection, character_set_results to utf8

Solution two (don't need to restart MySQL):

  1. change the table and column encoding to utf8mb4

  2. specifying characterEncoding=UTF-8 in the jdbc connector,cause the jdbc connector doesn't suport utf8mb4.

  3. write your sql statment like this (need to add allowMultiQueries=true to jdbc connector):

    'SET NAMES utf8mb4;INSERT INTO Mytable ...';
    

this will make sure each connection to the server, character_set_client,character_set_connection,character_set_results are utf8mb4.
Also see charset-connection.

How to change navigation bar color in iOS 7 or 6?

    you can add bellow code in appdelegate.m .if your app is navigation based

    // for background color
   [nav.navigationBar setBarTintColor:[UIColor blueColor]];

    // for change navigation title and button color
    [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],
    NSForegroundColorAttributeName,               
    [UIFont fontWithName:@"FontNAme" size:20],
    NSFontAttributeName, nil]];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

How many socket connections can a web server handle?

Note that HTTP doesn't typically keep TCP connections open for any longer than it takes to transmit the page to the client; and it usually takes much more time for the user to read a web page than it takes to download the page... while the user is viewing the page, he adds no load to the server at all.

So the number of people that can be simultaneously viewing your web site is much larger than the number of TCP connections that it can simultaneously serve.

FPDF utf-8 encoding (HOW-TO)

Don't use UTF-8 encoding. Standard FPDF fonts use ISO-8859-1 or Windows-1252. It is possible to perform a conversion to ISO-8859-1 with utf8_decode(): $str = utf8_decode($str); But some characters such as Euro won't be translated correctly. If the iconv extension is available, the right way to do it is the following: $str = iconv('UTF-8', 'windows-1252', $str);

How do I obtain crash-data from my Android application?

While many of the answers on this page are useful, it is easy for them to become out of date. The AppBrain website aggregates statistics which allow you to find the most popular crash reporting solution that is current:

Android crash reporting libraries

app brain website

You can see that at the time of posting this picture, Crashlytics is used in 5.24% of apps and 12.38% of installs.

Vuex - passing multiple parameters to mutation

In simple terms you need to build your payload into a key array

payload = {'key1': 'value1', 'key2': 'value2'}

Then send the payload directly to the action

this.$store.dispatch('yourAction', payload)

No change in your action

yourAction: ({commit}, payload) => {
  commit('YOUR_MUTATION',  payload )
},

In your mutation call the values with the key

'YOUR_MUTATION' (state,  payload ){
  state.state1 = payload.key1
  state.state2 =  payload.key2
},

Absolute position of an element on the screen using jQuery

BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:

function getOffsetTop (el) {
    if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
    return el.offsetTop || 0
}
function getOffsetLeft (el) {
    if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
    return el.offsetleft || 0
}
function coordinates(el) {
    var y1 = getOffsetTop(el) - window.scrollY;
    var x1 = getOffsetLeft(el) - window.scrollX; 
    var y2 = y1 + el.offsetHeight;
    var x2 = x1 + el.offsetWidth;
    return {
        x1: x1, x2: x2, y1: y1, y2: y2
    }
}

How to disassemble a memory range with GDB?

You can force gcc to output directly to assembly code by adding the -S switch

gcc -S hello.c

What is the SQL command to return the field names of a table?

For those looking for an answer in Oracle:

SELECT column_name FROM user_tab_columns WHERE table_name = 'TABLENAME'

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

How to change indentation mode in Atom?

Adding @Manbroski answer here that worked for me:

try Ctrl-Shift-P Editor: Toggle Soft Tabs

How to view the stored procedure code in SQL Server Management Studio

exec sp_helptext 'your_sp_name' -- don't forget the quotes

In management studio by default results come in grid view. If you would like to see it in text view go to:

Query --> Results to --> Results to Text

or CTRL + T and then Execute.

What is SYSNAME data type in SQL Server?

Another use case is when using the SQL Server 2016+ functionality of AT TIME ZONE

The below statement will return a date converted to GMT

SELECT 
CONVERT(DATETIME, SWITCHOFFSET([ColumnA], DATEPART(TZOFFSET, [ColumnA] AT TIME ZONE 'GMT Standard Time')))

If you want to pass the time zone as a variable, say:

SELECT 
CONVERT(DATETIME, SWITCHOFFSET([ColumnA], DATEPART(TZOFFSET, [ColumnA] AT TIME ZONE @TimeZone)))

then that variable needs to be of the type sysname (declaring it as varchar will cause an error).

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

An easy approach is to leverage this code:

<a href="javascript:void(0);">Link Title</a>

This approach doesn't force a page refresh, so the scrollbar stays in place. Also, it allows you to programmatically change the onclick event and handle client side event binding using jQuery.

For these reasons, the above solution is better than:

<a href="javascript:myClickHandler();">Link Title</a>
<a href="#" onclick="myClickHandler(); return false;">Link Title</a>

where the last solution will avoid the scroll-jump issue if and only if the myClickHandler method doesn't fail.

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

I had this issue today which was solved by selecting Product -> Clean. I was so confused since my code was proper. The problem started from using command-Z too many times :)

JavaScript string and number conversion

parseInt is misfeatured like scanf:

parseInt("12 monkeys", 10) is a number with value '12'
+"12 monkeys"              is a number with value 'NaN'
Number("12 monkeys")       is a number with value 'NaN'

Recursively list files in Java

With Java 7 you can use the following class:

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class MyFileIterator extends SimpleFileVisitor<Path>
{
    public MyFileIterator(String path) throws Exception
    {
        Files.walkFileTree(Paths.get(path), this);
    }

    @Override
    public FileVisitResult visitFile(Path file,
            BasicFileAttributes attributes) throws IOException
    {
        System.out.println("File: " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult preVisitDirectory(Path dir,
            BasicFileAttributes attributes) throws IOException
    {
        System.out.println("Dir: " + dir);
        return FileVisitResult.CONTINUE;
    }
}

How to select the first element with a specific attribute using XPath

if namespace is provided on the given xml, its better to use this.

(/*[local-name() ='bookstore']/*[local-name()='book'][@location='US'])[1]

How do I perform a JAVA callback between classes?

In this particular case, the following should work:

serverConnectionHandler = new ServerConnections(_address) {
    public void newConnection(Socket _socket) {
        System.out.println("A function of my child class was called.");
    }
};

It's an anonymous subclass.

How to scroll HTML page to given anchor?

Smoothly scroll to the proper position (2019)

Get correct y coordinate and use window.scrollTo({top: y, behavior: 'smooth'})

const id = 'anchorName2';
const yourElement = document.getElementById(id);
const y = yourElement.getBoundingClientRect().top + window.pageYOffset;

window.scrollTo({top: y, behavior: 'smooth'});

With offset

scrollIntoView is a good option too but it may not works perfectly in some cases. For example when you need additional offset. With scrollTo you just need to add that offset like this:

const yOffset = -10; 

window.scrollTo({top: y + yOffset, behavior: 'smooth'});

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

Use getElementById on HTMLElement instead of HTMLDocument

Sub Scrape()
    Dim Browser As InternetExplorer
    Dim Document As htmlDocument
    Dim Elements As IHTMLElementCollection
    Dim Element As IHTMLElement

    Set Browser = New InternetExplorer
    Browser.Visible = True
    Browser.navigate "http://www.stackoverflow.com"

    Do While Browser.Busy And Not Browser.readyState = READYSTATE_COMPLETE
        DoEvents
    Loop

    Set Document = Browser.Document

    Set Elements = Document.getElementById("hmenus").getElementsByTagName("li")
    For Each Element In Elements
        Debug.Print Element.innerText
        'Questions
        'Tags
        'Users
        'Badges
        'Unanswered
        'Ask Question
    Next Element

    Set Document = Nothing
    Set Browser = Nothing
End Sub

What is aria-label and how should I use it?

It's an attribute designed to help assistive technology (e.g. screen readers) attach a label to an otherwise anonymous HTML element.

So there's the <label> element:

<label for="fmUserName">Your name</label>
<input id="fmUserName">

The <label> explicitly tells the user to type their name into the input box where id="fmUserName".

aria-label does much the same thing, but it's for those cases where it isn't practical or desirable to have a label on screen. Take the MDN example:

<button aria-label="Close" onclick="myDialog.close()">X</button>`

Most people would be able to infer visually that this button will close the dialog. A blind person using assistive technology might just hear "X" read aloud, which doesn't mean much without the visual clues. aria-label explicitly tells them what the button will do.

Git: can't undo local changes (error: path ... is unmerged)

git checkout foo/bar.txt

did you tried that? (without a HEAD keyword)

I usually revert my changes this way.

KeyListener, keyPressed versus keyTyped

private String message;
private ScreenManager s;


//Here is an example of code to add the keyListener() as suggested; modify 
public void init(){
Window w = s.getFullScreenWindow();
w.addKeyListener(this);

public void keyPressed(KeyEvent e){
    int keyCode = e.getKeyCode();
        if(keyCode == KeyEvent.VK_F5)
            message = "Pressed: " + KeyEvent.getKeyText(keyCode);
}

Using moment.js to convert date to string "MM/dd/yyyy"

this also might be relevant to anyone using React -

install react-moment (npm i react-moment)

import Moment from 'react-moment'


<Moment format="MM/DD/YYYY">{yourTimeStamp}</Moment>

(or any other format you'd like)

Apache Tomcat :java.net.ConnectException: Connection refused

you can try to stop and start again with :

$ cd /path/apache-tomcat x.x.x/bin

then

$ sh shutdown.sh

when succesfully done the last step you must turn on your tomcat and catalina with command

$ sh startup.sh

I managed to resolve my problem with this way

JavaFX: How to get stage from controller during initialization?

Assign fx:id or declare variable to/of any node: anchorpane, button, etc. Then add event handler to it and within that event handler insert the given code below:

Stage stage = (Stage)((Node)((EventObject) eventVariable).getSource()).getScene().getWindow();

Hope, this works for you!!

Where to place JavaScript in an HTML file?

I would say that it depends of fact what do you planed to achieve with Javascript code:

  • if you planned to insert external your JS script(s), then the best place is in head of the page
  • if you planed to use pages on smartphones, then bottom of page, just before tag.
  • but, if you planned to make combination HTML and JS (dynamically created and populated HTML table, for example) then you must put it where you need it there.

How can I delete a query string parameter in JavaScript?

const params = new URLSearchParams(location.search)
params.delete('key_to_delete')
console.log(params.toString())

javascript: Disable Text Select

Just use this css method:

body{
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

You can find the same answer here: How to disable text selection highlighting using CSS?

Loop through a date range with JavaScript

Here simple working code, worked for me

_x000D_
_x000D_
var from = new Date(2012,0,1);_x000D_
var to = new Date(2012,1,20);_x000D_
    _x000D_
// loop for every day_x000D_
for (var day = from; day <= to; day.setDate(day.getDate() + 1)) {_x000D_
      _x000D_
   // your day is here_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

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

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

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

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

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

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

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

Java: Literal percent sign in printf statement

Escaped percent sign is double percent (%%):

System.out.printf("2 out of 10 is %d%%", 20);

When do I need to use AtomicBoolean in Java?

The AtomicBoolean class gives you a boolean value that you can update atomically. Use it when you have multiple threads accessing a boolean variable.

The java.util.concurrent.atomic package overview gives you a good high-level description of what the classes in this package do and when to use them. I'd also recommend the book Java Concurrency in Practice by Brian Goetz.

SQL Error: ORA-00922: missing or invalid option

You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ..., it's not recommended. Take a closer look here

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

If anyone struggle with that problem using docker + nginx, it could be permissions. Nginx logs shown error:

2019/12/16 08:54:58 [crit] 6#6: *23 open() "/var/tmp/nginx/fastcgi/4/00/0000000004" failed (13: Permission denied) while reading upstream, client: 172.24.0.2, server: test.loc, request: "GET /login HTTP/1.1", upstream: "fastcgi://172.28.0.2:9001", host: "test.loc"

Run inside nginx container(path might vary):

chown -R www-data:www-data /var/tmp/nginx/

How to call a JavaScript function, declared in <head>, in the body when I want to call it

You can also put the JavaScript code in script tags, rather than a separate function. <script>//JS Code</script> This way the code will get executes on Page Load.

Rename a file using Java

In short:

Files.move(source, source.resolveSibling("newname"));

More detail:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

The following is copied directly from http://docs.oracle.com/javase/7/docs/api/index.html:

Suppose we want to rename a file to "newname", keeping the file in the same directory:

Path source = Paths.get("path/here");
Files.move(source, source.resolveSibling("newname"));

Alternatively, suppose we want to move a file to new directory, keeping the same file name, and replacing any existing file of that name in the directory:

Path source = Paths.get("from/path");
Path newdir = Paths.get("to/path");
Files.move(source, newdir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING);

Elasticsearch difference between MUST and SHOULD bool query

must means: The clause (query) must appear in matching documents. These clauses must match, like logical AND.

should means: At least one of these clauses must match, like logical OR.

Basically they are used like logical operators AND and OR. See this.

Now in a bool query:

must means: Clauses that must match for the document to be included.

should means: If these clauses match, they increase the _score; otherwise, they have no effect. They are simply used to refine the relevance score for each document.


Yes you can use multiple filters inside must.

How do I print out the contents of a vector?

You can use an iterator:

std::vector<char> path;
// ...
for (std::vector<char>::const_iterator i = path.begin(); i != path.end(); ++i)
    std::cout << *i << ' ';

If you want to modify the vector's contents in the for loop, then use iterator rather than const_iterator.

But there's lots more that can be said about this. If you just want an answer you can use, then you can stop here; otherwise, read on.

auto (C++11) / typedef / type alias (C++11)

This is not another solution, but a supplement to the above iterator solution. If you are using the C++11 standard (or later), then you can use the auto keyword to help the readability:

for (auto i = path.begin(); i != path.end(); ++i)
    std::cout << *i << ' ';

But the type of i will be non-const (i.e., the compiler will use std::vector<char>::iterator as the type of i).

In this case, you might as well just use a typedef, which also brings with it its own benefits (which I won't expound upon here):

typedef std::vector<char> Path; // 'Path' now a synonym for the vector
Path path;
// ...
for (Path::const_iterator i = path.begin(); i != path.end(); ++i)
    std::cout << *i << ' ';

C++11 also introduced a type alias, which does the same job as a typedef and you may find more readable than using typedef:

using Path = std::vector<char>; // C++11 onwards only
Path path;
// ...
for (Path::const_iterator i = path.begin(); i != path.end(); ++i)
    std::cout << *i << ' ';

counter

You can, of course, use a integer type to record your position in the for loop:

for(int i=0; i<path.size(); ++i)
  std::cout << path[i] << ' ';

If you are going to do this, it's better to use the container's member types, if they are available and appropriate. std::vector has a member type called size_type for this job: it is the type returned by the size method.

// Path typedef'd to std::vector<char>
for( Path::size_type i=0; i<path.size(); ++i)
  std::cout << path[i] << ' ';

Why not just use this over the iterator solution? For simple cases you might as well, but the point is that an iterator is an object designed to do this job for more complicated objects where this solution is not going to be ideal.

range-based for loop (C++11)

See Jefffrey's solution. In C++11 (and later) you can use the new range-based for loop, which looks like this:

for (auto i: path)
  std::cout << i << ' ';

Since path is a vector of items (explicitly std::vector<char>), the object i is of type of the item of the vector (i.e., explicitly, it is of type char). The object i has a value that is a copy of the actual item in the path object. Thus, all changes to i in the loop are not preserved in path itself. Additionally, if you would like to enforce the fact that you don't want to be able to change the copied value of i in the loop, you can force the type of i to be const char like this:

for (const auto i: path)
  std::cout << i << ' ';

If you would like to modify the items in path, you can use a reference:

for (auto& i: path)
  std::cout << i << ' ';

and even if you don't want to modify path, if the copying of objects is expensive you should use a const reference instead of copying by value:

for (const auto& i: path)
  std::cout << i << ' ';

std::copy (C++11)

See Joshua's answer. You can use the STL algorithm std::copy to copy the vector contents onto the output stream. This is an elegant solution if you are comfortable with it. Getting more familiar with STL algorithms should be encouraged, and they provide a lot of functionality that beginners may fall into reinventing themselves. Read Joshua's post for more info.

overload std::ostream::operator<<

See Chris's answer, this is more a complement to the other answers since you will still need to implement one of the solutions above in the overloading. In his example he used a counter in a for loop. For example, this is how you could quickly use Joshua's solution:

#include <iterator> // needed for std::ostram_iterator

template <typename T>
std::ostream& operator<< (std::ostream& out, const std::vector<T>& v) {
  if ( !v.empty() ) {
    out << '[';
    std::copy (v.begin(), v.end(), std::ostream_iterator<T>(out, ", "));
    out << "\b\b]";
  }
  return out;
}

Using any of the other solutions should be equally straightforward.

conclusion

Any of the solutions presented here will work. It's up to you and the code on which one is the "best". Anything more detailed than this is probably best left for another question where the pros/cons can be properly evaluated; but as always user preference will always play a part: none of the solutions presented are wrong, but some will look nicer to each individual coder.

addendum

This is an expanded solution of an earlier one I posted. Since that post kept getting attention, I decided to expand on it and refer to the other excellent solutions that were posted here. My original post had a remark that mentioned that if you were intending on modifying your vector inside a for loop then there are two methods provided by std::vector to access elements: std::vector::operator[] which does not do bounds checking, and std::vector::at which does perform bounds checking. In other words, at will throw if you try to access an element outside the vector and operator[] wouldn't. I only added this comment, originally, for the sake of mentioning something that it might be useful to know of if anyone already didn't. And I see no difference now. Hence this addendum.

Cannot install packages inside docker Ubuntu image

Make sure you don't have any syntax errors in your Dockerfile as this can cause this error as well. A correct example is:

RUN apt-get update \
    && apt-get -y install curl \
    another-package

It was a combination of fixing a syntax error and adding apt-get update that solved the problem for me.

How to check if directory exist using C++ and winAPI

This code might work:

//if the directory exists
 DWORD dwAttr = GetFileAttributes(str);
 if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) 

Determine what attributes were changed in Rails after_save callback?

you can add a condition to the after_update like so:

class SomeModel < ActiveRecord::Base
  after_update :send_notification, if: :published_changed?

  ...
end

there's no need to add a condition within the send_notification method itself.

How to make HTML code inactive with comments

Reason of comments:

  1. Comment out elements temporarily rather than removing them, especially if they've been left unfinished.
  2. Write notes or reminders to yourself inside your actual HTML documents.
  3. Create notes for other scripting languages like JavaScript which requires them

HTML Comments

<!-- Everything is invisible  -->

Installing Pandas on Mac OSX

You need to install XCode AND you need to make sure you install the command line tools for XCode so you can get gcc.

What is IPV6 for localhost and 0.0.0.0?

IPv6 localhost

::1 is the loopback address in IPv6.

Within URLs

Within a URL, use square brackets []:

  • http://[::1]/
    Defaults to port 80.
  • http://[::1]:80/
    Specify port.

Enclosing the IPv6 literal in square brackets for use in a URL is defined in RFC 2732 – Format for Literal IPv6 Addresses in URL's.

Apache is downloading php files instead of displaying them

This might be happening due to the missing modules required for your php. Assuming you have php7 installed, search available php7 modules using

sudo apt-cache search php7-*

Above command will list all available PHP7 modules for installation. You can begin installation of modules like,

sudo apt-get install libapache2-mod-php7.0 php7.0-mysql php7.0-curl php7.0-json

Edit a text file on the console using Powershell

If you use Windows container and you want change any file, you can get and use Vim in Powershell console easily.

To shelled to the Windows Docker container with PowerShell:

docker exec -it <name> powershell

  • First get Chocolatey package manager

    Invoke-WebRequest https://chocolatey.org/install.ps1 -UseBasicParsing | Invoke-Expression;

  • Install Vim

    choco install vim

  • Refresh ENVIRONMENTAL VARIABLE You can just exit and shell back to the container

  • Go to file location and Vim it vim file.txt

'React' must be in scope when using JSX react/react-in-jsx-scope?

For those who still don't get the accepted solution :

Add

import React from 'react'
import ReactDOM from 'react-dom'

at the top of the file.

How do I set a textbox's value using an anchor with jQuery?

Following redsquare: You should not use in href attribute javascript code like "javascript:void();" - it is wrong. Better use for example href="#" and then in Your event handler as a last command: "return false;". And even better - use in href correct link - if user have javascript disabled, web browser follows the link - in this case Your webpage should reload with input filled with value of that link.

How to convert unsigned long to string

const int n = snprintf(NULL, 0, "%lu", ulong_value);
assert(n > 0);
char buf[n+1];
int c = snprintf(buf, n+1, "%lu", ulong_value);
assert(buf[n] == '\0');
assert(c == n);

git stash apply version

To view your recent work and what branch it happened on run

git stash list

then select the stash to apply and use only number:

git stash apply n

Where n (in the above sample) is that number corresponding to the Work In Progress.

Run chrome in fullscreen mode on Windows

  • Right click the Google Chrome icon and select Properties.
  • Copy the value of Target, for example: "C:\Users\zero\AppData\Local\Google\Chrome\Application\chrome.exe".
  • Create a shortcut on your Desktop.
  • Paste the value into Location of the item, and append --kiosk <your url>:

    "C:\Users\zero\AppData\Local\Google\Chrome\Application\chrome.exe" --kiosk http://www.google.com
    
  • Press Apply, then OK.

  • To start Chrome at Windows startup, copy this shortcut and paste it into the Startup folder (Start -> Program -> Startup).

asp.net Button OnClick event not firing

Try to Clean your solution and then try once again.

It will definitely work. Because every thing in code seems to be ok.

Go through this link for cleaning solution>

http://social.msdn.microsoft.com/Forums/en-US/vsdebug/thread/e53aab69-75b9-434a-bde3-74ca0865c165/

How can I process each letter of text using Javascript?

short answer: Array.from(string) will give you what you probably want and then you can iterate on it or whatever since it's just an array.

ok let's try it with this string: abc|??\n??|???.

codepoints are:

97
98
99
124
9899, 65039
10
9898, 65039
124
128104, 8205, 128105, 8205, 128103, 8205, 128103

so some characters have one codepoint (byte) and some have two or more, and a newline added for extra testing.

so after testing there are two ways:

  • byte per byte (codepoint per codepoint)
  • character groups (but not the whole family emoji)

_x000D_
_x000D_
string = "abc|??\n??|???"_x000D_
_x000D_
console.log({ 'string': string }) // abc|??\n??|???_x000D_
console.log({ 'string.length': string.length }) // 21_x000D_
_x000D_
for (let i = 0; i < string.length; i += 1) {_x000D_
  console.log({ 'string[i]': string[i] }) // byte per byte_x000D_
  console.log({ 'string.charAt(i)': string.charAt(i) }) // byte per byte_x000D_
}_x000D_
_x000D_
for (let char of string) {_x000D_
  console.log({ 'for char of string': char }) // character groups_x000D_
}_x000D_
_x000D_
for (let char in string) {_x000D_
  console.log({ 'for char in string': char }) // index of byte per byte_x000D_
}_x000D_
_x000D_
string.replace(/./g, (char) => {_x000D_
  console.log({ 'string.replace(/./g, ...)': char }) // byte per byte_x000D_
});_x000D_
_x000D_
string.replace(/[\S\s]/g, (char) => {_x000D_
  console.log({ 'string.replace(/[\S\s]/g, ...)': char }) // byte per byte_x000D_
});_x000D_
_x000D_
[...string].forEach((char) => {_x000D_
  console.log({ "[...string].forEach": char }) // character groups_x000D_
})_x000D_
_x000D_
string.split('').forEach((char) => {_x000D_
  console.log({ "string.split('').forEach": char }) // byte per byte_x000D_
})_x000D_
_x000D_
Array.from(string).forEach((char) => {_x000D_
  console.log({ "Array.from(string).forEach": char }) // character groups_x000D_
})_x000D_
_x000D_
Array.prototype.map.call(string, (char) => {_x000D_
  console.log({ "Array.prototype.map.call(string, ...)": char }) // byte per byte_x000D_
})_x000D_
_x000D_
var regexp = /(?:[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g_x000D_
_x000D_
string.replace(regexp, (char) => {_x000D_
  console.log({ 'str.replace(regexp, ...)': char }) // character groups_x000D_
});
_x000D_
_x000D_
_x000D_

IndentationError: unexpected unindent WHY?

@MaxPython The answer above is missing ":"

try:
   #do something
except:
  # print 'error/exception'

def printError(e): print e

Can we instantiate an abstract class directly?

According to others said, you cannot instantiate from abstract class. but it exist 2 way to use it. 1. make another non-abstact class that extends from abstract class. So you can instantiate from new class and use the attributes and methods in abstract class.

    public class MyCustomClass extends YourAbstractClass {

/// attributes, methods ,...
}
  1. work with interfaces.

How to print binary number via printf

Although ANSI C does not have this mechanism, it is possible to use itoa() as a shortcut:

  char buffer [33];
  itoa (i,buffer,2);
  printf ("binary: %s\n",buffer);

Here's the origin:

itoa in cplusplus reference

It is non-standard C, but K&R mentioned the implementation in the C book, so it should be quite common. It should be in stdlib.h.

How to SUM parts of a column which have same text value in different column in the same row

If your data has the names grouped as shown then you can use this formula in D2 copied down to get a total against the last entry for each name

=IF((A2=A3)*(B2=B3),"",SUM(C$2:C2)-SUM(D$1:D1))

See screenshot

enter image description here

Remove the last character in a string in T-SQL?

declare @x varchar(20),@y varchar(20)
select @x='sam'
select 
case when @x is null then @y
      when @y is null then @x
      else @x+','+@y
end


go

declare @x varchar(20),@y varchar(20)
select @x='sam'
--,@y='john'
DECLARE @listStr VARCHAR(MAX)   

SELECT @listStr = COALESCE(@x + ', ' ,'') +coalesce(@y+',','')
SELECT left(@listStr,len(@listStr)-1)

XAMPP permissions on Mac OS X?

If you are running your page on the new XAMPP-VM version of MacOS you will have to set daemon as user and as group. Here you can find a great step-by-step illustration with screenshots from aXfon on how to do this.

As the htdocs folder under XAMPP-VM will be mounted as external volume, you'll have to do this as root of the mounted volume (root@debian). This can be achieved through the XAMPP-VM GUI: See screenshot.

Once you are running as root of the mounted volume you can as described above change the file permission using:

chown -R daemon:daemon /opt/lampp/htdocs/FOLDER_OF_YOUR_PAGE

Source (w/ step-by-step illustration): aXfon

File count from a folder

System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("SourcePath");
int count = dir.GetFiles().Length;

You can use this.

MySQL remove all whitespaces from the entire column

Just use the following sql, you are done:

SELECT replace(CustomerName,' ', '') FROM Customers;

you can test this sample over here: W3School

How to inherit constructors?

No, you don't need to copy all 387 constructors to Bar and Bah. Bar and Bah can have as many or as few constructors as you want independent of how many you define on Foo. For example, you could choose to have just one Bar constructor which constructs Foo with Foo's 212th constructor.

Yes, any constructors you change in Foo that Bar or Bah depend on will require you to modify Bar and Bah accordingly.

No, there is no way in .NET to inherit constructors. But you can achieve code reuse by calling a base class's constructor inside the subclass's constructor or by calling a virtual method you define (like Initialize()).

How to clear variables in ipython?

Apart from the methods mentioned earlier. You can also use the command del to remove multiple variables

del variable1,variable2

How to query DATETIME field using only date in Microsoft SQL Server?

You can use this approach which truncates the time part:

select * from test
where convert(datetime,'03/19/2014',102) = DATEADD(dd, DATEDIFF(dd, 0, date), 0)

Attaching click event to a JQuery object not yet added to the DOM

Use this. You can replace body with any parent element that exists on dom ready

$('body').on('click', '#my-button', function () {
     console.log("yeahhhh!!! but this doesn't work for me :(");
});

Look here http://api.jquery.com/on/ for more info on how to use on() as it replaces live() as of 1.7+.

Below lists which version you should be using

$(selector).live(events, data, handler); // jQuery 1.3+

$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+

$(document).on(events, selector, data, handler); // jQuery 1.7+

Command line .cmd/.bat script, how to get directory of running script

This is equivalent to the path of the script:

%~dp0

This uses the batch parameter extension syntax. Parameter 0 is always the script itself.

If your script is stored at C:\example\script.bat, then %~dp0 evaluates to C:\example\.

ss64.com has more information about the parameter extension syntax. Here is the relevant excerpt:

You can get the value of any parameter using a % followed by it's numerical position on the command line.

[...]

When a parameter is used to supply a filename then the following extended syntax can be applied:

[...]

%~d1 Expand %1 to a Drive letter only - C:

[...]

%~p1 Expand %1 to a Path only e.g. \utils\ this includes a trailing \ which may be interpreted as an escape character by some commands.

[...]

The modifiers above can be combined:

%~dp1 Expand %1 to a drive letter and path only

[...]

You can get the pathname of the batch script itself with %0, parameter extensions can be applied to this so %~dp0 will return the Drive and Path to the batch script e.g. W:\scripts\

How to edit HTML input value colour?

Maybe something like this (just add your style):

<input type="text" 
       size="35" 
       value="Job Title e.g. Assistant Manager" 
       style="background-color:white; 
              border: solid 1px #6E6E6E;
              height: 30px; 
              font-size:18px; 
              vertical-align:9px;color:#bbb" 
        onfocus="if(this.value == 'Job Title e.g. Assistant Manager') {
                    this.value = '';
                    this.style.color='#000';
                 }" />

<input type="text" 
       name="searchterm" size="35" 
       style="background-color:white; 
              border: solid 1px #6E6E6E;
              height: 30px; 
              font-size:18px; 
              vertical-align:9px" />

UPDATE: Since placeholder attribute is very well supported on all major browsers, there is no need to do anything manually. Its possible to achieve the same thing with this:

<input type="text" 
       size="35" 
       placeholder="Job Title e.g. Assistant Manager" />

How to add line break for UILabel?

In the interface builder, you can use Ctrl + Enter to insert /n to the position you want. This way could implement the following situation

aaa
aaaaaaa

Run Command Prompt Commands

Though technically this doesn't directly answer question posed, it does answer the question of how to do what the original poster wanted to do: combine files. If anything, this is a post to help newbies understand what Instance Hunter and Konstantin are talking about.

This is the method I use to combine files (in this case a jpg and a zip). Note that I create a buffer that gets filled with the content of the zip file (in small chunks rather than in one big read operation), and then the buffer gets written to the back of the jpg file until the end of the zip file is reached:

private void CombineFiles(string jpgFileName, string zipFileName)
{
    using (Stream original = new FileStream(jpgFileName, FileMode.Append))
    {
        using (Stream extra = new FileStream(zipFileName, FileMode.Open, FileAccess.Read))
        {
            var buffer = new byte[32 * 1024];

            int blockSize;
            while ((blockSize = extra.Read(buffer, 0, buffer.Length)) > 0)
            {
                original.Write(buffer, 0, blockSize);
            }
        }
    }
}

change background image in body

If you have JQuery loaded already, you can just do this:

$('body').css('background-image', 'url(../images/backgrounds/header-top.jpg)');

EDIT:

First load JQuery in the head tag:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

Then call the Javascript to change the background image when something happens on the page, like when it finishes loading:

<script type="text/javascript">
    $(document).ready(function() {
        $('body').css('background-image', 'url(../images/backgrounds/header-top.jpg)');
    });
</script>

What is the difference between public, protected, package-private and private in Java?

Access modifiers are there to restrict access at several levels.

Public: It is basically as simple as you can access from any class whether that is in same package or not.

To access if you are in same package you can access directly, but if you are in another package then you can create an object of the class.

Default: It is accessible in the same package from any of the class of package.

To access you can create an object of the class. But you can not access this variable outside of the package.

Protected: you can access variables in same package as well as subclass in any other package. so basically it is default + Inherited behavior.

To access protected field defined in base class you can create object of child class.

Private: it can be access in same class.

In non-static methods you can access directly because of this reference (also in constructors)but to access in static methods you need to create object of the class.

Basic Python client socket example

Here is a pretty simple socket program. This is about as simple as sockets get.

for the client program(CPU 1)

import socket

s = socket.socket()
host = '111.111.0.11' # needs to be in quote
port = 1247
s.connect((host, port))
print s.recv(1024)
inpt = raw_input('type anything and click enter... ')
s.send(inpt)
print "the message has been sent"

You have to replace the 111.111.0.11 in line 4 with the IP number found in the second computers network settings.

For the server program(CPU 2)

import socket

s = socket.socket()
host = socket.gethostname()
port = 1247
s.bind((host,port))
s.listen(5)
while True:
    c, addr = s.accept()
    print("Connection accepted from " + repr(addr[1]))

    c.send("Server approved connection\n")
    print repr(addr[1]) + ": " + c.recv(1026)
    c.close()

Run the server program and then the client one.

Difference between Spring MVC and Spring Boot

  • Using spring boot you will no need to build configuration. This will have done automatically when you create project.

  • If you use spring MVC you need to build configuration yourself. It is more complicated, but it is crucial.

Create JSON object dynamically via JavaScript (Without concate strings)

This is what you need!

function onGeneratedRow(columnsResult)
{
    var jsonData = {};
    columnsResult.forEach(function(column) 
    {
        var columnName = column.metadata.colName;
        jsonData[columnName] = column.value;
    });
    viewData.employees.push(jsonData);
 }

How can I draw circle through XML Drawable - Android?

no need for the padding or the corners.

here's a sample:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
        android:angle="270"/>
</shape>

based on :

https://stackoverflow.com/a/10104037/878126

How to get .pem file from .key and .crt files?

Trying to upload a GoDaddy certificate to AWS I failed several times, but in the end it was pretty simple. No need to convert anything to .pem. You just have to be sure to include the GoDaddy bundle certificate in the chain parameter, e.g.

aws iam upload-server-certificate
    --server-certificate-name mycert
    --certificate-body file://try2/40271b1b25236fd1.crt
    --private-key file://server.key
    --path /cloudfront/production/
    --certificate-chain file://try2/gdig2_bundle.crt

And to delete your previous failed upload you can do

aws iam delete-server-certificate --server-certificate-name mypreviouscert