Programs & Examples On #Http upload

How do I load a PHP file into a variable?

If you are using http://, as eyze suggested, you will only be able to read the ouput of the PHP script. You can only read the PHP script itself if it is on the same server as your running script. You could then use something like

$Vdata = file_get_contents('/path/to/your/file.php");

C non-blocking keyboard input

select() is a bit too low-level for convenience. I suggest you use the ncurses library to put the terminal in cbreak mode and delay mode, then call getch(), which will return ERR if no character is ready:

WINDOW *w = initscr();
cbreak();
nodelay(w, TRUE);

At that point you can call getch without blocking.

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

Righ Click on info.plist and select open as and then click on Source Code Add this line in last of file before </dict> tag

<key>ITSAppUsesNonExemptEncryption</key>
    <false/>

and save file.

Set the text in a span

Use .text() instead, and change your selector:

$(".ui-datepicker-prev .ui-icon.ui-icon-circle-triangle-w").text('<<');

-- VIEW DEMO --

grep from tar.gz without extracting [faster one]

All of the code above was really helpful, but none of it quite answered my own need: grep all *.tar.gz files in the current directory to find a pattern that is specified as an argument in a reusable script to output:

  • The name of both the archive file and the extracted file
  • The line number where the pattern was found
  • The contents of the matching line

It's what I was really hoping that zgrep could do for me and it just can't.

Here's my solution:

pattern=$1
for f in *.tar.gz; do
     echo "$f:"
     tar -xzf "$f" --to-command 'grep --label="`basename $TAR_FILENAME`" -Hin '"$pattern ; true";
done

You can also replace the tar line with the following if you'd like to test that all variables are expanding properly with a basic echo statement:

tar -xzf "$f" --to-command 'echo "f:`basename $TAR_FILENAME` s:'"$pattern\""

Let me explain what's going on. Hopefully, the for loop and the echo of the archive filename in question is obvious.

tar -xzf: x extract, z filter through gzip, f based on the following archive file...

"$f": The archive file provided by the for loop (such as what you'd get by doing an ls) in double-quotes to allow the variable to expand and ensure that the script is not broken by any file names with spaces, etc.

--to-command: Pass the output of the tar command to another command rather than actually extracting files to the filesystem. Everything after this specifies what the command is (grep) and what arguments we're passing to that command.

Let's break that part down by itself, since it's the "secret sauce" here.

'grep --label="`basename $TAR_FILENAME`" -Hin '"$pattern ; true"

First, we use a single-quote to start this chunk so that the executed sub-command (basename $TAR_FILENAME) is not immediately expanded/resolved. More on that in a moment.

grep: The command to be run on the (not actually) extracted files

--label=: The label to prepend the results, the value of which is enclosed in double-quotes because we do want to have the grep command resolve the $TAR_FILENAME environment variable passed in by the tar command.

basename $TAR_FILENAME: Runs as a command (surrounded by backticks) and removes directory path and outputs only the name of the file

-Hin: H Display filename (provided by the label), i Case insensitive search, n Display line number of match

Then we "end" the first part of the command string with a single quote and start up the next part with a double quote so that the $pattern, passed in as the first argument, can be resolved.

Realizing which quotes I needed to use where was the part that tripped me up the longest. Hopefully, this all makes sense to you and helps someone else out. Also, I hope I can find this in a year when I need it again (and I've forgotten about the script I made for it already!)


And it's been a bit a couple of weeks since I wrote the above and it's still super useful... but it wasn't quite good enough as files have piled up and searching for things has gotten more messy. I needed a way to limit what I looked at by the date of the file (only looking at more recent files). So here's that code. Hopefully it's fairly self-explanatory.

if [ -z "$1" ]; then
    echo "Look within all tar.gz files for a string pattern, optionally only in recent files"
    echo "Usage: targrep <string to search for> [start date]"
fi
pattern=$1
startdatein=$2
startdate=$(date -d "$startdatein" +%s)
for f in *.tar.gz; do
    filedate=$(date -r "$f" +%s)
    if [[ -z "$startdatein" ]] || [[ $filedate -ge $startdate ]]; then
        echo "$f:"
        tar -xzf "$f" --to-command 'grep --label="`basename $TAR_FILENAME`" -Hin '"$pattern ; true"
    fi
done

And I can't stop tweaking this thing. I added an argument to filter by the name of the output files in the tar file. Wildcards work, too.

Usage:

targrep.sh [-d <start date>] [-f <filename to include>] <string to search for>

Example:

targrep.sh -d "1/1/2019" -f "*vehicle_models.csv" ford

while getopts "d:f:" opt; do
    case $opt in
            d) startdatein=$OPTARG;;
            f) targetfile=$OPTARG;;
    esac
done
shift "$((OPTIND-1))" # Discard options and bring forward remaining arguments
pattern=$1

echo "Searching for: $pattern"
if [[ -n $targetfile ]]; then
    echo "in filenames:  $targetfile"
fi

startdate=$(date -d "$startdatein" +%s)
for f in *.tar.gz; do
    filedate=$(date -r "$f" +%s)
    if [[ -z "$startdatein" ]] || [[ $filedate -ge $startdate ]]; then
            echo "$f:"
            if [[ -z "$targetfile" ]]; then
                    tar -xzf "$f" --to-command 'grep --label="`basename $TAR_FILENAME`" -Hin '"$pattern ; true"
            else
                    tar -xzf "$f" --no-anchored "$targetfile" --to-command 'grep --label="`basename $TAR_FILENAME`" -Hin '"$pattern ; true"
            fi
    fi
done

How to check if a given directory exists in Ruby

All the other answers are correct, however, you might have problems if you're trying to check directory in a user's home directory. Make sure you expand the relative path before checking:

File.exists? '~/exists'
=> false
File.directory? '~/exists'
=> false
File.exists? File.expand_path('~/exists')
=> true

How to invoke a Linux shell command from Java

exec does not execute a command in your shell

try

Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});

instead.

EDIT:: I don't have csh on my system so I used bash instead. The following worked for me

Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});

How to change Label Value using javascript

You're taking name in document.getElementById() Your cb should be txt206451 (ID Attribute) not name attribute.

Or

You can have it by document.getElementsByName()

var cb = document.getElementsByName('field206451')[0]; // First one

OR

var cb = document.getElementById('txt206451');

And for setting values into hidden use document.getElementsByName() like following

var cb = document.getElementById('txt206451');
var label = document.getElementsByName('label206451')[0]; // Get the first one of index
console.log(label);
cb.addEventListener('change', function (evt) { // use change here. not neccessarily
    if (this.checked) {
        label.value = 'Thanks'
    } else {
        label.value = '0'
    }
}, false);

Demo Fiddle

Do HTTP POST methods send data as a QueryString?

Post uses the message body to send the information back to the server, as opposed to Get, which uses the query string (everything after the question mark). It is possible to send both a Get query string and a Post message body in the same request, but that can get a bit confusing so is best avoided.

Generally, best practice dictates that you use Get when you want to retrieve data, and Post when you want to alter it. (These rules aren't set in stone, the specs don't forbid altering data with Get, but it's generally avoided on the grounds that you don't want people making changes just by clicking a link or typing a URL)

Conversely, you can use Post to retrieve data without changing it, but using Get means you can bookmark the page, or share the URL with other people, things you couldn't do if you'd used Post.

As for the actual format of the data sent in the message body, that's entirely up to the sender and is specified with the Content-Type header. If not specified, the default content-type for HTML forms is application/x-www-form-urlencoded, which means the server will expect the post body to be a string encoded in a similar manner to a GET query string. However this can't be depended on in all cases. RFC2616 says the following on the Content-Type header:

Any HTTP/1.1 message containing an entity-body SHOULD include a
Content-Type header field defining the media type of that body. If
and only if the media type is not given by a Content-Type field, the
recipient MAY attempt to guess the media type via inspection of its
content and/or the name extension(s) of the URI used to identify the
resource. If the media type remains unknown, the recipient SHOULD
treat it as type "application/octet-stream".

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

I had this issue when I first installed Docker and ran

docker run hello-world

I was on a corporate network and switching to my personal network solved the issue for me.

List and kill at jobs on UNIX

First

ps -ef

to list all processes. Note the the process number of the one you want to kill. Then

kill 1234

were you replace 1234 with the process number that you want.

Alternatively, if you are absolutely certain that there is only one process with a particular name, or you want to kill multiple processes which share the same name

killall processname

How to get random value out of an array?

Use rand() to get random number to echo random key. In ex: 0 - 3

$ran = array(1,2,3,4);
echo $ran[rand(0,3)];

Is it valid to have a html form inside another html form?

As others have said, it is not valid HTML.

It sounds like your are doing this to position the forms visually within each other. If that is the case, just do two separate forms and use CSS to position them.

Indexes of all occurrences of character in a string

Try this

String str = "helloslkhellodjladfjhello";
String findStr = "hello";

System.out.println(StringUtils.countMatches(str, findStr));

DATEDIFF function in Oracle

You can simply subtract two dates. You have to cast it first, using to_date:

select to_date('2000-01-01', 'yyyy-MM-dd')
       - to_date('2000-01-02', 'yyyy-MM-dd')
       datediff
from   dual
;

The result is in days, to the difference of these two dates is -1 (you could swap the two dates if you like). If you like to have it in hours, just multiply the result with 24.

Run-time error '1004' - Method 'Range' of object'_Global' failed

Change

Range(DataImportColumn & DataImportRow).Offset(0, 2).Value

to

Cells(DataImportRow,DataImportColumn).Value

When you just have the row and the column then you can use the cells() object. The syntax is Cells(Row,Column)

Also one more tip. You might want to fully qualify your Cells object. for example

ThisWorkbook.Sheets("WhatEver").Cells(DataImportRow,DataImportColumn).Value

Remove Backslashes from Json Data in JavaScript

try this

var finalData = str.replace(/\\/g, '');

Case insensitive access for generic dictionary

There is much simpler way:

using System;
using System.Collections.Generic;
....
var caseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

Find document with array that contains a specific value

For Loopback3 all the examples given did not work for me, or as fast as using REST API anyway. But it helped me to figure out the exact answer I needed.

{"where":{"arrayAttribute":{ "all" :[String]}}}

Set size of HTML page and browser window

You could use width: 100%; in your css.

How to validate email id in angularJs using ng-pattern

According to the answer of @scx ,I created a validation for GUI

app.directive('validateEmail', function() {
  var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
  return {
    link: function(scope, elm) {
      elm.on("keyup",function(){
            var isMatchRegex = EMAIL_REGEXP.test(elm.val());
            if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
              elm.removeClass('warning');
            }else if(isMatchRegex == false && !elm.hasClass('warning')){
              elm.addClass('warning');
            }
      });
    }
  }
});

And simply add :

css

.warning{
   border:1px solid red;
 }

html

<input type='email' validate-email name='email' id='email' ng-model='email' required>

How to finish Activity when starting other activity in Android?

The best - and simplest - solution might be this:

Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
finishAndRemoveTask();

Documentation for finishAndRemoveTask():

Call this when your activity is done and should be closed and the task should be completely removed as a part of finishing the root activity of the task.

Is that what you're looking for?

How to loop through all the properties of a class?

This is how I do it.

foreach (var fi in typeof(CustomRoles).GetFields())
{
    var propertyName = fi.Name;
}

Passive Link in Angular 2 - <a href=""> equivalent

you need to prevent event's default behaviour as follows.

In html

<a href="" (click)="view($event)">view</a>

In ts file

view(event:Event){
 event.preventDefault();
 //remaining code goes here..
}

How to convert CSV file to multiline JSON?

You can use Pandas DataFrame to achieve this, with the following Example:

import pandas as pd
csv_file = pd.DataFrame(pd.read_csv("path/to/file.csv", sep = ",", header = 0, index_col = False))
csv_file.to_json("/path/to/new/file.json", orient = "records", date_format = "epoch", double_precision = 10, force_ascii = True, date_unit = "ms", default_handler = None)

Java: Get month Integer from Date

Date mDate = new Date(System.currentTimeMillis());
mDate.getMonth() + 1

The returned value starts from 0, so you should add one to the result.

Using Bootstrap Tooltip with AngularJS

AngularStrap doesn't work in IE8 with angularjs version 1.2.9 so not use this if your application needs to support IE8

How to compare dates in datetime fields in Postgresql?

@Nicolai is correct about casting and why the condition is false for any data. i guess you prefer the first form because you want to avoid date manipulation on the input string, correct? you don't need to be afraid:

SELECT *
FROM table
WHERE update_date >= '2013-05-03'::date
AND update_date < ('2013-05-03'::date + '1 day'::interval);

Java resource as file

I had the same problem and was able to use the following:

// Load the directory as a resource
URL dir_url = ClassLoader.getSystemResource(dir_path);
// Turn the resource into a File object
File dir = new File(dir_url.toURI());
// List the directory
String files = dir.list()

What is the difference between Hibernate and Spring Data JPA

Hibernate is a JPA implementation, while Spring Data JPA is a JPA data access abstraction. Spring Data JPA cannot work without a JPA provider.

Spring Data offers a solution to the DDD Repository pattern or the legacy GenericDao custom implementations. It can also generate JPA queries on your behalf through method name conventions.

With Spring Data, you may use Hibernate, EclipseLink, or any other JPA provider. A very interesting benefit of using Spring or Java EE is that you can control transaction boundaries declaratively using the @Transactional annotation.

Spring JDBC is much more lightweight, and it's intended for native querying, and if you only intend to use JDBC alone, then you are better off using Spring JDBC to deal with the JDBC verbosity.

Therefore, Hibernate and Spring Data are complementary rather than competitors.

How to find which views are using a certain table in SQL Server (2008)?

If you need to find database objects (e.g. tables, columns, triggers) by name - have a look at the FREE Red-Gate tool called SQL Search which does this - it searches your entire database for any kind of string(s).

enter image description here

enter image description here

It's a great must-have tool for any DBA or database developer - did I already mention it's absolutely FREE to use for any kind of use??

How to mention C:\Program Files in batchfile

Surround the script call with "", generally it's good practices to do so with filepath.

"C:\Program Files"

Although for this particular name you probably should use environment variable like this :

"%ProgramFiles%\batch.cmd"

or for 32 bits program on 64 bit windows :

"%ProgramFiles(x86)%\batch.cmd"

Help with packages in java - import does not work

You got a bunch of good answers, so I'll just throw out a suggestion. If you are going to be working on this project for more than 2 days, download eclipse or netbeans and build your project in there.

If you are not normally a java programmer, then the help it will give you will be invaluable.

It's not worth the 1/2 hour download/install if you are only spending 2 hours on it.

Both have hotkeys/menu items to "Fix imports", with this you should never have to worry about imports again.

How to convert enum names to string in c

A function like that without validating the enum is a trifle dangerous. I suggest using a switch statement. Another advantage is that this can be used for enums that have defined values, for example for flags where the values are 1,2,4,8,16 etc.

Also put all your enum strings together in one array:-

static const char * allEnums[] = {
    "Undefined",
    "apple",
    "orange"
    /* etc */
};

define the indices in a header file:-

#define ID_undefined       0
#define ID_fruit_apple     1
#define ID_fruit_orange    2
/* etc */

Doing this makes it easier to produce different versions, for example if you want to make international versions of your program with other languages.

Using a macro, also in the header file:-

#define CASE(type,val) case val: index = ID_##type##_##val; break;

Make a function with a switch statement, this should return a const char * because the strings static consts:-

const char * FruitString(enum fruit e){

    unsigned int index;

    switch(e){
        CASE(fruit, apple)
        CASE(fruit, orange)
        CASE(fruit, banana)
        /* etc */
        default: index = ID_undefined;
    }
    return allEnums[index];
}

If programming with Windows then the ID_ values can be resource values.

(If using C++ then all the functions can have the same name.

string EnumToString(fruit e);

)

How to pass arguments to entrypoint in docker-compose.yml

The command clause does work as @Karthik says above.

As a simple example, the following service will have a -inMemory added to its ENTRYPOINT when docker-compose up is run.

version: '2'
services:
  local-dynamo:
    build: local-dynamo
    image: spud/dynamo
    command: -inMemory

Should you commit .gitignore into the Git repos?

Normally yes, .gitignore is useful for everyone who wants to work with the repository. On occasion you'll want to ignore more private things (maybe you often create LOG or something. In those cases you probably don't want to force that on anyone else.

Get data from fs.readFile

As said, fs.readFile is an asynchronous action. It means that when you tell node to read a file, you need to consider that it will take some time, and in the meantime, node continued to run the following code. In your case it's: console.log(content);.

It's like sending some part of your code for a long trip (like reading a big file).

Take a look at the comments that I've written:

var content;

// node, go fetch this file. when you come back, please run this "read" callback function
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});

// in the meantime, please continue and run this console.log
console.log(content);

That's why content is still empty when you log it. node has not yet retrieved the file's content.

This could be resolved by moving console.log(content) inside the callback function, right after content = data;. This way you will see the log when node is done reading the file and after content gets a value.

How to open child forms positioned within MDI parent in VB.NET?

Try adding a button on mdi parent and add this code' to set your mdi child inside the mdi parent. change the yourchildformname to your MDI Child's form name and see if this works.

    Dim NewMDIChild As New yourchildformname()
    'Set the Parent Form of the Child window.
    NewMDIChild.MdiParent = Me
    'Display the new form.
    NewMDIChild.Show()

How to deserialize a JObject to .NET object

According to this post, it's much better now:

// pick out one album
JObject jalbum = albums[0] as JObject;

// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();

Documentation: Convert JSON to a Type

Size of Matrix OpenCV

If you are using the Python wrappers, then (assuming your matrix name is mat):

  • mat.shape gives you an array of the type- [height, width, channels]

  • mat.size gives you the size of the array

Sample Code:

import cv2
mat = cv2.imread('sample.png')
height, width, channel = mat.shape[:3]
size = mat.size

Load a bitmap image into Windows Forms using open file dialog

You can try the following:

private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog fDialog = new OpenFileDialog();
        fDialog.Title = "Select file to be upload";
        fDialog.Filter = "All Files|*.*";
        //  fDialog.Filter = "PDF Files|*.pdf";
        if (fDialog.ShowDialog() == DialogResult.OK)
        {
            textBox1.Text = fDialog.FileName.ToString();
        }
    }

HTML: Image won't display?

I confess to not having read the whole thread. However when I faced a similar issue I found that checking carefully the case of the file name and correcting that in the HTML reference fixed a similar issue. So local preview on Windows worked but when I published to my server (hosted Linux) I had to make sure "mugshot.jpg" was changed to "mugshot.JPG". Part of the problem is the defaults in Windows hiding full file names behind file type indications.

What is private bytes, virtual bytes, working set?

The definition of the perfmon counters has been broken since the beginning and for some reason appears to be too hard to correct.

A good overview of Windows memory management is available in the video "Mysteries of Memory Management Revealed" on MSDN: It covers more topics than needed to track memory leaks (eg working set management) but gives enough detail in the relevant topics.


To give you a hint of the problem with the perfmon counter descriptions, here is the inside story about private bytes from "Private Bytes Performance Counter -- Beware!" on MSDN:

Q: When is a Private Byte not a Private Byte?

A: When it isn't resident.

The Private Bytes counter reports the commit charge of the process. That is to say, the amount of space that has been allocated in the swap file to hold the contents of the private memory in the event that it is swapped out. Note: I'm avoiding the word "reserved" because of possible confusion with virtual memory in the reserved state which is not committed.


From "Performance Planning" on MSDN:

3.3 Private Bytes

3.3.1 Description

Private memory, is defined as memory allocated for a process which cannot be shared by other processes. This memory is more expensive than shared memory when multiple such processes execute on a machine. Private memory in (traditional) unmanaged dlls usually constitutes of C++ statics and is of the order of 5% of the total working set of the dll.

How to play an android notification sound

Set sound to notification channel

        Uri alarmUri = Uri.fromFile(new File(<path>));

        AudioAttributes attributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_ALARM)
                .build();

        channel.setSound(alarmUri, attributes);

Using a custom (ttf) font in CSS

You need to use the css-property font-face to declare your font. Have a look at this fancy site: http://www.font-face.com/

Example:

@font-face {
  font-family: MyHelvetica;
  src: local("Helvetica Neue Bold"),
       local("HelveticaNeue-Bold"),
       url(MgOpenModernaBold.ttf);
  font-weight: bold;
}

See also: MDN @font-face

How to find the .NET framework version of a Visual Studio project?

You can also search the Visual Studio project files for the XML tag RequiredTargetFramework. This tag seems to exist on .NET 3.5 and higher.

For example: <RequiredTargetFramework>3.5</RequiredTargetFramework>

Understanding the results of Execute Explain Plan in Oracle SQL Developer

The CBO builds a decision tree, estimating the costs of each possible execution path available per query. The costs are set by the CPU_cost or I/O_cost parameter set on the instance. And the CBO estimates the costs, as best it can with the existing statistics of the tables and indexes that the query will use. You should not tune your query based on cost alone. Cost allows you to understand WHY the optimizer is doing what it does. Without cost you could figure out why the optimizer chose the plan it did. Lower cost does not mean a faster query. There are cases where this is true and there will be cases where this is wrong. Cost is based on your table stats and if they are wrong the cost is going to be wrong.

When tuning your query, you should take a look at the cardinality and the number of rows of each step. Do they make sense? Is the cardinality the optimizer is assuming correct? Is the rows being return reasonable. If the information present is wrong then its very likely the optimizer doesn't have the proper information it needs to make the right decision. This could be due to stale or missing statistics on the table and index as well as cpu-stats. Its best to have stats updated when tuning a query to get the most out of the optimizer. Knowing your schema is also of great help when tuning. Knowing when the optimizer chose a really bad decision and pointing it in the correct path with a small hint can save a load of time.

Remove element by id

This one actually comes from Firefox... for once, IE was ahead of the pack and allowed the removal of an element directly.

This is just my assumption, but I believe the reason that you must remove a child through the parent is due to an issue with the way Firefox handled the reference.

If you call an object to commit hari-kari directly, then immediately after it dies, you are still holding that reference to it. This has the potential to create several nasty bugs... such as failing to remove it, removing it but keeping references to it that appear valid, or simply a memory leak.

I believe that when they realized the issue, the workaround was to remove an element through its parent because when the element is gone, you are now simply holding a reference to the parent. This would stop all that unpleasantness, and (if closing down a tree node by node, for example) would 'zip-up' rather nicely.

It should be an easily fixable bug, but as with many other things in web programming, the release was probably rushed, leading to this... and by the time the next version came around, enough people were using it that changing this would lead to breaking a bunch of code.

Again, all of this is simply my guesswork.

I do, however, look forward to the day when web programming finally gets a full spring cleaning, all these strange little idiosyncracies get cleaned up, and everyone starts playing by the same rules.

Probably the day after my robot servant sues me for back wages.

Check if certain value is contained in a dataframe column in pandas

I think you need str.contains, if you need rows where values of column date contains string 07311954:

print df[df['date'].astype(str).str.contains('07311954')]

Or if type of date column is string:

print df[df['date'].str.contains('07311954')]

If you want check last 4 digits for string 1954 in column date:

print df[df['date'].astype(str).str[-4:].str.contains('1954')]

Sample:

print df['date']
0    8152007
1    9262007
2    7311954
3    2252011
4    2012011
5    2012011
6    2222011
7    2282011
Name: date, dtype: int64

print df['date'].astype(str).str[-4:].str.contains('1954')
0    False
1    False
2     True
3    False
4    False
5    False
6    False
7    False
Name: date, dtype: bool

print df[df['date'].astype(str).str[-4:].str.contains('1954')]
     cmte_id trans_typ entity_typ state  employer  occupation     date  \
2  C00119040       24K        CCM    MD       NaN         NaN  7311954   

   amount     fec_id    cand_id  
2    1000  C00140715  H2MD05155  

Putting GridView data in a DataTable

Copying Grid to datatable

        if (GridView.Rows.Count != 0)
        {
            //Forloop for header
            for (int i = 0; i < GridView.HeaderRow.Cells.Count; i++)
            {
                dt.Columns.Add(GridView.HeaderRow.Cells[i].Text);
            }
            //foreach for datarow
            foreach (GridViewRow row in GridView.Rows)
            {
                DataRow dr = dt.NewRow();
                for (int j = 0; j < row.Cells.Count; j++)
                {
                    dr[GridView.HeaderRow.Cells[j].Text] = row.Cells[j].Text;
                }
                dt.Rows.Add(dr);
            }
            //Loop for footer
            if (GridView.FooterRow.Cells.Count != 0)
            {
                DataRow dr = dt.NewRow();
                for (int i = 0; i < GridView.FooterRow.Cells.Count; i++)
                {
                    //You have to re-do the work if you did anything in databound for footer.  
                }
                dt.Rows.Add(dr);
            }
            dt.TableName = "tb";
        }

convert a char* to std::string

I would like to mention a new method which uses the user defined literal s. This isn't new, but it will be more common because it was added in the C++14 Standard Library.

Largely superfluous in the general case:

string mystring = "your string here"s;

But it allows you to use auto, also with wide strings:

auto mystring = U"your UTF-32 string here"s;

And here is where it really shines:

string suffix;
cin >> suffix;
string mystring = "mystring"s + suffix;

What does yield mean in PHP?

With yield you can easily describe the breakpoints between multiple tasks in a single function. That's all, there is nothing special about it.

$closure = function ($injected1, $injected2, ...){
    $returned = array();
    //task1 on $injected1
    $returned[] = $returned1;
//I need a breakpoint here!!!!!!!!!!!!!!!!!!!!!!!!!
    //task2 on $injected2
    $returned[] = $returned2;
    //...
    return $returned;
};
$returned = $closure($injected1, $injected2, ...);

If task1 and task2 are highly related, but you need a breakpoint between them to do something else:

  • free memory between processing database rows
  • run other tasks which provide dependency to the next task, but which are unrelated by understanding the current code
  • doing async calls and wait for the results
  • and so on ...

then generators are the best solution, because you don't have to split up your code into many closures or mix it with other code, or use callbacks, etc... You just use yield to add a breakpoint, and you can continue from that breakpoint if you are ready.

Add breakpoint without generators:

$closure1 = function ($injected1){
    //task1 on $injected1
    return $returned1;
};
$closure2 = function ($injected2){
    //task2 on $injected2
    return $returned1;
};
//...
$returned1 = $closure1($injected1);
//breakpoint between task1 and task2
$returned2 = $closure2($injected2);
//...

Add breakpoint with generators

$closure = function (){
    $injected1 = yield;
    //task1 on $injected1
    $injected2 = (yield($returned1));
    //task2 on $injected2
    $injected3 = (yield($returned2));
    //...
    yield($returnedN);
};
$generator = $closure();
$returned1 = $generator->send($injected1);
//breakpoint between task1 and task2
$returned2 = $generator->send($injected2);
//...
$returnedN = $generator->send($injectedN);

note: It is easy to make mistake with generators, so always write unit tests before you implement them! note2: Using generators in an infinite loop is like writing a closure which has infinite length...

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_

How to select between brackets (or quotes or ...) in Vim?

A simple keymap in vim would solve this issue. map viq F”lvf”hh This above command maps viq to the keys to search between quotes. Replace " with any character and create your keymaps. Stick this in vimrc during startup and you should be able to use it everytime.

Change values on matplotlib imshow() graph axis

I would try to avoid changing the xticklabels if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.

Defining the range of your grid is probably the best and with imshow it can be done by adding the extent keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks with perhaps some formatter. Altering the labels directly should be the last resort.

fig, ax = plt.subplots(figsize=(6,6))

ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio

enter image description here

How can Bash execute a command in a different directory context?

If you want to return to your current working directory:

current_dir=$PWD;cd /path/to/your/command/dir;special command ARGS;cd $current_dir;
  1. We are setting a variable current_dir equal to your pwd
  2. after that we are going to cd to where you need to run your command
  3. then we are running the command
  4. then we are going to cd back to our variable current_dir

Another Solution by @apieceofbart pushd && YOUR COMMAND && popd

Adding Image to xCode by dragging it from File

Add the image to Your project by clicking File -> "Add Files to ...".

Then choose the image in ImageView properties (Utilities -> Attributes Inspector).

Get a Windows Forms control by name in C#

A simple solution would be to iterate through the Controls list in a foreach loop. Something like this:

foreach (Control child in Controls)
{
    // Code that executes for each control.
}

So now you have your iterator, child, which is of type Control. Now do what you will with that, personally I found this in a project I did a while ago in which it added an event for this control, like this:

child.MouseDown += new MouseEventHandler(dragDown);

How do I convert Word files to PDF programmatically?

Seems to be some relevent info here:

Converting MS Word Documents to PDF in ASP.NET

Also, with Office 2007 having publish to PDF functionality, I guess you could use office automation to open the *.DOC file in Word 2007 and Save as PDF. I'm not too keen on office automation as it's slow and prone to hanging, but just throwing that out there...

How to delete an SMS from the inbox in Android programmatically?

Using suggestions from others, I think I got it to work:

(using SDK v1 R2)

It's not perfect, since i need to delete the entire conversation, but for our purposes, it's a sufficient compromise as we will at least know all messages will be looked at and verified. Our flow will probably need to then listen for the message, capture for the message we want, do a query to get the thread_id of the recently inbounded message and do the delete() call.

In our Activity:

Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uriSms, null,null,null,null); 
int id = c.getInt(0);
int thread_id = c.getInt(1); //get the thread_id
getContentResolver().delete(Uri.parse("content://sms/conversations/" + thread_id),null,null);

Note: I wasn't able to do a delete on content://sms/inbox/ or content://sms/all/

Looks like the thread takes precedence, which makes sense, but the error message only emboldened me to be angrier. When trying the delete on sms/inbox/ or sms/all/, you will probably get:

java.lang.IllegalArgumentException: Unknown URL
    at com.android.providers.telephony.SmsProvider.delete(SmsProvider.java:510)
    at android.content.ContentProvider$Transport.delete(ContentProvider.java:149)
    at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:149)

For additional reference too, make sure to put this into your manifest for your intent receiver:

<receiver android:name=".intent.MySmsReceiver">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
    </intent-filter>
</receiver>

Note the receiver tag does not look like this:

<receiver android:name=".intent.MySmsReceiver" 
    android:permission="android.permission.RECEIVE_SMS">

When I had those settings, android gave me some crazy permissions exceptions that didn't allow android.phone to hand off the received SMS to my intent. So, DO NOT put that RECEIVE_SMS permission attribute in your intent! Hopefully someone wiser than me can tell me why that was the case.

How to add url parameters to Django template url tag?

Im not sure if im out of the subject, but i found solution for me; You have a class based view, and you want to have a get parameter as a template tag:

class MyView(DetailView):
    model = MyModel

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        ctx['tag_name'] = self.request.GET.get('get_parameter_name', None)
        return ctx

Then you make your get request /mysite/urlname?get_parameter_name='stuff.

In your template, when you insert {{ tag_name }}, you will have access to the get parameter value ('stuff'). If you have an url in your template that also needs this parameter, you can do

 {% url 'my_url' %}?get_parameter_name={{ tag_name }}"

You will not have to modify your url configuration

How to show alert message in mvc 4 controller?

<a href="@Url.Action("DeleteBlog")" class="btn btn-sm btn-danger" onclick="return confirm ('Are you sure want to delete blog?');">

Cross browser JavaScript (not jQuery...) scroll to top animation

I see that most/all of the above posts search for a button with javascript. This works, as long as you have only one button. I would recommend defining an "onclick" element inside the button. That "onclick" would then call the function causing it to scroll.

If you do it like that, you can use more than one button, as long as the button looks something like this:

<button onclick="scrollTo(document.body, 0, 1250)">To the top</button>

Set timeout for webClient.DownloadFile()

Try WebClient.DownloadFileAsync(). You can call CancelAsync() by timer with your own timeout.

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

You can try:

var headingDiv       = document.getElementById("head");
headingDiv.innerHTML = "<H3>Public Offers</H3>";

Using a custom typeface in Android

I did this in a more "brute force" way that doesn't require changes to the layout xml or Activities.

Tested on Android version 2.1 through 4.4. Run this at app startup, in your Application class:

private void setDefaultFont() {

    try {
        final Typeface bold = Typeface.createFromAsset(getAssets(), DEFAULT_BOLD_FONT_FILENAME);
        final Typeface italic = Typeface.createFromAsset(getAssets(), DEFAULT_ITALIC_FONT_FILENAME);
        final Typeface boldItalic = Typeface.createFromAsset(getAssets(), DEFAULT_BOLD_ITALIC_FONT_FILENAME);
        final Typeface regular = Typeface.createFromAsset(getAssets(),DEFAULT_NORMAL_FONT_FILENAME);

        Field DEFAULT = Typeface.class.getDeclaredField("DEFAULT");
        DEFAULT.setAccessible(true);
        DEFAULT.set(null, regular);

        Field DEFAULT_BOLD = Typeface.class.getDeclaredField("DEFAULT_BOLD");
        DEFAULT_BOLD.setAccessible(true);
        DEFAULT_BOLD.set(null, bold);

        Field sDefaults = Typeface.class.getDeclaredField("sDefaults");
        sDefaults.setAccessible(true);
        sDefaults.set(null, new Typeface[]{
                regular, bold, italic, boldItalic
        });

    } catch (NoSuchFieldException e) {
        logFontError(e);
    } catch (IllegalAccessException e) {
        logFontError(e);
    } catch (Throwable e) {
        //cannot crash app if there is a failure with overriding the default font!
        logFontError(e);
    }
}

For a more complete example, see http://github.com/perchrh/FontOverrideExample

How to get a substring of text?

If you have your text in your_text variable, you can use:

your_text[0..29]

Get a particular cell value from HTML table using JavaScript

To get the text from this cell-

<table>
    <tr id="somerow">
        <td>some text</td>            
    </tr>
</table>

You can use this -

var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");
alert(Cells[0].innerText);

How do I get the SharedPreferences from a PreferenceActivity in Android?

import android.preference.PreferenceManager;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// then you use
prefs.getBoolean("keystring", true);

Update

According to Shared Preferences | Android Developer Tutorial (Part 13) by Sai Geetha M N,

Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.

Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.

  1. Shared Preferences: The shared preferences can be used by all the components (activities, services etc) of the applications.

  2. Activity handled preferences: These preferences can only be used within the particular activity and can not be used by other components of the application.

Shared Preferences:

The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in a default file (1) or you can specify a file name (2) to be used to refer to the preferences.

(1) The recommended way is to use by the default mode, without specifying the file name

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

(2) Here is how you get the instance when you specify the file name

public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two modes supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.

Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:

int storedPreference = preferences.getInt("storedInt", 0);

To store values in the preference file SharedPreference.Editor object has to be used. Editor is a nested interface in the SharedPreference class.

SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();

Editor also supports methods like remove() and clear() to delete the preference values from the file.

Activity Preferences:

The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activity private preferences you can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.

Following is the code to get preferences

SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);

The code to store values is also the same as in case of shared preferences.

SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();

You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.

To see some more examples check Android's Data Storage post on developers site.

Disable building workspace process in Eclipse

You can switch to manual build so can control when this is done. Just make sure that Project > Build Automatically from the main menu is unchecked.

Alter table to modify default value of column

ALTER TABLE {TABLE NAME}
ALTER COLUMN {COLUMN NAME} SET DEFAULT '{DEFAULT VALUES}'

example :

ALTER TABLE RESULT
ALTER COLUMN STATUS SET DEFAULT 'FAIL'

Git Commit Messages: 50/72 Formatting

Separation of presentation and data drives my commit messages here.

Your commit message should not be hard-wrapped at any character count and instead line breaks should be used to separate thoughts, paragraphs, etc. as part of the data, not the presentation. In this case, the "data" is the message you are trying to get across and the "presentation" is how the user sees that.

I use a single summary line at the top and I try to keep it short but I don't limit myself to an arbitrary number. It would be far better if Git actually provided a way to store summary messages as a separate entity from the message but since it doesn't I have to hack one in and I use the first line break as the delimiter (luckily, many tools support this means of breaking apart the data).

For the message itself newlines indicate something meaningful in the data. A single newline indicates a start/break in a list and a double newline indicates a new thought/idea.

This is a summary line, try to keep it short and end with a line break.
This is a thought, perhaps an explanation of what I have done in human readable format.  It may be complex and long consisting of several sentences that describe my work in essay format.  It is not up to me to decide now (at author time) how the user is going to consume this data.

Two line breaks separate these two thoughts.  The user may be reading this on a phone or a wide screen monitor.  Have you ever tried to read 72 character wrapped text on a device that only displays 60 characters across?  It is a truly painful experience.  Also, the opening sentence of this paragraph (assuming essay style format) should be an intro into the paragraph so if a tool chooses it may want to not auto-wrap and let you just see the start of each paragraph.  Again, it is up to the presentation tool not me (a random author at some point in history) to try to force my particular formatting down everyone else's throat.

Just as an example, here is a list of points:
* Point 1.
* Point 2.
* Point 3.

Here's what it looks like in a viewer that soft wraps the text.

This is a summary line, try to keep it short and end with a line break.

This is a thought, perhaps an explanation of what I have done in human readable format. It may be complex and long consisting of several sentences that describe my work in essay format. It is not up to me to decide now (at author time) how the user is going to consume this data.

Two line breaks separate these two thoughts. The user may be reading this on a phone or a wide screen monitor. Have you ever tried to read 72 character wrapped text on a device that only displays 60 characters across? It is a truly painful experience. Also, the opening sentence of this paragraph (assuming essay style format) should be an intro into the paragraph so if a tool chooses it may want to not auto-wrap and let you just see the start of each paragraph. Again, it is up to the presentation tool not me (a random author at some point in history) to try to force my particular formatting down everyone else's throat.

Just as an example, here is a list of points:
* Point 1.
* Point 2.
* Point 3.

My suspicion is that the author of Git commit message recommendation you linked has never written software that will be consumed by a wide array of end-users on different devices before (i.e., a website) since at this point in the evolution of software/computing it is well known that storing your data with hard-coded presentation information is a bad idea as far as user experience goes.

How do you programmatically update query params in react-router?

Within the push method of hashHistory, you can specify your query parameters. For instance,

history.push({
  pathname: '/dresses',
  search: '?color=blue'
})

or

history.push('/dresses?color=blue')

You can check out this repository for additional examples on using history

Cannot convert lambda expression to type 'string' because it is not a delegate type

If it's not related to missing using directives stated by other users, this will also happen if there is another problem with your query.

Take a look on VS compiler error list : For example, if the "Value" variable in your query doesn't exist, you will have the "lambda to string" error, and a few errors after another one more related to the unknown/erroneous field.

In your case it could be :

objContentLine = (from q in db.qryContents
                  where q.LineID == Value
                  orderby q.RowID descending
                  select q).FirstOrDefault();

Errors:

Error 241 Cannot convert lambda expression to type 'string' because it is not a delegate type

Error 242 Delegate 'System.Func<..>' does not take 1 arguments

Error 243 The name 'Value' does not exist in the current context

Fix the "Value" variable error and the other errors will also disappear.

Change drawable color programmatically

I have wrote a generic function in which you can pass context, icon is id drawable/mipmap image icon and new color which you need for that icon.

This function returns a drawable.

public static Drawable changeDrawableColor(Context context,int icon, int newColor) {
    Drawable mDrawable = ContextCompat.getDrawable(context, icon).mutate(); 
    mDrawable.setColorFilter(new PorterDuffColorFilter(newColor, PorterDuff.Mode.SRC_IN)); 
    return mDrawable;
} 

changeDrawableColor(getContext(),R.mipmap.ic_action_tune, Color.WHITE);

How to secure phpMyAdmin

Most likely, somewhere on your webserver will be an Alias directive like this;

Alias /phpmyadmin "c:/wamp/apps/phpmyadmin3.1.3.1/"

In my wampserver / localhost setup, it was in c:/wamp/alias/phpmyadmin.conf.

Just change the alias directive and you should be good to go.

POST request not allowed - 405 Not Allowed - nginx, even with headers included

In my case it was POST submission of a json to be processed and get a return value. I cross checked logs of my app server with and without nginx. What i got was my location was not getting appended to proxy_pass url and the version of HTTP protocol version is different.

  • Without nginx: "POST /xxQuery HTTP/1.1" 200 -
  • With nginx: "POST / HTTP/1.0" 405 -

My earlier location block was

location /xxQuery {
    proxy_method POST;
    proxy_pass http://127.0.0.1:xx00/;
    client_max_body_size 10M;
}

I changed it to

location /xxQuery {
    proxy_method POST;
    proxy_http_version 1.1;
    proxy_pass http://127.0.0.1:xx00/xxQuery;
    client_max_body_size 10M;
}

It worked.

Object of class mysqli_result could not be converted to string in

Try with:

$row = mysqli_fetch_assoc($result);
echo "my result <a href='data/" . htmlentities($row['classtype'], ENT_QUOTES, 'UTF-8') . ".php'>My account</a>";

CSS centred header image

I think this is what you need if I'm understanding you correctly:

<div id="wrapperHeader">
 <div id="header">
  <img src="images/logo.png" alt="logo" />
 </div> 
</div>



div#wrapperHeader {
 width:100%;
 height;200px; /* height of the background image? */
 background:url(images/header.png) repeat-x 0 0;
 text-align:center;
}

div#wrapperHeader div#header {
 width:1000px;
 height:200px;
 margin:0 auto;
}

div#wrapperHeader div#header img {
 width:; /* the width of the logo image */
 height:; /* the height of the logo image */
 margin:0 auto;
}

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

Use:

netstat -a -o

This shows the PID of the process running on a particular port.

Keep in mind the process ID and go to Task Manager and services or details tab and end the process which has the same PID.

Thus you can kill a process running on a particular port in Windows.

EXCEL VBA, inserting blank row and shifting cells

Sub Addrisk()

Dim rActive As Range
Dim Count_Id_Column as long

Set rActive = ActiveCell

Application.ScreenUpdating = False

with thisworkbook.sheets(1) 'change to "sheetname" or sheetindex
    for i = 1 to .range("A1045783").end(xlup).row
        if 'something'  = 'something' then
            .range("A" & i).EntireRow.Copy 'add thisworkbook.sheets(index_of_sheet) if you copy from another sheet
            .range("A" & i).entirerow.insert shift:= xldown 'insert and shift down, can also use xlup
            .range("A" & i + 1).EntireRow.paste 'paste is all, all other defs are less.
            'change I to move on to next row (will get + 1 end of iteration)
            i = i + 1
        end if

            On Error Resume Next
                .SpecialCells(xlCellTypeConstants).ClearContents
            On Error GoTo 0

        End With
    next i
End With

Application.CutCopyMode = False
Application.ScreenUpdating = True 're-enable screen updates

End Sub

React PropTypes : Allow different types of PropTypes for one prop

This might work for you:

height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

How to extract the decimal part from a floating point number in C?

You use the modf function:

double integral;
double fractional = modf(some_double, &integral);

You can also cast it to an integer, but be warned you may overflow the integer. The result is not predictable then.

Can I underline text in an Android layout?

The most recent approach of drawing underlined text is described by Romain Guy on medium with available source code on GitHub. This sample application exposes two possible implementations:

  • A Path-based implementation that requires API level 19
  • A Region-based implementation that requires API level 1

enter image description here

How to get indices of a sorted array in Python

Essentially you need to do an argsort, what implementation you need depends if you want to use external libraries (e.g. NumPy) or if you want to stay pure-Python without dependencies.

The question you need to ask yourself is: Do you want the

  • indices that would sort the array/list
  • indices that the elements would have in the sorted array/list

Unfortunately the example in the question doesn't make it clear what is desired because both will give the same result:

>>> arr = np.array([1, 2, 3, 100, 5])

>>> np.argsort(np.argsort(arr))
array([0, 1, 2, 4, 3], dtype=int64)

>>> np.argsort(arr)
array([0, 1, 2, 4, 3], dtype=int64)

Choosing the argsort implementation

If you have NumPy at your disposal you can simply use the function numpy.argsort or method numpy.ndarray.argsort.

An implementation without NumPy was mentioned in some other answers already, so I'll just recap the fastest solution according to the benchmark answer here

def argsort(l):
    return sorted(range(len(l)), key=l.__getitem__)

Getting the indices that would sort the array/list

To get the indices that would sort the array/list you can simply call argsort on the array or list. I'm using the NumPy versions here but the Python implementation should give the same results

>>> arr = np.array([3, 1, 2, 4])
>>> np.argsort(arr)
array([1, 2, 0, 3], dtype=int64)

The result contains the indices that are needed to get the sorted array.

Since the sorted array would be [1, 2, 3, 4] the argsorted array contains the indices of these elements in the original.

  • The smallest value is 1 and it is at index 1 in the original so the first element of the result is 1.
  • The 2 is at index 2 in the original so the second element of the result is 2.
  • The 3 is at index 0 in the original so the third element of the result is 0.
  • The largest value 4 and it is at index 3 in the original so the last element of the result is 3.

Getting the indices that the elements would have in the sorted array/list

In this case you would need to apply argsort twice:

>>> arr = np.array([3, 1, 2, 4])
>>> np.argsort(np.argsort(arr))
array([2, 0, 1, 3], dtype=int64)

In this case :

  • the first element of the original is 3, which is the third largest value so it would have index 2 in the sorted array/list so the first element is 2.
  • the second element of the original is 1, which is the smallest value so it would have index 0 in the sorted array/list so the second element is 0.
  • the third element of the original is 2, which is the second-smallest value so it would have index 1 in the sorted array/list so the third element is 1.
  • the fourth element of the original is 4 which is the largest value so it would have index 3 in the sorted array/list so the last element is 3.

Jquery change background color

This is how it should be:

Code:

$(function(){
  $("button").mouseover(function(){
    var $p = $("#P44");
    $p.stop()
      .css("background-color","yellow")
      .hide(1500, function() {
          $p.css("background-color","red")
            .show(1500);
      });
  });
});

Demo: http://jsfiddle.net/p7w9W/2/

Explanation:

You have to wait for the callback on the animating functions before you switch background color. You should also not use only numeric ID:s, and if you have an ID of your <p> there you shouldn't include a class in your selector.

I also enhanced your code (caching of the jQuery object, chaining, etc.)

Update: As suggested by VKolev the color is now changing when the item is hidden.

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

@nmr also check the ownership and groups on the sqlite file itself... I'd copied my database in from /sdcard as root so had to change the permissions..

-rw-rw---- root     root       180224 2014-05-05 11:06 test.sqlite

should be..

-rw-rw---- u0_a80   u0_a80     180224 2014-05-05 11:06 test.sqlite

Used the following commands to set the correct ownership and group. The u0_a80 I got from ls -al on other files in the directory

chown u0_a80 test.sqlite
chgrp u0_a80 test.sqlite

How to check if a String contains any letter from a to z?

You can look for regular expression

Regex.IsMatch(str, @"^[a-zA-Z]+$");

How to convert an Array to a Set in Java

After you do Arrays.asList(array) you can execute Set set = new HashSet(list);

Here is a sample method, you can write:

public <T> Set<T> GetSetFromArray(T[] array) {
    return new HashSet<T>(Arrays.asList(array));
}

"Cross origin requests are only supported for HTTP." error when loading a local file

It simply says that the application should be run on a web server. I had the same problem with chrome, I started tomcat and moved my application there, and it worked.

Are multiple `.gitignore`s frowned on?

I can think of at least two situations where you would want to have multiple .gitignore files in different (sub)directories.

  • Different directories have different types of file to ignore. For example the .gitignore in the top directory of your project ignores generated programs, while Documentation/.gitignore ignores generated documentation.

  • Ignore given files only in given (sub)directory (you can use /sub/foo in .gitignore, though).

Please remember that patterns in .gitignore file apply recursively to the (sub)directory the file is in and all its subdirectories, unless pattern contains '/' (so e.g. pattern name applies to any file named name in given directory and all its subdirectories, while /name applies to file with this name only in given directory).

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

We're all working around some old bugs that haven't been fixed likely because it's "by design." I ran into the freezing problem @iwasrobbed described elsewhere when trying to nil the interactivePopGestureRecognizer's delegate which seemed like it should've worked. If you want swipe behavior reconsider using backBarButtonItem which you can customize.

I also ran into interactivePopGestureRecognizer not working when the UINavigationBar is hidden. If hiding the navigation bar is a concern for you, reconsider your design before implementing a workaround for a bug.

Excel 2007 - Compare 2 columns, find matching values

VLOOKUP deosnt work for String literals

What is the right way to populate a DropDownList from a database?

((TextBox)GridView1.Rows[e.NewEditIndex].Cells[3].Controls[0]).Enabled = false;

Getting current device language in iOS?

@amir response in Swift :

// Get language prefered by user
let langageRegion = NSLocale.preferredLanguages().first!
let languageDic = NSLocale.componentsFromLocaleIdentifier(langageRegion)
let language = languageDic[NSLocaleLanguageCode]

Pass connection string to code-first DbContext

A little late to the game here, but another option is:

public class NerdDinners : DbContext
{
    public NerdDinners(string connString)
    {
        this.Database.Connection.ConnectionString = connString;
    }
    public DbSet<Dinner> Dinners { get; set; }
}

Accessing a property in a parent Component

I made a generic component where I need a reference to the parent using it. Here's what I came up with:

In my component I made an @Input :

@Input()
parent: any;

Then In the parent using this component:

<app-super-component [parent]="this"> </app-super-component>

In the super component I can use any public thing coming from the parent:

Attributes:

parent.anyAttribute

Functions :

parent[myFunction](anyParameter)

and of course private stuff won't be accessible.

How to fill a datatable with List<T>

I also had to come up with an alternate solution, as none of the options listed here worked in my case. I was using an IEnumerable and the underlying data was a IEnumerable and the properties couldn't be enumerated. This did the trick:

// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> data)
{
    List<IDataRecord> list = data.Cast<IDataRecord>().ToList();

    PropertyDescriptorCollection props = null;
    DataTable table = new DataTable();
    if (list != null && list.Count > 0)
    {
        props = TypeDescriptor.GetProperties(list[0]);
        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }
    }
    if (props != null)
    {
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = props[i].GetValue(item) ?? DBNull.Value;
            }
            table.Rows.Add(values);
        }
    }
    return table;
}

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

Please note that PrimeFaces supports the standard JSF 2.0+ keywords:

  • @this Current component.
  • @all Whole view.
  • @form Closest ancestor form of current component.
  • @none No component.

and the standard JSF 2.3+ keywords:

  • @child(n) nth child.
  • @composite Closest composite component ancestor.
  • @id(id) Used to search components by their id ignoring the component tree structure and naming containers.
  • @namingcontainer Closest ancestor naming container of current component.
  • @parent Parent of the current component.
  • @previous Previous sibling.
  • @next Next sibling.
  • @root UIViewRoot instance of the view, can be used to start searching from the root instead the current component.

But, it also comes with some PrimeFaces specific keywords:

  • @row(n) nth row.
  • @widgetVar(name) Component with given widgetVar.

And you can even use something called "PrimeFaces Selectors" which allows you to use jQuery Selector API. For example to process all inputs in a element with the CSS class myClass:

process="@(.myClass :input)"

See:

Error "File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it"

That Problem is because:- The folder or file you pasted to your product downloaded from the firebase console is not named as google-services.json. so now click it then right mouse click in all the options open refractor and rename it to google-services.json. because this worked for me

Split a large pandas dataframe

I wanted to do the same, and I had first problems with the split function, then problems with installing pandas 0.15.2, so I went back to my old version, and wrote a little function that works very well. I hope this can help!

# input - df: a Dataframe, chunkSize: the chunk size
# output - a list of DataFrame
# purpose - splits the DataFrame into smaller chunks
def split_dataframe(df, chunk_size = 10000): 
    chunks = list()
    num_chunks = len(df) // chunk_size + 1
    for i in range(num_chunks):
        chunks.append(df[i*chunk_size:(i+1)*chunk_size])
    return chunks

Styling the arrow on bootstrap tooltips

The arrow is a border.
You need to change for each arrow the color depending on the 'data-placement' of the tooltip.

.tooltip.top .tooltip-arrow {
  border-top-color: @color;
}
.tooltip.top-left .tooltip-arrow {
  border-top-color: @color;
}
.tooltip.top-right .tooltip-arrow {
  border-top-color:@color;
}
.tooltip.right .tooltip-arrow {
  border-right-color: @color;
}
.tooltip.left .tooltip-arrow {
  border-left-color: @color;
}
.tooltip.bottom .tooltip-arrow {
  border-bottom-color: @color;
}
.tooltip.bottom-left .tooltip-arrow {
  border-bottom-color: @color;
}
.tooltip.bottom-right .tooltip-arrow {
  border-bottom-color: @color;
}
.tooltip > .tooltip-inner {
  background-color: @color;
}

Creating virtual directories in IIS express

I had something else, the files itself where inaccessible in a SBS envirenment.

Delete the files in the config folder (if you can't open them!) and replace them with a copy of the folder on your own local pc.

Fixed it for me :)

How do I call a function twice or more times consecutively?

I would:

for _ in range(3):
    do()

The _ is convention for a variable whose value you don't care about.

You might also see some people write:

[do() for _ in range(3)]

however that is slightly more expensive because it creates a list containing the return values of each invocation of do() (even if it's None), and then throws away the resulting list. I wouldn't suggest using this unless you are using the list of return values.

Convert date to UTC using moment.js

This will be the answer:

moment.utc(moment(localdate)).format()
localdate = '2020-01-01 12:00:00'

moment(localdate)
//Moment<2020-01-01T12:00:00+08:00>

moment.utc(moment(localdate)).format()
//2020-01-01T04:00:00Z

How do you count the elements of an array in java

What I think you may want is an ArrayList<Integer> instead of an array. This will allow you do to:

ArrayList<Integer> arr = new ArrayList<Integer>(20);
System.out.println(arr.size());

The output will be 0.

Then, you can add things to the list, and it will keep track of the count for you. (It will also grow the size of the backing storage as you need as well.)

How to clear out session on log out

I use following to clear session and clear aspnet_sessionID:

HttpContext.Current.Session.Clear();
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

How to make an introduction page with Doxygen

As of v1.8.8 there is also the option USE_MDFILE_AS_MAINPAGE. So make sure to add your index file, e.g. README.md, to INPUT and set it as this option's value:

INPUT += README.md
USE_MDFILE_AS_MAINPAGE = README.md

Printing out a linked list using toString

When the JVM tries to run your application, it calls your main method statically; something like this:

LinkedList.main();

That means there is no instance of your LinkedList class. In order to call your toString() method, you can create a new instance of your LinkedList class.

So the body of your main method should be like this:

public static void main(String[] args){
    // creating an instance of LinkedList class
    LinkedList ll = new LinkedList();

    // adding some data to the list
    ll.insertFront(1);
    ll.insertFront(2);
    ll.insertFront(3);
    ll.insertBack(4);

    System.out.println(ll.toString());
}

How to return a part of an array in Ruby?

another way is to use the range method

foo = [1,2,3,4,5,6]
bar = [10,20,30,40,50,60]
a = foo[0...3]
b = bar[3...6]

print a + b 
=> [1, 2, 3, 40, 50 , 60]

Wheel file installation

You normally use a tool like pip to install wheels. Leave it to the tool to discover and download the file if this is for a project hosted on PyPI.

For this to work, you do need to install the wheel package:

pip install wheel

You can then tell pip to install the project (and it'll download the wheel if available), or the wheel file directly:

pip install project_name  # discover, download and install
pip install wheel_file.whl  # directly install the wheel

The wheel module, once installed, also is runnable from the command line, you can use this to install already-downloaded wheels:

python -m wheel install wheel_file.whl

Also see the wheel project documentation.

How to check if a float value is a whole number

You don't need to loop or to check anything. Just take a cube root of 12,000 and round it down:

r = int(12000**(1/3.0))
print r*r*r # 10648

Changing the interval of SetInterval while it's running

I couldn't synchronize and change the speed my setIntervals too and I was about to post a question. But I think I've found a way. It should certainly be improved because I'm a beginner. So, I'd gladly read your comments/remarks about this.

<body onload="foo()">
<div id="count1">0</div>
<div id="count2">2nd counter is stopped</div>
<button onclick="speed0()">pause</button>
<button onclick="speedx(1)">normal speed</button>
<button onclick="speedx(2)">speed x2</button>
<button onclick="speedx(4)">speed x4</button>
<button onclick="startTimer2()">Start second timer</button>
</body>
<script>
var count1 = 0,
    count2 = 0,
    greenlight = new Boolean(0), //blocks 2nd counter
    speed = 1000,   //1second
    countingSpeed;
function foo(){
    countingSpeed = setInterval(function(){
        counter1();
        counter2();
    },speed);
}
function counter1(){
    count1++;
    document.getElementById("count1").innerHTML=count1;
}
function counter2(){
    if (greenlight != false) {
        count2++;
        document.getElementById("count2").innerHTML=count2;
    }
}
function startTimer2(){
    //while the button hasn't been clicked, greenlight boolean is false
    //thus, the 2nd timer is blocked
    greenlight = true;
    counter2();
    //counter2() is greenlighted
}

//these functions modify the speed of the counters
function speed0(){
    clearInterval(countingSpeed);
}
function speedx(a){
    clearInterval(countingSpeed);
    speed=1000/a;
    foo();
}
</script>

If you want the counters to begin to increase once the page is loaded, put counter1() and counter2() in foo() before countingSpeed is called. Otherwise, it takes speed milliseconds before execution. EDIT : Shorter answer.

Test file upload using HTTP PUT method

For curl, how about using the -d switch? Like: curl -X PUT "localhost:8080/urlstuffhere" -d "@filename"?

Warning: comparison with string literals results in unspecified behaviour

This an old question, but I have had to explain it to someone recently and I thought recording the answer here would be helpful at least in understanding how C works.

String literals like

"a"

or

"This is a string"

are put in the text or data segments of your program.

A string in C is actually a pointer to a char, and the string is understood to be the subsequent chars in memory up until a NUL char is encountered. That is, C doesn't really know about strings.

So if I have

char *s1 = "This is a string";

then s1 is a pointer to the first byte of the string.

Now, if I have

char *s2 = "This is a string";

this is also a pointer to the same first byte of that string in the text or data segment of the program.

But if I have

char *s3 = malloc( 17 );
strcpy(s3, "This is a string");

then s3 is a pointer to another place in memory into which I copy all the bytes of the other strings.

Illustrative examples:

Although, as your compiler rightly points out, you shouldn't do this, the following will evaluate to true:

s1 == s2 // True: we are comparing two pointers that contain the same address

but the following will evaluate to false

s1 == s3 // False: Comparing two pointers that don't hold the same address.

And although it might be tempting to have something like this:

struct Vehicle{
    char *type;
    // other stuff
}

if( type == "Car" )
   //blah1
else if( type == "Motorcycle )
   //blah2

You shouldn't do it because it's not something that is guarantied to work. Even if you know that type will always be set using a string literal.

I have tested it and it works. If I do

A.type = "Car";

then blah1 gets executed and similarly for "Motorcycle". And you'd be able to do things like

if( A.type == B.type )

but this is just terrible. I'm writing about it because I think it's interesting to know why it works, and it helps understand why you shouldn't do it.

Solutions:

In your case, what you want to do is use strcmp(a,b) == 0 to replace a == b

In the case of my example, you should use an enum.

enum type {CAR = 0, MOTORCYCLE = 1}

The preceding thing with string was useful because you could print the type, so you might have an array like this

char *types[] = {"Car", "Motorcycle"};

And now that I think about it, this is error prone since one must be careful to maintain the same order in the types array.

Therefore it might be better to do

char *getTypeString(int type)
{
    switch(type)
    case CAR: return "Car";
    case MOTORCYCLE: return "Motorcycle"
    default: return NULL;
}

How should I load files into my Java application?

The short answer

Use one of these two methods:

For example:

InputStream inputStream = YourClass.class.getResourceAsStream("image.jpg");

--

The long answer

Typically, one would not want to load files using absolute paths. For example, don’t do this if you can help it:

File file = new File("C:\\Users\\Joe\\image.jpg");

This technique is not recommended for at least two reasons. First, it creates a dependency on a particular operating system, which prevents the application from easily moving to another operating system. One of Java’s main benefits is the ability to run the same bytecode on many different platforms. Using an absolute path like this makes the code much less portable.

Second, depending on the relative location of the file, this technique might create an external dependency and limit the application’s mobility. If the file exists outside the application’s current directory, this creates an external dependency and one would have to be aware of the dependency in order to move the application to another machine (error prone).

Instead, use the getResource() methods in the Class class. This makes the application much more portable. It can be moved to different platforms, machines, or directories and still function correctly.

Check if date is in the past Javascript

var datep = $('#datepicker').val();

if(Date.parse(datep)-Date.parse(new Date())<0)
{
   // do something
}

How to move all files including hidden files into parent directory via *

Alternative simpler solution is to use rsync utility:

sudo rsync -vuar --delete-after --dry-run path/subfolder/ path/

Note: Above command will show what is going to be changed. To execute the actual changes, remove --dry-run.

The advantage is that the original folder (subfolder) would be removed as well as part of the command, and when using mv examples here you still need to clean up your folders, not to mention additional headache to cover hidden and non-hidden files in one single pattern.

In addition rsync provides support of copying/moving files between remotes and it would make sure that files are copied exactly as they originally were (-a).

The used -u parameter would skip existing newer files, -r recurse into directories and -v would increase verbosity.

Import txt file and having each line as a list

with open('path/to/file') as infile: # try open('...', 'rb') as well
    answer = [line.strip().split(',') for line in infile]

If you want the numbers as ints:

with open('path/to/file') as infile:
    answer = [[int(i) for i in line.strip().split(',')] for line in infile]

Makefile: How to correctly include header file and its directory?

The preprocessor is looking for StdCUtil/split.h in

and in

  • $INC_DIR (i.e. ../StdCUtil/ = /root/Core/../StdCUtil/ = /root/StdCUtil/). So ../StdCUtil/ + StdCUtil/split.h = ../StdCUtil/StdCUtil/split.h and the file is missing

You can fix the error changing the $INC_DIR variable (best solution):

$INC_DIR = ../

or the include directive:

#include "split.h"

but in this way you lost the "path syntax" that makes it very clear what namespace or module the header file belongs to.

Reference:

EDIT/UPDATE

It should also be

CXX = g++
CXXFLAGS = -c -Wall -I$(INC_DIR)

...

%.o: %.cpp $(DEPS)
    $(CXX) -o $@ $< $(CXXFLAGS)

PHP: How to get referrer URL?

$_SERVER['HTTP_REFERER'];

But if you run a file (that contains the above code) by directly hitting the URL in the browser then you get the following error.

Notice: Undefined index: HTTP_REFERER

How to determine if one array contains all elements of another array

This can be achieved by doing

(a2 & a1) == a2

This creates the intersection of both arrays, returning all elements from a2 which are also in a1. If the result is the same as a2, you can be sure you have all elements included in a1.

This approach only works if all elements in a2 are different from each other in the first place. If there are doubles, this approach fails. The one from Tempos still works then, so I wholeheartedly recommend his approach (also it's probably faster).

Map to String in Java

Use Object#toString().

String string = map.toString();

That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

how to parse JSON file with GSON

just parse as an array:

Review[] reviews = new Gson().fromJson(jsonString, Review[].class);

then if you need you can also create a list in this way:

List<Review> asList = Arrays.asList(reviews);

P.S. your json string should be look like this:

[
    {
        "reviewerID": "A2SUAM1J3GNN3B1",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },
    {
        "reviewerID": "A2SUAM1J3GNN3B2",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },

    [...]
]

How to read text file in JavaScript

Yeah it is possible with FileReader, I have already done an example of this, here's the code:

<!DOCTYPE html>
<html>
  <head>
    <title>Read File (via User Input selection)</title>
    <script type="text/javascript">
    var reader; //GLOBAL File Reader object for demo purpose only

    /**
     * Check for the various File API support.
     */
    function checkFileAPI() {
        if (window.File && window.FileReader && window.FileList && window.Blob) {
            reader = new FileReader();
            return true; 
        } else {
            alert('The File APIs are not fully supported by your browser. Fallback required.');
            return false;
        }
    }

    /**
     * read text input
     */
    function readText(filePath) {
        var output = ""; //placeholder for text output
        if(filePath.files && filePath.files[0]) {           
            reader.onload = function (e) {
                output = e.target.result;
                displayContents(output);
            };//end onload()
            reader.readAsText(filePath.files[0]);
        }//end if html5 filelist support
        else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX
            try {
                reader = new ActiveXObject("Scripting.FileSystemObject");
                var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
                output = file.ReadAll(); //text contents of file
                file.Close(); //close file "input stream"
                displayContents(output);
            } catch (e) {
                if (e.number == -2146827859) {
                    alert('Unable to access local files due to browser security settings. ' + 
                     'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' + 
                     'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"'); 
                }
            }       
        }
        else { //this is where you could fallback to Java Applet, Flash or similar
            return false;
        }       
        return true;
    }   

    /**
     * display content using a basic HTML replacement
     */
    function displayContents(txt) {
        var el = document.getElementById('main'); 
        el.innerHTML = txt; //display output in DOM
    }   
</script>
</head>
<body onload="checkFileAPI();">
    <div id="container">    
        <input type="file" onchange='readText(this)' />
        <br/>
        <hr/>   
        <h3>Contents of the Text file:</h3>
        <div id="main">
            ...
        </div>
    </div>
</body>
</html>

It's also possible to do the same thing to support some older versions of IE (I think 6-8) using the ActiveX Object, I had some old code which does that too but its been a while so I'll have to dig it up I've found a solution similar to the one I used courtesy of Jacky Cui's blog and edited this answer (also cleaned up code a bit). Hope it helps.

Lastly, I just read some other answers that beat me to the draw, but as they suggest, you might be looking for code that lets you load a text file from the server (or device) where the JavaScript file is sitting. If that's the case then you want AJAX code to load the document dynamically which would be something as follows:

<!DOCTYPE html>
<html>
<head><meta charset="utf-8" />
<title>Read File (via AJAX)</title>
<script type="text/javascript">
var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');

function loadFile() {
    reader.open('get', 'test.txt', true); 
    reader.onreadystatechange = displayContents;
    reader.send(null);
}

function displayContents() {
    if(reader.readyState==4) {
        var el = document.getElementById('main');
        el.innerHTML = reader.responseText;
    }
}

</script>
</head>
<body>
<div id="container">
    <input type="button" value="test.txt"  onclick="loadFile()" />
    <div id="main">
    </div>
</div>
</body>
</html>

Multiple arguments to function called by pthread_create()?

struct arg_struct *args = (struct arg_struct *)args;

--> this assignment is wrong, I mean the variable argument should be used in this context. Cheers!!!

How do I check what version of Python is running my script?

import sys
sys.version.split(' ')[0]

sys.version gives you what you want, just pick the first number :)

Hashing a dictionary?

I do it like this:

hash(str(my_dict))

What's the best way to detect a 'touch screen' device using JavaScript?

No, it's not possible. The excellent answers given are only ever partial, because any given method will produce false positives and false negatives. Even the browser doesn't always know if a touchscreen is present, due to OS APIs, and the fact can change during a browser session, particularly with KVM-type arrangements.

See further details in this excellent article:

http://www.stucox.com/blog/you-cant-detect-a-touchscreen/

The article suggests you reconsider the assumptions that make you want to detect touchscreens, they're probably wrong. (I checked my own for my app, and my assumptions were indeed wrong!)

The article concludes:

For layouts, assume everyone has a touchscreen. Mouse users can use large UI controls much more easily than touch users can use small ones. The same goes for hover states.

For events and interactions, assume anyone may have a touchscreen. Implement keyboard, mouse and touch interactions alongside each other, ensuring none block each other.

BULK INSERT with identity (auto-increment) column

Add an id column to the csv file and leave it blank:

id,Name,Address
,name1,addr test 1
,name2,addr test 2

Remove KEEPIDENTITY keyword from query:

BULK INSERT Employee  FROM 'path\tempFile.csv ' 
WITH (FIRSTROW = 2,FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n');

The id identity field will be auto-incremented.

If you assign values to the id field in the csv, they'll be ignored unless you use the KEEPIDENTITY keyword, then they'll be used instead of auto-increment.

pip installs packages successfully, but executables not found from command line

In addition to adding python's bin directory to $PATH variable, I also had to change the owner of that directory, to make it work. No idea why I wasn't the owner already.

chown -R ~/Library/Python/

cut or awk command to print first field of first row

sed -n 1p /etc/*release |cut -d " " -f1

if tab delimited:

sed -n 1p /etc/*release |cut -f1

Vertically align text within input field of fixed-height without display: table or padding?

Try :

height: 21px;
line-height: 21px; /* FOR IE */

Because on some versions of IE (< 9) the property height is not properly interpreted.

How to pull remote branch from somebody else's repo

If the forked repo is protected so you can't push directly into it, and your goal is to make changes to their foo, then you need to get their branch foo into your repo like so:

git remote add protected_repo https://github.com/theirusername/their_repo.git
git fetch protected_repo 
git checkout --no-track protected_repo/foo

Now you have a local copy of foo with no upstream associated to it. You can commit changes to it (or not) and then push your foo to your own remote repo.

git push --set-upstream origin foo

Now foo is in your repo on GitHub and your local foo is tracking it. If they continue to make changes to foo you can fetch theirs and merge into your foo.

git checkout foo 
git fetch protected_repo
git merge protected_repo/foo

"UnboundLocalError: local variable referenced before assignment" after an if statement

I was facing same issue in my exercise. Although not related, yet might give some reference. I didn't get any error once I placed addition_result = 0 inside function. Hope it helps! Apologize if this answer is not in context.

user_input = input("Enter multiple values separated by comma > ")

def add_numbers(num_list):
    addition_result = 0
    for i in num_list:
        addition_result = addition_result + i
    print(addition_result)

add_numbers(user_input)

JQuery add class to parent element

$(this.parentNode).addClass('newClass');

Get difference between two dates in months using Java

You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

How to use if, else condition in jsf to display image

Instead of using the "c" tags, you could also do the following:

<h:outputLink value="Images/thumb_02.jpg" target="_blank" rendered="#{not empty user or user.userId eq 0}" />
<h:graphicImage value="Images/thumb_02.jpg" rendered="#{not empty user or user.userId eq 0}" />

<h:outputLink value="/DisplayBlobExample?userId=#{user.userId}" target="_blank" rendered="#{not empty user and user.userId neq 0}" />
<h:graphicImage value="/DisplayBlobExample?userId=#{user.userId}" rendered="#{not empty user and user.userId neq 0}"/>

I think that's a little more readable alternative to skuntsel's alternative answer and is utilizing the JSF rendered attribute instead of nesting a ternary operator. And off the answer, did you possibly mean to put your image in between the anchor tags so the image is clickable?

Spring Data JPA find by embedded object property

According to me, Spring doesn't handle all the cases with ease. In your case the following should do the trick

Page<QueuedBook> findByBookIdRegion(Region region, Pageable pageable);  

or

Page<QueuedBook> findByBookId_Region(Region region, Pageable pageable);

However, it also depends on the naming convention of fields that you have in your @Embeddable class,

e.g. the following field might not work in any of the styles that mentioned above

private String cRcdDel;

I tried with both the cases (as follows) and it didn't work (it seems like Spring doesn't handle this type of naming conventions(i.e. to many Caps , especially in the beginning - 2nd letter (not sure about if this is the only case though)

Page<QueuedBook> findByBookIdCRcdDel(String cRcdDel, Pageable pageable); 

or

Page<QueuedBook> findByBookIdCRcdDel(String cRcdDel, Pageable pageable);

When I renamed column to

private String rcdDel;

my following solutions work fine without any issue:

Page<QueuedBook> findByBookIdRcdDel(String rcdDel, Pageable pageable); 

OR

Page<QueuedBook> findByBookIdRcdDel(String rcdDel, Pageable pageable);

PowerShell: Create Local User Account

Import-Csv C:\test.csv |
Foreach-Object {
  NET USER    $ _.username   $ _.password /ADD
  NET LOCALGROUP "group" $_.username  /ADD
}

edit csv as username,password and change "group" for your groupname

:) worked on 2012 R2

GLYPHICONS - bootstrap icon font hex value

We can find these by looking at Bootstrap's stylesheet, Bootstrap.css. Each \{number} represents a hexadecimal value, so \2a is equal to 0x2a or &#x2a;.

As for the font, that can be downloaded from http://glyphicons.com.

.glyphicon-asterisk:before {
  content: "\2a";
}

.glyphicon-plus:before {
  content: "\2b";
}

.glyphicon-euro:before {
  content: "\20ac";
}

.glyphicon-minus:before {
  content: "\2212";
}

.glyphicon-cloud:before {
  content: "\2601";
}

.glyphicon-envelope:before {
  content: "\2709";
}

.glyphicon-pencil:before {
  content: "\270f";
}

.glyphicon-glass:before {
  content: "\e001";
}

.glyphicon-music:before {
  content: "\e002";
}

.glyphicon-search:before {
  content: "\e003";
}

.glyphicon-heart:before {
  content: "\e005";
}

.glyphicon-star:before {
  content: "\e006";
}

.glyphicon-star-empty:before {
  content: "\e007";
}

.glyphicon-user:before {
  content: "\e008";
}

.glyphicon-film:before {
  content: "\e009";
}

.glyphicon-th-large:before {
  content: "\e010";
}

.glyphicon-th:before {
  content: "\e011";
}

.glyphicon-th-list:before {
  content: "\e012";
}

.glyphicon-ok:before {
  content: "\e013";
}

.glyphicon-remove:before {
  content: "\e014";
}

.glyphicon-zoom-in:before {
  content: "\e015";
}

.glyphicon-zoom-out:before {
  content: "\e016";
}

.glyphicon-off:before {
  content: "\e017";
}

.glyphicon-signal:before {
  content: "\e018";
}

.glyphicon-cog:before {
  content: "\e019";
}

.glyphicon-trash:before {
  content: "\e020";
}

.glyphicon-home:before {
  content: "\e021";
}

.glyphicon-file:before {
  content: "\e022";
}

.glyphicon-time:before {
  content: "\e023";
}

.glyphicon-road:before {
  content: "\e024";
}

.glyphicon-download-alt:before {
  content: "\e025";
}

.glyphicon-download:before {
  content: "\e026";
}

.glyphicon-upload:before {
  content: "\e027";
}

.glyphicon-inbox:before {
  content: "\e028";
}

.glyphicon-play-circle:before {
  content: "\e029";
}

.glyphicon-repeat:before {
  content: "\e030";
}

.glyphicon-refresh:before {
  content: "\e031";
}

.glyphicon-list-alt:before {
  content: "\e032";
}

.glyphicon-lock:before {
  content: "\e033";
}

.glyphicon-flag:before {
  content: "\e034";
}

.glyphicon-headphones:before {
  content: "\e035";
}

.glyphicon-volume-off:before {
  content: "\e036";
}

.glyphicon-volume-down:before {
  content: "\e037";
}

.glyphicon-volume-up:before {
  content: "\e038";
}

.glyphicon-qrcode:before {
  content: "\e039";
}

.glyphicon-barcode:before {
  content: "\e040";
}

.glyphicon-tag:before {
  content: "\e041";
}

.glyphicon-tags:before {
  content: "\e042";
}

.glyphicon-book:before {
  content: "\e043";
}

.glyphicon-bookmark:before {
  content: "\e044";
}

.glyphicon-print:before {
  content: "\e045";
}

.glyphicon-camera:before {
  content: "\e046";
}

.glyphicon-font:before {
  content: "\e047";
}

.glyphicon-bold:before {
  content: "\e048";
}

.glyphicon-italic:before {
  content: "\e049";
}

.glyphicon-text-height:before {
  content: "\e050";
}

.glyphicon-text-width:before {
  content: "\e051";
}

.glyphicon-align-left:before {
  content: "\e052";
}

.glyphicon-align-center:before {
  content: "\e053";
}

.glyphicon-align-right:before {
  content: "\e054";
}

.glyphicon-align-justify:before {
  content: "\e055";
}

.glyphicon-list:before {
  content: "\e056";
}

.glyphicon-indent-left:before {
  content: "\e057";
}

.glyphicon-indent-right:before {
  content: "\e058";
}

.glyphicon-facetime-video:before {
  content: "\e059";
}

.glyphicon-picture:before {
  content: "\e060";
}

.glyphicon-map-marker:before {
  content: "\e062";
}

.glyphicon-adjust:before {
  content: "\e063";
}

.glyphicon-tint:before {
  content: "\e064";
}

.glyphicon-edit:before {
  content: "\e065";
}

.glyphicon-share:before {
  content: "\e066";
}

.glyphicon-check:before {
  content: "\e067";
}

.glyphicon-move:before {
  content: "\e068";
}

.glyphicon-step-backward:before {
  content: "\e069";
}

.glyphicon-fast-backward:before {
  content: "\e070";
}

.glyphicon-backward:before {
  content: "\e071";
}

.glyphicon-play:before {
  content: "\e072";
}

.glyphicon-pause:before {
  content: "\e073";
}

.glyphicon-stop:before {
  content: "\e074";
}

.glyphicon-forward:before {
  content: "\e075";
}

.glyphicon-fast-forward:before {
  content: "\e076";
}

.glyphicon-step-forward:before {
  content: "\e077";
}

.glyphicon-eject:before {
  content: "\e078";
}

.glyphicon-chevron-left:before {
  content: "\e079";
}

.glyphicon-chevron-right:before {
  content: "\e080";
}

.glyphicon-plus-sign:before {
  content: "\e081";
}

.glyphicon-minus-sign:before {
  content: "\e082";
}

.glyphicon-remove-sign:before {
  content: "\e083";
}

.glyphicon-ok-sign:before {
  content: "\e084";
}

.glyphicon-question-sign:before {
  content: "\e085";
}

.glyphicon-info-sign:before {
  content: "\e086";
}

.glyphicon-screenshot:before {
  content: "\e087";
}

.glyphicon-remove-circle:before {
  content: "\e088";
}

.glyphicon-ok-circle:before {
  content: "\e089";
}

.glyphicon-ban-circle:before {
  content: "\e090";
}

.glyphicon-arrow-left:before {
  content: "\e091";
}

.glyphicon-arrow-right:before {
  content: "\e092";
}

.glyphicon-arrow-up:before {
  content: "\e093";
}

.glyphicon-arrow-down:before {
  content: "\e094";
}

.glyphicon-share-alt:before {
  content: "\e095";
}

.glyphicon-resize-full:before {
  content: "\e096";
}

.glyphicon-resize-small:before {
  content: "\e097";
}

.glyphicon-exclamation-sign:before {
  content: "\e101";
}

.glyphicon-gift:before {
  content: "\e102";
}

.glyphicon-leaf:before {
  content: "\e103";
}

.glyphicon-fire:before {
  content: "\e104";
}

.glyphicon-eye-open:before {
  content: "\e105";
}

.glyphicon-eye-close:before {
  content: "\e106";
}

.glyphicon-warning-sign:before {
  content: "\e107";
}

.glyphicon-plane:before {
  content: "\e108";
}

.glyphicon-calendar:before {
  content: "\e109";
}

.glyphicon-random:before {
  content: "\e110";
}

.glyphicon-comment:before {
  content: "\e111";
}

.glyphicon-magnet:before {
  content: "\e112";
}

.glyphicon-chevron-up:before {
  content: "\e113";
}

.glyphicon-chevron-down:before {
  content: "\e114";
}

.glyphicon-retweet:before {
  content: "\e115";
}

.glyphicon-shopping-cart:before {
  content: "\e116";
}

.glyphicon-folder-close:before {
  content: "\e117";
}

.glyphicon-folder-open:before {
  content: "\e118";
}

.glyphicon-resize-vertical:before {
  content: "\e119";
}

.glyphicon-resize-horizontal:before {
  content: "\e120";
}

.glyphicon-hdd:before {
  content: "\e121";
}

.glyphicon-bullhorn:before {
  content: "\e122";
}

.glyphicon-bell:before {
  content: "\e123";
}

.glyphicon-certificate:before {
  content: "\e124";
}

.glyphicon-thumbs-up:before {
  content: "\e125";
}

.glyphicon-thumbs-down:before {
  content: "\e126";
}

.glyphicon-hand-right:before {
  content: "\e127";
}

.glyphicon-hand-left:before {
  content: "\e128";
}

.glyphicon-hand-up:before {
  content: "\e129";
}

.glyphicon-hand-down:before {
  content: "\e130";
}

.glyphicon-circle-arrow-right:before {
  content: "\e131";
}

.glyphicon-circle-arrow-left:before {
  content: "\e132";
}

.glyphicon-circle-arrow-up:before {
  content: "\e133";
}

.glyphicon-circle-arrow-down:before {
  content: "\e134";
}

.glyphicon-globe:before {
  content: "\e135";
}

.glyphicon-wrench:before {
  content: "\e136";
}

.glyphicon-tasks:before {
  content: "\e137";
}

.glyphicon-filter:before {
  content: "\e138";
}

.glyphicon-briefcase:before {
  content: "\e139";
}

.glyphicon-fullscreen:before {
  content: "\e140";
}

.glyphicon-dashboard:before {
  content: "\e141";
}

.glyphicon-paperclip:before {
  content: "\e142";
}

.glyphicon-heart-empty:before {
  content: "\e143";
}

.glyphicon-link:before {
  content: "\e144";
}

.glyphicon-phone:before {
  content: "\e145";
}

.glyphicon-pushpin:before {
  content: "\e146";
}

.glyphicon-usd:before {
  content: "\e148";
}

.glyphicon-gbp:before {
  content: "\e149";
}

.glyphicon-sort:before {
  content: "\e150";
}

.glyphicon-sort-by-alphabet:before {
  content: "\e151";
}

.glyphicon-sort-by-alphabet-alt:before {
  content: "\e152";
}

.glyphicon-sort-by-order:before {
  content: "\e153";
}

.glyphicon-sort-by-order-alt:before {
  content: "\e154";
}

.glyphicon-sort-by-attributes:before {
  content: "\e155";
}

.glyphicon-sort-by-attributes-alt:before {
  content: "\e156";
}

.glyphicon-unchecked:before {
  content: "\e157";
}

.glyphicon-expand:before {
  content: "\e158";
}

.glyphicon-collapse-down:before {
  content: "\e159";
}

.glyphicon-collapse-up:before {
  content: "\e160";
}

.glyphicon-log-in:before {
  content: "\e161";
}

.glyphicon-flash:before {
  content: "\e162";
}

.glyphicon-log-out:before {
  content: "\e163";
}

.glyphicon-new-window:before {
  content: "\e164";
}

.glyphicon-record:before {
  content: "\e165";
}

.glyphicon-save:before {
  content: "\e166";
}

.glyphicon-open:before {
  content: "\e167";
}

.glyphicon-saved:before {
  content: "\e168";
}

.glyphicon-import:before {
  content: "\e169";
}

.glyphicon-export:before {
  content: "\e170";
}

.glyphicon-send:before {
  content: "\e171";
}

.glyphicon-floppy-disk:before {
  content: "\e172";
}

.glyphicon-floppy-saved:before {
  content: "\e173";
}

.glyphicon-floppy-remove:before {
  content: "\e174";
}

.glyphicon-floppy-save:before {
  content: "\e175";
}

.glyphicon-floppy-open:before {
  content: "\e176";
}

.glyphicon-credit-card:before {
  content: "\e177";
}

.glyphicon-transfer:before {
  content: "\e178";
}

.glyphicon-cutlery:before {
  content: "\e179";
}

.glyphicon-header:before {
  content: "\e180";
}

.glyphicon-compressed:before {
  content: "\e181";
}

.glyphicon-earphone:before {
  content: "\e182";
}

.glyphicon-phone-alt:before {
  content: "\e183";
}

.glyphicon-tower:before {
  content: "\e184";
}

.glyphicon-stats:before {
  content: "\e185";
}

.glyphicon-sd-video:before {
  content: "\e186";
}

.glyphicon-hd-video:before {
  content: "\e187";
}

.glyphicon-subtitles:before {
  content: "\e188";
}

.glyphicon-sound-stereo:before {
  content: "\e189";
}

.glyphicon-sound-dolby:before {
  content: "\e190";
}

.glyphicon-sound-5-1:before {
  content: "\e191";
}

.glyphicon-sound-6-1:before {
  content: "\e192";
}

.glyphicon-sound-7-1:before {
  content: "\e193";
}

.glyphicon-copyright-mark:before {
  content: "\e194";
}

.glyphicon-registration-mark:before {
  content: "\e195";
}

.glyphicon-cloud-download:before {
  content: "\e197";
}

.glyphicon-cloud-upload:before {
  content: "\e198";
}

.glyphicon-tree-conifer:before {
  content: "\e199";
}

.glyphicon-tree-deciduous:before {
  content: "\e200";
}

Fatal error: iostream: No such file or directory in compiling C program using GCC

Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t. I am glad that you did.

Anyways, You have a .c source file, and most of the code looks as per C standards, except that #include <iostream> and using namespace std;

C equivalent for the built-in functions of C++ standard #include<iostream> can be availed through #include<stdio.h>

  1. Replace #include <iostream> with #include <stdio.h>, delete using namespace std;
  2. With #include <iostream> taken off, you would need a C standard alternative for cout << endl;, which can be done by printf("\n"); or putchar('\n');
    Out of the two options, printf("\n"); works the faster as I observed.

    When used printf("\n"); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.031s
    user    0m0.030s
    sys     0m0.030s
    

    When used putchar('\n'); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.047s
    user    0m0.030s
    sys     0m0.030s
    

Compiled with Cygwin gcc (GCC) 4.8.3 version. results averaged over 10 samples. (Took me 15 mins)

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

Simplicity of this technique is stunning:
(This method has its implications though, but if you only need to center element regardless of flow of the rest of the content, it's just fine. Use with care)

Markup:

<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum accumsan tellus purus, et mollis nulla consectetur ac. Quisque id elit at diam convallis venenatis eget sed justo. Nunc egestas enim mauris, sit amet tempor risus ultricies in. Sed dignissim magna erat, vel laoreet tortor bibendum vitae. Ut porttitor tincidunt est imperdiet vestibulum. Vivamus id nibh tellus. Integer massa orci, gravida non imperdiet sed, consectetur ac quam. Nunc dignissim felis id tortor tincidunt, a eleifend nulla molestie. Phasellus eleifend leo purus, vel facilisis massa dignissim vitae. Pellentesque libero sapien, tincidunt ut lorem non, porta accumsan risus. Morbi tempus pharetra ex, vel luctus turpis tempus eu. Integer vitae sagittis massa, id gravida erat. Maecenas sed purus et magna tincidunt faucibus nec eget erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc nec mollis sem.</div>

And CSS:

div {
  color: white;
  background: red;
  padding: 15px;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translateX(-50%) translateY(-50%);
  -webkit-transform: translate(-50%,-50%);
  transform: translate(-50%,-50%);
}   

This will center element horizontally and vertically too. No negative margins, just power of transforms. Also we should already forget about IE8 shouldn't we?

onclick="location.href='link.html'" does not load page in Safari

I had the same error. Make sure you don't have any <input>, <select>, etc. name="location".

Change output format for MySQL command line results to CSV

mysql client can detect the output fd, if the fd is S_IFIFO(pipe) then don't output ASCII TABLES, if the fd is character device(S_IFCHR) then output ASCII TABLES.

you can use --table to force output the ASCII TABLES like:

$mysql -t -N -h127.0.0.1 -e "select id from sbtest1 limit 1" | cat
+--------+
| 100024 |
+--------+

-t, --table Output in table format.

How to see full absolute path of a symlink

unix flavors -> ll symLinkName

OSX -> readlink symLinkName

Difference is 1st way would display the sym link path in a blinking way and 2nd way would just echo it out on the console.

How to check for a Null value in VB.NET

The equivalent of null in VB is Nothing so your check wants to be:

If editTransactionRow.pay_id IsNot Nothing Then
    stTransactionPaymentID = editTransactionRow.pay_id
End If

Or possibly, if you are actually wanting to check for a SQL null value:

If editTransactionRow.pay_id <> DbNull.Value Then
    ...
End If

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

This error message...

Selenium message:session not created: This version of ChromeDriver only supports Chrome version 74
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Mac OS X 10.14.3 x86_64)

...implies that the ChromeDriver expects the Chrome Browser version to be 74.


Quick installation of the latest ChromeDriver

To install the latest version of ChromeDriver you can use:

  • Mac users with Homebrew: brew tap homebrew/cask && brew cask install chromedriver
  • Debian based Linux distros: sudo apt-get install chromium-chromedriver
  • Windows users with Chocolatey installed: choco install chromedriver

Analysis

Your main issue is the incompatibility between the version of the binaries you are using as follows:

Supports Chrome v74

  • You are using the currently released chrome=73.0

So there is a clear mismatch between the ChromeDriver v74.0.3729.6 and the Chrome Browser v73.0


Solution

  • Downgrade ChromeDriver to ChromeDriver v73.0.3683.68 level.
  • Keep Chrome version at Chrome v73 level. (as per ChromeDriver v73.0.3683.68 release notes)
  • Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.
  • If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.
  • Execute your @Test.
  • Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.

Reference

You can find a relevant detailed discussion in:

Error on line 2 at column 1: Extra content at the end of the document

You might have output (maybe error/debug output) that precedes your call to

header("Content-type: text/xml");

Therefore, the content being delivered to the browser is not "xml"... that's what the error message is trying to tell you (at least that was the case for me and I had the same error message as you've described).

Angular 2: Passing Data to Routes?

You can do this:

app-routing-modules.ts:

import { NgModule                  }    from '@angular/core';
import { RouterModule, Routes      }    from '@angular/router';
import { PowerBoosterComponent     }    from './component/power-booster.component';


export const routes: Routes = [
  { path:  'pipeexamples',component: PowerBoosterComponent, 
data:{  name:'shubham' } },
    ];
    @NgModule({
      imports: [ RouterModule.forRoot(routes) ],
      exports: [ RouterModule ]
    })
    export class AppRoutingModule {}

In this above route, I want to send data via a pipeexamples path to PowerBoosterComponent.So now I can receive this data in PowerBoosterComponent like this:

power-booster-component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';

@Component({
  selector: 'power-booster',
  template: `
    <h2>Power Booster</h2>`
})

export class PowerBoosterComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router

  ) { }
  ngOnInit() {
    //this.route.snapshot.data['name']
    console.log("Data via params: ",this.route.snapshot.data['name']);
  }
}

So you can get the data by this.route.snapshot.data['name'].

Hard reset of a single file

Reset to head:

To hard reset a single file to HEAD:

git checkout @ -- myfile.ext

Note that @ is short for HEAD. An older version of git may not support the short form.

Reset to index:

To hard reset a single file to the index, assuming the index is non-empty, otherwise to HEAD:

git checkout -- myfile.ext

The point is that to be safe, you don't want to leave out @ or HEAD from the command unless you specifically mean to reset to the index only.

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

I would assume that one might want a solution that produces a widely useable base64 URI. Please visit data:text/plain;charset=utf-8;base64,4pi44pi54pi64pi74pi84pi+4pi/ to see a demonstration (copy the data uri, open a new tab, paste the data URI into the address bar, then press enter to go to the page). Despite the fact that this URI is base64-encoded, the browser is still able to recognize the high code points and decode them properly. The minified encoder+decoder is 1058 bytes (+Gzip?589 bytes)

!function(e){"use strict";function h(b){var a=b.charCodeAt(0);if(55296<=a&&56319>=a)if(b=b.charCodeAt(1),b===b&&56320<=b&&57343>=b){if(a=1024*(a-55296)+b-56320+65536,65535<a)return d(240|a>>>18,128|a>>>12&63,128|a>>>6&63,128|a&63)}else return d(239,191,189);return 127>=a?inputString:2047>=a?d(192|a>>>6,128|a&63):d(224|a>>>12,128|a>>>6&63,128|a&63)}function k(b){var a=b.charCodeAt(0)<<24,f=l(~a),c=0,e=b.length,g="";if(5>f&&e>=f){a=a<<f>>>24+f;for(c=1;c<f;++c)a=a<<6|b.charCodeAt(c)&63;65535>=a?g+=d(a):1114111>=a?(a-=65536,g+=d((a>>10)+55296,(a&1023)+56320)):c=0}for(;c<e;++c)g+="\ufffd";return g}var m=Math.log,n=Math.LN2,l=Math.clz32||function(b){return 31-m(b>>>0)/n|0},d=String.fromCharCode,p=atob,q=btoa;e.btoaUTF8=function(b,a){return q((a?"\u00ef\u00bb\u00bf":"")+b.replace(/[\x80-\uD7ff\uDC00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g,h))};e.atobUTF8=function(b,a){a||"\u00ef\u00bb\u00bf"!==b.substring(0,3)||(b=b.substring(3));return p(b).replace(/[\xc0-\xff][\x80-\xbf]*/g,k)}}(""+void 0==typeof global?""+void 0==typeof self?this:self:global)

Below is the source code used to generate it.

var fromCharCode = String.fromCharCode;
var btoaUTF8 = (function(btoa, replacer){"use strict";
    return function(inputString, BOMit){
        return btoa((BOMit ? "\xEF\xBB\xBF" : "") + inputString.replace(
            /[\x80-\uD7ff\uDC00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, replacer
        ));
    }
})(btoa, function(nonAsciiChars){"use strict";
    // make the UTF string into a binary UTF-8 encoded string
    var point = nonAsciiChars.charCodeAt(0);
    if (point >= 0xD800 && point <= 0xDBFF) {
        var nextcode = nonAsciiChars.charCodeAt(1);
        if (nextcode !== nextcode) // NaN because string is 1 code point long
            return fromCharCode(0xef/*11101111*/, 0xbf/*10111111*/, 0xbd/*10111101*/);
        // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
        if (nextcode >= 0xDC00 && nextcode <= 0xDFFF) {
            point = (point - 0xD800) * 0x400 + nextcode - 0xDC00 + 0x10000;
            if (point > 0xffff)
                return fromCharCode(
                    (0x1e/*0b11110*/<<3) | (point>>>18),
                    (0x2/*0b10*/<<6) | ((point>>>12)&0x3f/*0b00111111*/),
                    (0x2/*0b10*/<<6) | ((point>>>6)&0x3f/*0b00111111*/),
                    (0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/)
                );
        } else return fromCharCode(0xef, 0xbf, 0xbd);
    }
    if (point <= 0x007f) return nonAsciiChars;
    else if (point <= 0x07ff) {
        return fromCharCode((0x6<<5)|(point>>>6), (0x2<<6)|(point&0x3f));
    } else return fromCharCode(
        (0xe/*0b1110*/<<4) | (point>>>12),
        (0x2/*0b10*/<<6) | ((point>>>6)&0x3f/*0b00111111*/),
        (0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/)
    );
});

Then, to decode the base64 data, either HTTP get the data as a data URI or use the function below.

var clz32 = Math.clz32 || (function(log, LN2){"use strict";
    return function(x) {return 31 - log(x >>> 0) / LN2 | 0};
})(Math.log, Math.LN2);
var fromCharCode = String.fromCharCode;
var atobUTF8 = (function(atob, replacer){"use strict";
    return function(inputString, keepBOM){
        inputString = atob(inputString);
        if (!keepBOM && inputString.substring(0,3) === "\xEF\xBB\xBF")
            inputString = inputString.substring(3); // eradicate UTF-8 BOM
        // 0xc0 => 0b11000000; 0xff => 0b11111111; 0xc0-0xff => 0b11xxxxxx
        // 0x80 => 0b10000000; 0xbf => 0b10111111; 0x80-0xbf => 0b10xxxxxx
        return inputString.replace(/[\xc0-\xff][\x80-\xbf]*/g, replacer);
    }
})(atob, function(encoded){"use strict";
    var codePoint = encoded.charCodeAt(0) << 24;
    var leadingOnes = clz32(~codePoint);
    var endPos = 0, stringLen = encoded.length;
    var result = "";
    if (leadingOnes < 5 && stringLen >= leadingOnes) {
        codePoint = (codePoint<<leadingOnes)>>>(24+leadingOnes);
        for (endPos = 1; endPos < leadingOnes; ++endPos)
            codePoint = (codePoint<<6) | (encoded.charCodeAt(endPos)&0x3f/*0b00111111*/);
        if (codePoint <= 0xFFFF) { // BMP code point
          result += fromCharCode(codePoint);
        } else if (codePoint <= 0x10FFFF) {
          // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
          codePoint -= 0x10000;
          result += fromCharCode(
            (codePoint >> 10) + 0xD800,  // highSurrogate
            (codePoint & 0x3ff) + 0xDC00 // lowSurrogate
          );
        } else endPos = 0; // to fill it in with INVALIDs
    }
    for (; endPos < stringLen; ++endPos) result += "\ufffd"; // replacement character
    return result;
});

The advantage of being more standard is that this encoder and this decoder are more widely applicable because they can be used as a valid URL that displays correctly. Observe.

_x000D_
_x000D_
(function(window){_x000D_
    "use strict";_x000D_
    var sourceEle = document.getElementById("source");_x000D_
    var urlBarEle = document.getElementById("urlBar");_x000D_
    var mainFrameEle = document.getElementById("mainframe");_x000D_
    var gotoButton = document.getElementById("gotoButton");_x000D_
    var parseInt = window.parseInt;_x000D_
    var fromCodePoint = String.fromCodePoint;_x000D_
    var parse = JSON.parse;_x000D_
    _x000D_
    function unescape(str){_x000D_
        return str.replace(/\\u[\da-f]{0,4}|\\x[\da-f]{0,2}|\\u{[^}]*}|\\[bfnrtv"'\\]|\\0[0-7]{1,3}|\\\d{1,3}/g, function(match){_x000D_
          try{_x000D_
            if (match.startsWith("\\u{"))_x000D_
              return fromCodePoint(parseInt(match.slice(2,-1),16));_x000D_
            if (match.startsWith("\\u") || match.startsWith("\\x"))_x000D_
              return fromCodePoint(parseInt(match.substring(2),16));_x000D_
            if (match.startsWith("\\0") && match.length > 2)_x000D_
              return fromCodePoint(parseInt(match.substring(2),8));_x000D_
            if (/^\\\d/.test(match)) return fromCodePoint(+match.slice(1));_x000D_
          }catch(e){return "\ufffd".repeat(match.length)}_x000D_
          return parse('"' + match + '"');_x000D_
        });_x000D_
    }_x000D_
    _x000D_
    function whenChange(){_x000D_
      try{ urlBarEle.value = "data:text/plain;charset=UTF-8;base64," + btoaUTF8(unescape(sourceEle.value), true);_x000D_
      } finally{ gotoURL(); }_x000D_
    }_x000D_
    sourceEle.addEventListener("change",whenChange,{passive:1});_x000D_
    sourceEle.addEventListener("input",whenChange,{passive:1});_x000D_
    _x000D_
    // IFrame Setup:_x000D_
    function gotoURL(){mainFrameEle.src = urlBarEle.value}_x000D_
    gotoButton.addEventListener("click", gotoURL, {passive: 1});_x000D_
    function urlChanged(){urlBarEle.value = mainFrameEle.src}_x000D_
    mainFrameEle.addEventListener("load", urlChanged, {passive: 1});_x000D_
    urlBarEle.addEventListener("keypress", function(evt){_x000D_
      if (evt.key === "enter") evt.preventDefault(), urlChanged();_x000D_
    }, {passive: 1});_x000D_
    _x000D_
        _x000D_
    var fromCharCode = String.fromCharCode;_x000D_
    var btoaUTF8 = (function(btoa, replacer){_x000D_
      "use strict";_x000D_
        return function(inputString, BOMit){_x000D_
         return btoa((BOMit?"\xEF\xBB\xBF":"") + inputString.replace(_x000D_
          /[\x80-\uD7ff\uDC00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, replacer_x000D_
      ));_x000D_
     }_x000D_
    })(btoa, function(nonAsciiChars){_x000D_
  "use strict";_x000D_
     // make the UTF string into a binary UTF-8 encoded string_x000D_
     var point = nonAsciiChars.charCodeAt(0);_x000D_
     if (point >= 0xD800 && point <= 0xDBFF) {_x000D_
      var nextcode = nonAsciiChars.charCodeAt(1);_x000D_
      if (nextcode !== nextcode) { // NaN because string is 1code point long_x000D_
       return fromCharCode(0xef/*11101111*/, 0xbf/*10111111*/, 0xbd/*10111101*/);_x000D_
      }_x000D_
      // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae_x000D_
      if (nextcode >= 0xDC00 && nextcode <= 0xDFFF) {_x000D_
       point = (point - 0xD800) * 0x400 + nextcode - 0xDC00 + 0x10000;_x000D_
       if (point > 0xffff) {_x000D_
        return fromCharCode(_x000D_
         (0x1e/*0b11110*/<<3) | (point>>>18),_x000D_
         (0x2/*0b10*/<<6) | ((point>>>12)&0x3f/*0b00111111*/),_x000D_
         (0x2/*0b10*/<<6) | ((point>>>6)&0x3f/*0b00111111*/),_x000D_
         (0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/)_x000D_
        );_x000D_
       }_x000D_
      } else {_x000D_
       return fromCharCode(0xef, 0xbf, 0xbd);_x000D_
      }_x000D_
     }_x000D_
     if (point <= 0x007f) { return inputString; }_x000D_
     else if (point <= 0x07ff) {_x000D_
      return fromCharCode((0x6<<5)|(point>>>6), (0x2<<6)|(point&0x3f/*00111111*/));_x000D_
     } else {_x000D_
      return fromCharCode(_x000D_
       (0xe/*0b1110*/<<4) | (point>>>12),_x000D_
       (0x2/*0b10*/<<6) | ((point>>>6)&0x3f/*0b00111111*/),_x000D_
       (0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/)_x000D_
      );_x000D_
     }_x000D_
    });_x000D_
    setTimeout(whenChange, 0);_x000D_
})(window);
_x000D_
img:active{opacity:0.8}
_x000D_
<center>_x000D_
<textarea id="source" style="width:66.7vw">Hello \u1234 W\186\0256ld!_x000D_
Enter text into the top box. Then the URL will update automatically._x000D_
</textarea><br />_x000D_
<div style="width:66.7vw;display:inline-block;height:calc(25vw + 1em + 6px);border:2px solid;text-align:left;line-height:1em">_x000D_
<input id="urlBar" style="width:calc(100% - 1em - 13px)" /><img id="gotoButton" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABsAAAAeCAMAAADqx5XUAAAAclBMVEX///9NczZ8e32ko6fDxsU/fBoSQgdFtwA5pAHVxt+7vLzq5ex23y4SXABLiiTm0+/c2N6DhoQ6WSxSyweVlZVvdG/Uz9aF5kYlbwElkwAggACxs7Jl3hX07/cQbQCar5SU9lRntEWGum+C9zIDHwCGnH5IvZAOAAABmUlEQVQoz7WS25acIBBFkRLkIgKKtOCttbv//xdDmTGZzHv2S63ltuBQQP4rdRiRUP8UK4wh6nVddQwj/NtDQTvac8577zTQb72zj65/876qqt7wykU6/1U6vFEgjE1mt/5LRqrpu7oVsn0sjZejMfxR3W/yLikqAFcUx93YxLmZGOtElmEu6Ufd9xV3ZDTGcEvGLbMk0mHHlUSvS5svCwS+hVL8loQQyfpI1Ay8RF/xlNxcsTchGjGDIuBG3Ik7TMyNxn8m0TSnBAK6Z8UZfp3IbAonmJvmsEACum6aNv7B0CnvpezDcNhw9XWsuAr7qnRg6dABmeM4dTgn/DZdXWs3LMspZ1KDMt1kcPJ6S1icWNp2qaEmjq6myx7jbQK3VKItLJaW5FR+cuYlRhYNKzGa9vF4vM5roLW3OSVjkmiGJrPhUq301/16pVKZRGFYWjTP50spTxBN5Z4EKnSonruk+n4tUokv1aJSEl/MLZU90S3L6/U6o0J142iQVp3HcZxKSo8LfkNRCtJaKYFSRX7iaoAAUDty8wvWYR6HJEepdwAAAABJRU5ErkJggg==" style="width:calc(1em + 4px);line-height:1em;vertical-align:-40%;cursor:pointer" />_x000D_
<iframe id="mainframe" style="width:66.7vw;height:25vw" frameBorder="0"></iframe>_x000D_
</div>_x000D_
</center>
_x000D_
_x000D_
_x000D_

In addition to being very standardized, the above code snippets are also very fast. Instead of an indirect chain of succession where the data has to be converted several times between various forms (such as in Riccardo Galli's response), the above code snippet is as direct as performantly possible. It uses only one simple fast String.prototype.replace call to process the data when encoding, and only one to decode the data when decoding. Another plus is that (especially for big strings), String.prototype.replace allows the browser to automatically handle the underlying memory management of resizing the string, leading a significant performance boost especially in evergreen browsers like Chrome and Firefox that heavily optimize String.prototype.replace. Finally, the icing on the cake is that for you latin script exclusivo users, strings which don't contain any code points above 0x7f are extra fast to process because the string remains unmodified by the replacement algorithm.

I have created a github repository for this solution at https://github.com/anonyco/BestBase64EncoderDecoder/

CodeIgniter : Unable to load the requested file:

"Unable to load the requested file"

Can be also caused by access permissions under linux , make sure you set the correct read permissions for the directory "views/home"

PHP Curl UTF-8 Charset

$output = curl_exec($ch);
$result = iconv("Windows-1251", "UTF-8", $output);

Set up adb on Mac OS X

cd sdk/platform-tools/ and then use ./adb devices instead

How to sort a file, based on its numerical values for a field?

You have to use the numeric sort option:

sort -n -k 1,1 File.txt

How to test if a file is a directory in a batch script?

The NUL technique seems to only work on 8.3 compliant file names.

(In other words, `D:\Documents and Settings` is "bad" and `D:\DOCUME~1` is "good")


I think there is some difficulty using the "NUL" tecnique when there are SPACES in the directory name, such as "Documents and Settings."

I am using Windows XP service pack 2 and launching the cmd prompt from %SystemRoot%\system32\cmd.exe

Here are some examples of what DID NOT work and what DOES WORK for me:

(These are all demonstrations done "live" at an interactive prompt. I figure that you should get things to work there before trying to debug them in a script.)

This DID NOT work:

D:\Documents and Settings>if exist "D:\Documents and Settings\NUL" echo yes

This DID NOT work:

D:\Documents and Settings>if exist D:\Documents and Settings\NUL echo yes

This DOES work (for me):

D:\Documents and Settings>cd ..

D:\>REM get the short 8.3 name for the file

D:\>dir /x

Volume in drive D has no label. Volume Serial Number is 34BE-F9C9

Directory of D:\
09/25/2008 05:09 PM <DIR> 2008
09/25/2008 05:14 PM <DIR> 200809~1.25 2008.09.25
09/23/2008 03:44 PM <DIR> BOOST_~3 boost_repo_working_copy
09/02/2008 02:13 PM 486,128 CHROME~1.EXE ChromeSetup.exe
02/14/2008 12:32 PM <DIR> cygwin

[[Look right here !!!! ]]
09/25/2008 08:34 AM <DIR> DOCUME~1 Documents and Settings

09/11/2008 01:57 PM 0 EMPTY_~1.TXT empty_testcopy_file.txt
01/21/2008 06:58 PM <DIR> NATION~1 National Instruments Downloads
10/12/2007 11:25 AM <DIR> NVIDIA
05/13/2008 09:42 AM <DIR> Office10
09/19/2008 11:08 AM <DIR> PROGRA~1 Program Files
12/02/1999 02:54 PM 24,576 setx.exe
09/15/2008 11:19 AM <DIR> TEMP
02/14/2008 12:26 PM <DIR> tmp
01/21/2008 07:05 PM <DIR> VXIPNP
09/23/2008 12:15 PM <DIR> WINDOWS
02/21/2008 03:49 PM <DIR> wx28
02/29/2008 01:47 PM <DIR> WXWIDG~2 wxWidgets
3 File(s) 510,704 bytes
20 Dir(s) 238,250,901,504 bytes free

D:\>REM now use the \NUL test with the 8.3 name

D:\>if exist d:\docume~1\NUL echo yes

yes

This works, but it's sort of silly, because the dot already implies i am in a directory:

D:\Documents and Settings>if exist .\NUL echo yes

Where is Java Installed on Mac OS X?

Use unix find function to find javas installed...

sudo find / -name java

ng-change not working on a text input

Maybe you can try something like this:

Using a directive

directive('watchChange', function() {
    return {
        scope: {
            onchange: '&watchChange'
        },
        link: function(scope, element, attrs) {
            element.on('input', function() {
                scope.onchange();
            });
        }
    };
});

http://jsfiddle.net/H2EAB/

Write a number with two decimal places SQL Server

try this

SELECT CONVERT(DECIMAL(10,2),YOURCOLUMN)

Why are C++ inline functions in the header?

Because the compiler needs to see them in order to inline them. And headers files are the "components" which are commonly included in other translation units.

#include "file.h"
// Ok, now me (the compiler) can see the definition of that inline function. 
// So I'm able to replace calls for the actual implementation.

jQuery click not working for dynamically created items

source: this post

if you created your elements dynamically(using javascript), then this code doesn't work. Because, .click() will attach events to elements that already exists. As you are dynamically creating your elements using javascript, it doesn't work.

For this you have to use some other functions which works on dynamically created elements. This can be done in different ways..

Earlier we have .live() function

$('selector').live('click', function()
{
//your code
});

but .live() is deprecated.This can be replaced by other functions.

Delegate():

Using delegate() function you can click on dynamically generated HTML elements.

Example:

$(document).delegate('selector', 'click', function()
{
 //your code
});

EDIT: The delegate() method was deprecated in version 3.0. Use the on() method instead.

ON():

Using on() function you can click on dynamically generated HTML elements.

Example:

$(document).on('click', 'selector', function()
{
// your code
});

Remove all whitespaces from NSString

This may help you if you are experiencing \u00a0 in stead of (whitespace). I had this problem when I was trying to extract Device Contact Phone Numbers. I needed to modify the phoneNumber string so it has no whitespace in it.

NSString* yourString = [yourString stringByReplacingOccurrencesOfString:@"\u00a0" withString:@""];

When yourString was the current phone number.

Accept server's self-signed ssl certificate in Java client

Apache HttpClient 4.5 supports accepting self-signed certificates:

SSLContext sslContext = SSLContexts.custom()
    .loadTrustMaterial(new TrustSelfSignedStrategy())
    .build();
SSLConnectionSocketFactory socketFactory =
    new SSLConnectionSocketFactory(sslContext);
Registry<ConnectionSocketFactory> reg =
    RegistryBuilder.<ConnectionSocketFactory>create()
    .register("https", socketFactory)
    .build();
HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);        
CloseableHttpClient httpClient = HttpClients.custom()
    .setConnectionManager(cm)
    .build();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse sslResponse = httpClient.execute(httpGet);

This builds an SSL socket factory which will use the TrustSelfSignedStrategy, registers it with a custom connection manager then does an HTTP GET using that connection manager.

I agree with those who chant "don't do this in production", however there are use-cases for accepting self-signed certificates outside production; we use them in automated integration tests, so that we're using SSL (like in production) even when not running on the production hardware.

How to create a Rectangle object in Java using g.fillRect method

Try this:

public void paint (Graphics g) {    
    Rectangle r = new Rectangle(xPos,yPos,width,height);
    g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());  
}

[edit]

// With explicit casting
public void paint (Graphics g) {    
        Rectangle r = new Rectangle(xPos, yPos, width, height);
        g.fillRect(
           (int)r.getX(),
           (int)r.getY(),
           (int)r.getWidth(),
           (int)r.getHeight()
        );  
    }

Convert HTML to PDF in .NET

Update: I would now recommend PupeteerSharp over wkhtmltopdf.

Try wkhtmtopdf. It is the best tool I have found so far.

For .NET, you may use this small library to easily invoke wkhtmtopdf command line utility.

How do I delete an item or object from an array using ng-click?

In case you're inside an ng-repeat

you could use a one liner option

    <div ng-repeat="key in keywords"> 
        <button ng-click="keywords.splice($index, 1)">

            {{key.name}}
        </button>
    </div>

$index is used by angular to show current index of the array inside ng-repeat

Multiple commands in an alias for bash

So use a semi-colon:

alias lock='gnome-screensaver; gnome-screen-saver-command --lock'

This doesn't work well if you want to supply arguments to the first command. Alternatively, create a trivial script in your $HOME/bin directory.

How to count the number of true elements in a NumPy bool array

You have multiple options. Two options are the following.

numpy.sum(boolarr)
numpy.count_nonzero(boolarr)

Here's an example:

>>> import numpy as np
>>> boolarr = np.array([[0, 0, 1], [1, 0, 1], [1, 0, 1]], dtype=np.bool)
>>> boolarr
array([[False, False,  True],
       [ True, False,  True],
       [ True, False,  True]], dtype=bool)

>>> np.sum(boolarr)
5

Of course, that is a bool-specific answer. More generally, you can use numpy.count_nonzero.

>>> np.count_nonzero(boolarr)
5

ImportError: No module named six

If pip "says" six is installed but you're still getting:

ImportError: No module named six.moves

try re-installing six (worked for me):

pip uninstall six
pip install six

refresh both the External data source and pivot tables together within a time schedule

Auto Refresh Workbook for example every 5 sec. Apply to module

Public Sub Refresh()
'refresh
ActiveWorkbook.RefreshAll

alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
    Application.OnTime alertTime, "Refresh"

End Sub

Apply to Workbook on Open

Private Sub Workbook_Open()
alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
Application.OnTime alertTime, "Refresh"
End Sub

:)

Styling a disabled input with css only

A space in a CSS selector selects child elements.

.btn input

This is basically what you wrote and it would select <input> elements within any element that has the btn class.

I think you're looking for

input[disabled].btn:hover, input[disabled].btn:active, input[disabled].btn:focus

This would select <input> elements with the disabled attribute and the btn class in the three different states of hover, active and focus.

How to overcome "datetime.datetime not JSON serializable"?

I had encountered same problem when externalizing django model object to dump as JSON. Here is how you can solve it.

def externalize(model_obj):
  keys = model_obj._meta.get_all_field_names() 
  data = {}
  for key in keys:
    if key == 'date_time':
      date_time_obj = getattr(model_obj, key)
      data[key] = date_time_obj.strftime("%A %d. %B %Y")
    else:
      data[key] = getattr(model_obj, key)
  return data

HTTP response header content disposition for attachments

This has nothing to do with the MIME type, but the Content-Disposition header, which should be something like:

Content-Disposition: attachment; filename=genome.jpeg;

Make sure it is actually correctly passed to the client (not filtered by the server, proxy or something). Also you could try to change the order of writing headers and set them before getting output stream.

How to change font in ipython notebook

In your notebook (simple approach). Add new cell with following code

%%html
<style type='text/css'>
.CodeMirror{
    font-size: 12px;
}

div.output_area pre {
    font-size: 12px;
}
</style>

What's the best way to parse a JSON response from the requests library?

You can use json.loads:

import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)

This converts a given string into a dictionary which allows you to access your JSON data easily within your code.

Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json().

Removing input background colour for Chrome autocomplete?

Although solutions that can be found in many answers do work in Chrome, they do not work in Safari for Mac and iOS.

Safari requires an additional statement – background-clip.

This is the full code for a solution that works across all major browsers on different platforms:

/* Disable autofill highlighting */
input:-webkit-autofill  {
  -webkit-text-fill-color: var(--text-input-color) !important;
  -webkit-box-shadow: 0 0 0 1rem var(--page-background-color) inset !important;
  background-clip: content-box !important;
}

(Please change the --text-input-color and --page-background-color with your own values.)

What does PermGen actually stand for?

PermGen stands for Permanent Generation.

Here is a brief blurb on DDJ

How does one output bold text in Bash?

I assume bash is running on a vt100-compatible terminal in which the user did not explicitly turn off the support for formatting.

First, turn on support for special characters in echo, using -e option. Later, use ansi escape sequence ESC[1m, like:

echo -e "\033[1mSome Text"

More on ansi escape sequences for example here: ascii-table.com/ansi-escape-sequences-vt-100.php

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

For some reason Alt + Shift + F didn't work for me on Mac Visual Studio Code 1.3.1, and actually the command "Format Document" don't worked at all. But command Formatter worked very well.

So you can use Command + Shift + P and type Formatter or make your own shortcut in menu FilePreferencesKeyboard ShortcutsCommand + K Command + S then type Formatter and add your shortcut.

See an example:

Enter image description here

Different ways of loading a file as an InputStream

All these answers around here, as well as the answers in this question, suggest that loading absolute URLs, like "/foo/bar.properties" treated the same by class.getResourceAsStream(String) and class.getClassLoader().getResourceAsStream(String). This is NOT the case, at least not in my Tomcat configuration/version (currently 7.0.40).

MyClass.class.getResourceAsStream("/foo/bar.properties"); // works!  
MyClass.class.getClassLoader().getResourceAsStream("/foo/bar.properties"); // does NOT work!

Sorry, I have absolutely no satisfying explanation, but I guess that tomcat does dirty tricks and his black magic with the classloaders and cause the difference. I always used class.getResourceAsStream(String) in the past and haven't had any problems.

PS: I also posted this over here

node.js: cannot find module 'request'

ReferenceError: Can't find variable: require.

You have installed "npm", you can run as normal the script to a "localhost" "127.0.0.1".

When you use the http.clientRequest() with "options" in a "npm" you need to install "RequireJS" inside of the module.

A module is any file or directory in the node_modules directory that can be loaded by the Node. Install "RequiereJS" for to make work the http.clientRequest(options).

Replace input type=file by an image

This works really well for me:

_x000D_
_x000D_
.image-upload>input {_x000D_
  display: none;_x000D_
}
_x000D_
<div class="image-upload">_x000D_
  <label for="file-input">_x000D_
    <img src="https://icon-library.net/images/upload-photo-icon/upload-photo-icon-21.jpg"/>_x000D_
  </label>_x000D_
_x000D_
  <input id="file-input" type="file" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Basically the for attribute of the label makes it so that clicking the label is the same as clicking the specified input.

Also, the display property set to none makes it so that the file input isn't rendered at all, hiding it nice and clean.

Tested in Chrome but according to the web should work on all major browsers. :)

EDIT: Added JSFiddle here: https://jsfiddle.net/c5s42vdz/

What's the difference between size_t and int in C++?

From the friendly Wikipedia:

The stdlib.h and stddef.h header files define a datatype called size_t which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t.

The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors, particularly as 64-bit architectures become more prevalent.

Also, check Why size_t matters

How do I change selected value of select2 dropdown with JqGrid?

If you want to add new value='newValue' and text='newLabel', you should add this code:

  1. Add new Option to <select>:

    var opt = "<option value='newValue' selected ='selected'>" + newLabel+ " </option>";
    $(selLocationID).html(opt);
    
  2. Trigger <select> change to selected value:

    $(selLocationID).val('newValue').trigger("change");
    

Error while inserting date - Incorrect date value:

As MySql accepts the date in y-m-d format in date type column, you need to STR_TO_DATE function to convert the date into yyyy-mm-dd format for insertion in following way:

INSERT INTO table_name(today) 
VALUES(STR_TO_DATE('07-25-2012','%m-%d-%y'));  

Similary, if you want to select the date in different format other than Mysql format, you should try DATE_FORMAT function

SELECT DATE_FORMAT(today, '%m-%d-%y') from table_name; 

Convert HTML string to image

Try the following:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Program
{
    static void Main(string[] args)
    {
        var source =  @"
        <!DOCTYPE html>
        <html>
            <body>
                <p>An image from W3Schools:</p>
                <img 
                    src=""http://www.w3schools.com/images/w3schools_green.jpg"" 
                    alt=""W3Schools.com"" 
                    width=""104"" 
                    height=""142"">
            </body>
        </html>";
        StartBrowser(source);
        Console.ReadLine();
    }

    private static void StartBrowser(string source)
    {
        var th = new Thread(() =>
        {
            var webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted +=
                webBrowser_DocumentCompleted;
            webBrowser.DocumentText = source;
            Application.Run();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }

    static void 
        webBrowser_DocumentCompleted(
        object sender, 
        WebBrowserDocumentCompletedEventArgs e)
    {
        var webBrowser = (WebBrowser)sender;
        using (Bitmap bitmap = 
            new Bitmap(
                webBrowser.Width, 
                webBrowser.Height))
        {
            webBrowser
                .DrawToBitmap(
                bitmap, 
                new System.Drawing
                    .Rectangle(0, 0, bitmap.Width, bitmap.Height));
            bitmap.Save(@"filename.jpg", 
                System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.

javascript function wait until another function to finish

There are several ways I can think of to do this.

Use a callback:

 function FunctInit(someVarible){
      //init and fill screen
      AndroidCallGetResult();  // Enables Android button.
 }

 function getResult(){ // Called from Android button only after button is enabled
      //return some variables
 }

Use a Timeout (this would probably be my preference):

 var inited = false;
 function FunctInit(someVarible){
      //init and fill screen
      inited = true;
 }

 function getResult(){
      if (inited) {
           //return some variables
      } else {
           setTimeout(getResult, 250);
      }
 }

Wait for the initialization to occur:

 var inited = false;
 function FunctInit(someVarible){
      //init and fill screen
      inited = true;
 }

 function getResult(){
      var a = 1;
      do { a=1; }
      while(!inited);
      //return some variables
 }

How to move from one fragment to another fragment on click of an ImageView in Android?

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_profile, container, false);
    notification = (ImageView)v.findViewById(R.id.notification);

    notification.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FragmentTransaction fr = getFragmentManager().beginTransaction();
            fr.replace(R.id.container,new NotificationFragment());
            fr.commit();
        }
    });

    return v;
}

Getting "net::ERR_BLOCKED_BY_CLIENT" error on some AJAX calls

AdBlockers usually have some rules, i.e. they match the URIs against some type of expression (sometimes they also match the DOM against expressions, not that this matters in this case).

Having rules and expressions that just operate on a tiny bit of text (the URI) is prone to create some false-positives...

Besides instructing your users to disable their extensions (at least on your site) you can also get the extension and test which of the rules/expressions blocked your stuff, provided the extension provides enough details about that. Once you identified the culprit, you can either try to avoid triggering the rule by using different URIs, report the rule as incorrect or overly-broad to the team that created it, or both. Check the docs for a particular add-on on how to do that.

For example, AdBlock Plus has a Blockable items view that shows all blocked items on a page and the rules that triggered the block. And those items also including XHR requests.

Blockable items

Disable Enable Trigger SQL server for a table

if you want to execute ENABLE TRIGGER Directly From Source :

we can't write like this:

Conn.Execute "ENABLE TRIGGER trigger_name ON table_name"

instead, we can write :

Conn.Execute "ALTER TABLE table_name DISABLE TRIGGER trigger_name"

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

If you still need an answer then in my case it works after (re)download Android image but directly from Android Studio not through Visual Studio button.

Converting unix timestamp string to readable date

The most voted answer suggests using fromtimestamp which is error prone since it uses the local timezone. To avoid issues a better approach is to use UTC:

datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')

Where posix_time is the Posix epoch time you want to convert

How to query MongoDB with "like"?

Above answers are perfectly answering the questions about core mongodb query. But when using pattern based search query such as:

{"keywords":{ "$regex": "^toron.*"}}

or

{"keywords":{ "$regex": "^toron"}}

in spring boot jpa repository query with @Query annotation, use query something like:

@Query(value = "{ keyword : { $regex : ?0 }  }")
List<SomeResponse> findByKeywordContainingRegex(String keyword);

and call should be either of:

List<SomeResponse> someResponseList =    someRepository.findByKeywordsContainingRegex("^toron");

List<SomeResponse> someResponseList =    someRepository.findByKeywordsContainingRegex("^toron.*");

But Never use:

List<SomeResponse> someResponseList = someRepository.findByKeywordsContainingRegex("/^toron/");

List<SomeResponse> someResponseList =someRepository.findByKeywordsContainingRegex("/^toron.*/");

Important point to note: each time ?0 field in @Query statement is replaced with double quoted string. so forwardslash(/)should not be used in these cases! always go for pattern using double quotes in searching pattern!! eg. use "^toron" or "^toron.*" over /^toron/ or /^toron.*/

Get name of currently executing test in JUnit 4

A convoluted way is to create your own Runner by subclassing org.junit.runners.BlockJUnit4ClassRunner.

You can then do something like this:

public class NameAwareRunner extends BlockJUnit4ClassRunner {

    public NameAwareRunner(Class<?> aClass) throws InitializationError {
        super(aClass);
    }

    @Override
    protected Statement methodBlock(FrameworkMethod frameworkMethod) {
        System.err.println(frameworkMethod.getName());
        return super.methodBlock(frameworkMethod);
    }
}

Then for each test class, you'll need to add a @RunWith(NameAwareRunner.class) annotation. Alternatively, you could put that annotation on a Test superclass if you don't want to remember it every time. This, of course, limits your selection of runners but that may be acceptable.

Also, it may take a little bit of kung fu to get the current test name out of the Runner and into your framework, but this at least gets you the name.

How to get current page URL in MVC 3

For me the issue was when I tried to access HTTPContext in the Controller's constructor while HTTPContext is not ready yet. When moved inside Index method it worked:

var uri = new Uri(Request.Url.AbsoluteUri);
url = uri.Scheme + "://" + uri.Host + "/";enter code here