Programs & Examples On #Propertychangesupport

Saving binary data as file using JavaScript from a browser

Try

_x000D_
_x000D_
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
_x000D_
_x000D_

I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here

Datatables on-the-fly resizing

You should try this one.

var table = $('#example').DataTable();
table.columns.adjust().draw();

Link: column adjust in datatable

jQuery equivalent to Prototype array.last()

I know the answer is already given, but I think I've got another solution for this. You could take the array, reverse it and output the first array item like this:

var a = [1,2,3,4];
var lastItem = a.reverse()[0];

Works fine for me.

Reading file from Workspace in Jenkins with Groovy script

May this help to someone if they have the same requirement.

This will read a file that contains the Jenkins Job name and run them iteratively from one single job.

Please change below code accordingly in your Jenkins.

_x000D_
_x000D_
pipeline {
   agent any

   stages {
      stage('Hello') {
         steps {
             script{
            git branch: 'Your Branch name', credentialsId: 'Your crendiatails', url: ' Your BitBucket Repo URL '

##To read file from workspace which will contain the Jenkins Job Name ###
           
     def filePath = readFile "${WORKSPACE}/ Your File Location"                   

##To read file line by line ###
 
     def lines = filePath.readLines() 
      
##To iterate and run Jenkins Jobs one by one ####

                    for (line in lines) {                                            
                      build(job: "$line/branchName",
                        parameters:
                        [string(name: 'vertical', value: "${params.vert}"),
                        string(name: 'environment', value: "${params.env}"),
                        string(name: 'branch', value: "${params.branch}"),
                        string(name: 'project', value: "${params.project}")
                        ]
                    )
                        }  
                                       }
                    
         }
         }
      }
   }
_x000D_
_x000D_
_x000D_

Return Bit Value as 1/0 and NOT True/False in SQL Server

 Try this:- SELECT Case WHEN COLUMNNAME=0 THEN 'sex'
              ELSE WHEN COLUMNNAME=1 THEN 'Female' END AS YOURGRIDCOLUMNNAME FROM YOURTABLENAME

in your query for only true or false column

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

The reason for the error is the same origin policy. It only allows you to do XMLHTTPRequests to your own domain. See if you can use a JSONP callback instead:

$.getJSON( 'http://<url>/api.php?callback=?', function ( data ) { alert ( data ); } );

Android Drawing Separator/Divider Line in Layout?

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="2dp"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:paddingTop="2dp"
    android:scaleType="fitXY"
    android:src="?android:attr/listDivider" />

difference between throw and throw new Exception()

Most important difference is that second expression erases type of exception. And exception type plays vital role in catching exceptions:

public void MyMethod ()
{
    // both can throw IOException
    try { foo(); } catch { throw; }
    try { bar(); } catch(E) {throw new Exception(E.message); }
}

(...)

try {
    MyMethod ();
} catch (IOException ex) {
    Console.WriteLine ("Error with I/O"); // [1]
} catch (Exception ex) {
    Console.WriteLine ("Other error");    // [2]
}

If foo() throws IOException, [1] catch block will catch exception. But when bar() throws IOException, it will be converted to plain Exception ant won't be caught by [1] catch block.

How to access PHP session variables from jQuery function in a .js file?

You can produce the javascript file via PHP. Nothing says a javascript file must have a .js extention. For example in your HTML:

<script src='javascript.php'></script>

Then your script file:

<?php header("Content-type: application/javascript"); ?>

$(function() {
    $( "#progressbar" ).progressbar({
        value: <?php echo $_SESSION['value'] ?>
    });

    // ... more javascript ...

If this particular method isn't an option, you could put an AJAX request in your javascript file, and have the data returned as JSON from the server side script.

Returning unique_ptr from functions

This is in no way specific to std::unique_ptr, but applies to any class that is movable. It's guaranteed by the language rules since you are returning by value. The compiler tries to elide copies, invokes a move constructor if it can't remove copies, calls a copy constructor if it can't move, and fails to compile if it can't copy.

If you had a function that accepts std::unique_ptr as an argument you wouldn't be able to pass p to it. You would have to explicitly invoke move constructor, but in this case you shouldn't use variable p after the call to bar().

void bar(std::unique_ptr<int> p)
{
    // ...
}

int main()
{
    unique_ptr<int> p = foo();
    bar(p); // error, can't implicitly invoke move constructor on lvalue
    bar(std::move(p)); // OK but don't use p afterwards
    return 0;
}

Converting serial port data to TCP/IP in a Linux environment

I think your question isn't quite clear. There are several answers here on how to catch the data coming into a Linux's serial port, but perhaps your problem is the other way around?

If you need to catch the data coming out of a Linux's serial port and send it to a server, there are several little hardware gizmos that can do this, starting with the simple serial print server such as this Lantronix gizmo.

No, I'm not affiliated with Lantronix in any way.

Why I can't change directories using "cd"?

On my particular case i needed too many times to change for the same directory. So on my .bashrc (I use ubuntu) i've added the

1 -

$ nano ~./bashrc

 function switchp
 {
    cd /home/tree/projects/$1
 }

2-

$ source ~/.bashrc

3 -

$ switchp java

Directly it will do: cd /home/tree/projects/java

Hope that helps!

Which command do I use to generate the build of a Vue app?

If you've created your project using:

vue init webpack myproject

You'd need to set your NODE_ENV to production and run, because the project has web pack configured for both development and production:

NODE_ENV=production npm run build

Copy dist/ directory into your website root directory.

If you're deploying with Docker, you'd need an express server, serving the dist/ directory.

Dockerfile

FROM node:carbon

RUN mkdir -p /usr/src/app

WORKDIR /usr/src/app
ADD . /usr/src/app
RUN npm install

ENV NODE_ENV=production

RUN npm run build

# Remove unused directories
RUN rm -rf ./src
RUN rm -rf ./build

# Port to expose
EXPOSE 8080
CMD [ "npm", "start" ]

SQL "select where not in subquery" returns no results

Just off the top of my head...

select c.commonID, t1.commonID, t2.commonID
from Common c
     left outer join Table1 t1 on t1.commonID = c.commonID
     left outer join Table2 t2 on t2.commonID = c.commonID
where t1.commonID is null 
     and t2.commonID is null

I ran a few tests and here were my results w.r.t. @patmortech's answer and @rexem's comments.

If either Table1 or Table2 is not indexed on commonID, you get a table scan but @patmortech's query is still twice as fast (for a 100K row master table).

If neither are indexed on commonID, you get two table scans and the difference is negligible.

If both are indexed on commonID, the "not exists" query runs in 1/3 the time.

Deleting multiple elements from a list

l = ['a','b','a','c','a','d']
to_remove = [1, 3]
[l[i] for i in range(0, len(l)) if i not in to_remove])

It's basically the same as the top voted answer, just a different way of writing it. Note that using l.index() is not a good idea, because it can't handle duplicated elements in a list.

How would one write object-oriented code in C?

Trivial example with an Animal and Dog: You mirror C++'s vtable mechanism (largely anyway). You also separate allocation and instantiation (Animal_Alloc, Animal_New) so we don't call malloc() multiple times. We must also explicitly pass the this pointer around.

If you were to do non-virtual functions, that's trival. You just don't add them to the vtable and static functions don't require a this pointer. Multiple inheritance generally requires multiple vtables to resolve ambiguities.

Also, you should be able to use setjmp/longjmp to do exception handling.

struct Animal_Vtable{
    typedef void (*Walk_Fun)(struct Animal *a_This);
    typedef struct Animal * (*Dtor_Fun)(struct Animal *a_This);

    Walk_Fun Walk;
    Dtor_Fun Dtor;
};

struct Animal{
    Animal_Vtable vtable;

    char *Name;
};

struct Dog{
    Animal_Vtable vtable;

    char *Name; // Mirror member variables for easy access
    char *Type;
};

void Animal_Walk(struct Animal *a_This){
    printf("Animal (%s) walking\n", a_This->Name);
}

struct Animal* Animal_Dtor(struct Animal *a_This){
    printf("animal::dtor\n");
    return a_This;
}

Animal *Animal_Alloc(){
    return (Animal*)malloc(sizeof(Animal));
}

Animal *Animal_New(Animal *a_Animal){
    a_Animal->vtable.Walk = Animal_Walk;
    a_Animal->vtable.Dtor = Animal_Dtor;
    a_Animal->Name = "Anonymous";
    return a_Animal;
}

void Animal_Free(Animal *a_This){
    a_This->vtable.Dtor(a_This);

    free(a_This);
}

void Dog_Walk(struct Dog *a_This){
    printf("Dog walking %s (%s)\n", a_This->Type, a_This->Name);
}

Dog* Dog_Dtor(struct Dog *a_This){
    // Explicit call to parent destructor
    Animal_Dtor((Animal*)a_This);

    printf("dog::dtor\n");

    return a_This;
}

Dog *Dog_Alloc(){
    return (Dog*)malloc(sizeof(Dog));
}

Dog *Dog_New(Dog *a_Dog){
    // Explict call to parent constructor
    Animal_New((Animal*)a_Dog);

    a_Dog->Type = "Dog type";
    a_Dog->vtable.Walk = (Animal_Vtable::Walk_Fun) Dog_Walk;
    a_Dog->vtable.Dtor = (Animal_Vtable::Dtor_Fun) Dog_Dtor;

    return a_Dog;
}

int main(int argc, char **argv){
    /*
      Base class:

        Animal *a_Animal = Animal_New(Animal_Alloc());
    */
    Animal *a_Animal = (Animal*)Dog_New(Dog_Alloc());

    a_Animal->vtable.Walk(a_Animal);

    Animal_Free(a_Animal);
}

PS. This is tested on a C++ compiler, but it should be easy to make it work on a C compiler.

Command to delete all pods in all kubernetes namespaces

You just need sed to do this:

kubectl get pods --no-headers=true --all-namespaces |sed -r 's/(\S+)\s+(\S+).*/kubectl --namespace \1 delete pod \2/e'

Explains:

  1. use command kubectl get pods --all-namespaces to get the list of all pods in all namespaces.
  2. use --no-headers=true option to hide the headers.
  3. use s command of sed to fetch the first two words, which represent namespace and pod's name respectively, then assemble the delete command using them.
  4. the final delete command is just like: kubectl --namespace kube-system delete pod heapster-eq3yw.
  5. use the e modifier of s command to execute the command assembled above, which will do the actual delete works.

To avoid delete pods in kube-system namespace, just need to add grep -v kube-system to exclude kube-system namespace before the sed command.

Why should we include ttf, eot, woff, svg,... in a font-face

Woff is a compressed (zipped) form of the TrueType - OpenType font. It is small and can be delivered over the network like a graphic file. Most importantly, this way the font is preserved completely including rendering rule tables that very few people care about because they use only Latin script.

Take a look at [dead URL removed]. The font you see is an experimental web delivered smartfont (woff) that has thousands of combined characters making complex shapes. The underlying text is simple Latin code of romanized Singhala. (Copy and paste to Notepad and see).

Only woff can do this because nobody has this font and yet it is seen anywhere (Mac, Win, Linux and even on smartphones by all browsers except by IE. IE does not have full support for Open Types).

Add ... if string is too long PHP

<?php
function truncate($string, $length, $stopanywhere=false) {
    //truncates a string to a certain char length, stopping on a word if not specified otherwise.
    if (strlen($string) > $length) {
        //limit hit!
        $string = substr($string,0,($length -3));
        if ($stopanywhere) {
            //stop anywhere
            $string .= '...';
        } else{
            //stop on a word.
            $string = substr($string,0,strrpos($string,' ')).'...';
        }
    }
    return $string;
}
?>

I use the above code snippet many-a-times..

What is the memory consumption of an object in Java?

In case it's useful to anyone, you can download from my web site a small Java agent for querying the memory usage of an object. It'll let you query "deep" memory usage as well.

What's the difference between '$(this)' and 'this'?

Yes you only need $() when you're using jQuery. If you want jQuery's help to do DOM things just keep this in mind.

$(this)[0] === this

Basically every time you get a set of elements back jQuery turns it into a jQuery object. If you know you only have one result, it's going to be in the first element.

$("#myDiv")[0] === document.getElementById("myDiv");

And so on...

How do I use raw_input in Python 3

Timmerman's solution works great when running the code, but if you don't want to get Undefined name errors when using pyflakes or a similar linter you could use the following instead:

try:
    import __builtin__
    input = getattr(__builtin__, 'raw_input')
except (ImportError, AttributeError):
    pass

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

How to get a time zone from a location using latitude and longitude coordinates?

You can use geolocator.js for easily getting timezone and more...

It uses Google APIs that require a key. So, first you configure geolocator:

geolocator.config({
    language: "en",
    google: {
        version: "3",
        key: "YOUR-GOOGLE-API-KEY"
    }
});

Get TimeZone if you have the coordinates:

geolocator.getTimeZone(options, function (err, timezone) {
    console.log(err || timezone);
});

Example output:

{
    id: "Europe/Paris",
    name: "Central European Standard Time",
    abbr: "CEST",
    dstOffset: 0,
    rawOffset: 3600,
    timestamp: 1455733120
}

Locate then get TimeZone and more

If you don't have the coordinates, you can locate the user position first.

Example below will first try HTML5 Geolocation API to get the coordinates. If it fails or rejected, it will get the coordinates via Geo-IP look-up. Finally, it will get the timezone and more...

var options = {
    enableHighAccuracy: true,
    timeout: 6000,
    maximumAge: 0,
    desiredAccuracy: 30,
    fallbackToIP: true, // if HTML5 fails or rejected
    addressLookup: true, // this will get full address information
    timezone: true,
    map: "my-map" // this will even create a map for you
};
geolocator.locate(options, function (err, location) {
    console.log(err || location);
});

Example output:

{
    coords: {
        latitude: 37.4224764,
        longitude: -122.0842499,
        accuracy: 30,
        altitude: null,
        altitudeAccuracy: null,
        heading: null,
        speed: null
    },
    address: {
        commonName: "",
        street: "Amphitheatre Pkwy",
        route: "Amphitheatre Pkwy",
        streetNumber: "1600",
        neighborhood: "",
        town: "",
        city: "Mountain View",
        region: "Santa Clara County",
        state: "California",
        stateCode: "CA",
        postalCode: "94043",
        country: "United States",
        countryCode: "US"
    },
    formattedAddress: "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
    type: "ROOFTOP",
    placeId: "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
    timezone: {
        id: "America/Los_Angeles",
        name: "Pacific Standard Time",
        abbr: "PST",
        dstOffset: 0,
        rawOffset: -28800
    },
    flag: "//cdnjs.cloudflare.com/ajax/libs/flag-icon-css/2.3.1/flags/4x3/us.svg",
    map: {
        element: HTMLElement,
        instance: Object, // google.maps.Map
        marker: Object, // google.maps.Marker
        infoWindow: Object, // google.maps.InfoWindow
        options: Object // map options
    },
    timestamp: 1456795956380
}

Amazon S3 upload file and get URL

        System.out.println("Link : " + s3Object.getObjectContent().getHttpRequest().getURI());

with this you can retrieve the link of already uploaded file to S3 bucket.

Get a Windows Forms control by name in C#

Assuming you have Windows.Form Form1 as the parent form which owns the menu you've created. One of the form's attributes is named .Menu. If the menu was created programmatically, it should be the same, and it would be recognized as a menu and placed in the Menu attribute of the Form.

In this case, I had a main menu called File. A sub menu, called a MenuItem under File contained the tag Open and was named menu_File_Open. The following worked. Assuming you

// So you don't have to fully reference the objects.
using System.Windows.Forms;

// More stuff before the real code line, but irrelevant to this discussion.

MenuItem my_menuItem = (MenuItem)Form1.Menu.MenuItems["menu_File_Open"];

// Now you can do what you like with my_menuItem;

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

The Qt documentations has an Image Viewer example which demonstrates handling resizing images inside a QLabel. The basic idea is to use QScrollArea as a container for the QLabel and if needed use label.setScaledContents(bool) and scrollarea.setWidgetResizable(bool) to fill available space and/or ensure QLabel inside is resizable. Additionally, to resize QLabel while honoring aspect ratio use:

label.setPixmap(pixmap.scaled(width, height, Qt::KeepAspectRatio, Qt::FastTransformation));

The width and height can be set based on scrollarea.width() and scrollarea.height(). In this way there is no need to subclass QLabel.

How can I dynamically add items to a Java array?

keep a count of where you are in the primitive array

class recordStuff extends Thread
{
    double[] aListOfDoubles;
    int i = 0;

    void run()
    {
        double newData;
        newData = getNewData(); // gets data from somewhere

        aListofDoubles[i] = newData; // adds it to the primitive array of doubles
        i++ // increments the counter for the next pass

        System.out.println("mode: " + doStuff());
    }

    void doStuff()
    {
        // Calculate the mode of the double[] array

        for (int i = 0; i < aListOfDoubles.length; i++) 
        {
            int count = 0;
            for (int j = 0; j < aListOfDoubles.length; j++)
            {
                if (a[j] == a[i]) count++;
            }
            if (count > maxCount) 
            {
                maxCount = count;
                maxValue = aListOfDoubles[i];
            }
        }
        return maxValue;
    }
}

Redirecting exec output to a buffer or file

For sending the output to another file (I'm leaving out error checking to focus on the important details):

if (fork() == 0)
{
    // child
    int fd = open(file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);

    dup2(fd, 1);   // make stdout go to file
    dup2(fd, 2);   // make stderr go to file - you may choose to not do this
                   // or perhaps send stderr to another file

    close(fd);     // fd no longer needed - the dup'ed handles are sufficient

    exec(...);
}

For sending the output to a pipe so you can then read the output into a buffer:

int pipefd[2];
pipe(pipefd);

if (fork() == 0)
{
    close(pipefd[0]);    // close reading end in the child

    dup2(pipefd[1], 1);  // send stdout to the pipe
    dup2(pipefd[1], 2);  // send stderr to the pipe

    close(pipefd[1]);    // this descriptor is no longer needed

    exec(...);
}
else
{
    // parent

    char buffer[1024];

    close(pipefd[1]);  // close the write end of the pipe in the parent

    while (read(pipefd[0], buffer, sizeof(buffer)) != 0)
    {
    }
}

Postgresql: error "must be owner of relation" when changing a owner object

This solved my problem : Sample alter table statement to change the ownership.

ALTER TABLE databasechangelog OWNER TO arwin_ash;
ALTER TABLE databasechangeloglock OWNER TO arwin_ash;

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

I encountered this as well. The conditions that caused my issue:

  • I'm running a full IIS7 instance locally
  • I'm versioning my software into separate projects

I had caused this by opening a previous version (VS prompted to ask if I wanted to point to this instance in IIS debugging, I answered 'Yes'), then opening the current version (again responding to the IIS prompt with a 'Yes'), then attempting to debug in the previous version.

To solve, I merely closed and re-opened the previous and intended version, once again asserting it as the debugging source.

Add hover text without javascript like we hover on a user's reputation

Use the title attribute, for example:

_x000D_
_x000D_
<div title="them's hoverin' words">hover me</div>
_x000D_
_x000D_
_x000D_

or:

_x000D_
_x000D_
<span title="them's hoverin' words">hover me</span>
_x000D_
_x000D_
_x000D_

Remove legend ggplot 2.2

If your chart uses both fill and color aesthetics, you can remove the legend with:

+ guides(fill=FALSE, color=FALSE)

How to access the SMS storage on Android?

Do the following, download SQLLite Database Browser from here:

Locate your db. file in your phone.

Then, as soon you install the program go to: "Browse Data", you will see all the SMS there!!

You can actually export the data to an excel file or SQL.

How to convert integer to decimal in SQL Server query?

declare @xx int 
set     @xx = 3 
select @xx      
select @xx * 2  -- yields another integer  
select @xx/1    -- same
select @xx/1.0  --yields 6 decimal places 
select @xx/1.00 --       6 
select @xx * 1.0  --     1 decimal place - victory
select @xx * 1.00 --     2         places - hooray 

Also _ inserting an int into a temp_table with like decimal(10,3) _ works ok.

How do I set the colour of a label (coloured text) in Java?

One of the disadvantages of using HTML for labels is when you need to write a localizable program (which should work in several languages). You will have issues to change just the translatable text. Or you will have to put the whole HTML code into your translations which is very awkward, I would even say absurd :)

gui_en.properties:

title.text=<html>Text color: <font color='red'>red</font></html>

gui_fr.properties:

title.text=<html>Couleur du texte: <font color='red'>rouge</font></html>

gui_ru.properties:

title.text=<html>???? ??????: <font color='red'>???????</font></html>

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

For UWP, I tried a different approach. I extended the ComboBox class, and processed the SelectionChanged and OnKeyUp events on the ComboBox as well as the Tapped event on the ComboBoxItems. In cases where I get a Tapped event or an Enter or Space key without first getting a SelectionChanged then I know the current item has been re-selected and I respond accordingly.

class ExtendedComboBox : ComboBox
{
    public ExtendedComboBox()
    {
        SelectionChanged += OnSelectionChanged;
    }

    protected override void PrepareContainerForItemOverride(Windows.UI.Xaml.DependencyObject element, object item)
    {
        ComboBoxItem cItem = element as ComboBoxItem;
        if (cItem != null)
        {
            cItem.Tapped += OnItemTapped;
        }

        base.PrepareContainerForItemOverride(element, item);
    }

    protected override void OnKeyUp(KeyRoutedEventArgs e)
    {
        // if the user hits the Enter or Space to select an item, then consider this a "reselect" operation
        if ((e.Key == Windows.System.VirtualKey.Space || e.Key == Windows.System.VirtualKey.Enter) && !isSelectionChanged)
        {
            // handle re-select logic here
        }

        isSelectionChanged = false;

        base.OnKeyUp(e);
    }

    // track whether or not the ComboBox has received a SelectionChanged notification
    // in cases where it has not yet we get a Tapped or KeyUp notification we will want to consider that a "re-select"
    bool isSelectionChanged = false;
    private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        isSelectionChanged = true;
    }

    private void OnItemTapped(object sender, TappedRoutedEventArgs e)
    {
        if (!isSelectionChanged)
        {
            // indicates that an item was re-selected  - handle logic here
        }

        isSelectionChanged = false;
    }
}

JQuery / JavaScript - trigger button click from another button click event

Add id's to both inputs, id="first" and id="second"

//trigger second button
$("#second").click()

Postgres where clause compare timestamp

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

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

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

This will return all rows from July, 15th.

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

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

Replace an element into a specific position of a vector

See an example here: http://www.cplusplus.com/reference/stl/vector/insert/ eg.:



...
vector::iterator iterator1;

  iterator1= vec1.begin();
  vec1.insert ( iterator1+i , vec2[i] );

// This means that at position "i" from the beginning it will insert the value from vec2 from position i

Your first approach was replacing the values from vec1[i] with the values from vec2[i]

When do I need to use AtomicBoolean in Java?

Here is the notes (from Brian Goetz book) I made, that might be of help to you

AtomicXXX classes

  • provide Non-blocking Compare-And-Swap implementation

  • Takes advantage of the support provide by hardware (the CMPXCHG instruction on Intel) When lots of threads are running through your code that uses these atomic concurrency API, they will scale much better than code which uses Object level monitors/synchronization. Since, Java's synchronization mechanisms makes code wait, when there are lots of threads running through your critical sections, a substantial amount of CPU time is spent in managing the synchronization mechanism itself (waiting, notifying, etc). Since the new API uses hardware level constructs (atomic variables) and wait and lock free algorithms to implement thread-safety, a lot more of CPU time is spent "doing stuff" rather than in managing synchronization.

  • not only offer better throughput, but they also provide greater resistance to liveness problems such as deadlock and priority inversion.

How to get a string after a specific substring?

You want to use str.partition():

>>> my_string.partition("world")[2]
" , i'm a beginner "

because this option is faster than the alternatives.

Note that this produces an empty string if the delimiter is missing:

>>> my_string.partition("Monty")[2]  # delimiter missing
''

If you want to have the original string, then test if the second value returned from str.partition() is non-empty:

prefix, success, result = my_string.partition(delimiter)
if not success: result = prefix

You could also use str.split() with a limit of 1:

>>> my_string.split("world", 1)[-1]
" , i'm a beginner "
>>> my_string.split("Monty", 1)[-1]  # delimiter missing
"hello python world , i'm a beginner "

However, this option is slower. For a best-case scenario, str.partition() is easily about 15% faster compared to str.split():

                                missing        first         lower         upper          last
      str.partition(...)[2]:  [3.745 usec]  [0.434 usec]  [1.533 usec]  <3.543 usec>  [4.075 usec]
str.partition(...) and test:   3.793 usec    0.445 usec    1.597 usec    3.208 usec    4.170 usec
      str.split(..., 1)[-1]:  <3.817 usec>  <0.518 usec>  <1.632 usec>  [3.191 usec]  <4.173 usec>
            % best vs worst:         1.9%         16.2%          6.1%          9.9%          2.3%

This shows timings per execution with inputs here the delimiter is either missing (worst-case scenario), placed first (best case scenario), or in the lower half, upper half or last position. The fastest time is marked with [...] and <...> marks the worst.

The above table is produced by a comprehensive time trial for all three options, produced below. I ran the tests on Python 3.7.4 on a 2017 model 15" Macbook Pro with 2.9 GHz Intel Core i7 and 16 GB ram.

This script generates random sentences with and without the randomly selected delimiter present, and if present, at different positions in the generated sentence, runs the tests in random order with repeats (producing the fairest results accounting for random OS events taking place during testing), and then prints a table of the results:

import random
from itertools import product
from operator import itemgetter
from pathlib import Path
from timeit import Timer

setup = "from __main__ import sentence as s, delimiter as d"
tests = {
    "str.partition(...)[2]": "r = s.partition(d)[2]",
    "str.partition(...) and test": (
        "prefix, success, result = s.partition(d)\n"
        "if not success: result = prefix"
    ),
    "str.split(..., 1)[-1]": "r = s.split(d, 1)[-1]",
}

placement = "missing first lower upper last".split()
delimiter_count = 3

wordfile = Path("/usr/dict/words")  # Linux
if not wordfile.exists():
    # macos
    wordfile = Path("/usr/share/dict/words")
words = [w.strip() for w in wordfile.open()]

def gen_sentence(delimiter, where="missing", l=1000):
    """Generate a random sentence of length l

    The delimiter is incorporated according to the value of where:

    "missing": no delimiter
    "first":   delimiter is the first word
    "lower":   delimiter is present in the first half
    "upper":   delimiter is present in the second half
    "last":    delimiter is the last word

    """
    possible = [w for w in words if delimiter not in w]
    sentence = random.choices(possible, k=l)
    half = l // 2
    if where == "first":
        # best case, at the start
        sentence[0] = delimiter
    elif where == "lower":
        # lower half
        sentence[random.randrange(1, half)] = delimiter
    elif where == "upper":
        sentence[random.randrange(half, l)] = delimiter
    elif where == "last":
        sentence[-1] = delimiter
    # else: worst case, no delimiter

    return " ".join(sentence)

delimiters = random.choices(words, k=delimiter_count)
timings = {}
sentences = [
    # where, delimiter, sentence
    (w, d, gen_sentence(d, w)) for d, w in product(delimiters, placement)
]
test_mix = [
    # label, test, where, delimiter sentence
    (*t, *s) for t, s in product(tests.items(), sentences)
]
random.shuffle(test_mix)

for i, (label, test, where, delimiter, sentence) in enumerate(test_mix, 1):
    print(f"\rRunning timed tests, {i:2d}/{len(test_mix)}", end="")
    t = Timer(test, setup)
    number, _ = t.autorange()
    results = t.repeat(5, number)
    # best time for this specific random sentence and placement
    timings.setdefault(
        label, {}
    ).setdefault(
        where, []
    ).append(min(dt / number for dt in results))

print()

scales = [(1.0, 'sec'), (0.001, 'msec'), (1e-06, 'usec'), (1e-09, 'nsec')]
width = max(map(len, timings))
rows = []
bestrow = dict.fromkeys(placement, (float("inf"), None))
worstrow = dict.fromkeys(placement, (float("-inf"), None))

for row, label in enumerate(tests):
    columns = []
    worst = float("-inf")
    for p in placement:
        timing = min(timings[label][p])
        if timing < bestrow[p][0]:
            bestrow[p] = (timing, row)
        if timing > worstrow[p][0]:
            worstrow[p] = (timing, row)
        worst = max(timing, worst)
        columns.append(timing)

    scale, unit = next((s, u) for s, u in scales if worst >= s)
    rows.append(
        [f"{label:>{width}}:", *(f" {c / scale:.3f} {unit} " for c in columns)]
    )

colwidth = max(len(c) for r in rows for c in r[1:])
print(' ' * (width + 1), *(p.center(colwidth) for p in placement), sep="  ")
for r, row in enumerate(rows):
    for c, p in enumerate(placement, 1):
        if bestrow[p][1] == r:
            row[c] = f"[{row[c][1:-1]}]"
        elif worstrow[p][1] == r:
            row[c] = f"<{row[c][1:-1]}>"
    print(*row, sep="  ")

percentages = []
for p in placement:
    best, worst = bestrow[p][0], worstrow[p][0]
    ratio = ((worst - best) / worst)
    percentages.append(f"{ratio:{colwidth - 1}.1%} ")

print("% best vs worst:".rjust(width + 1), *percentages, sep="  ")

SQL Server datetime LIKE select?

If you do that, you are forcing it to do a string conversion. It would be better to build a start/end date range, and use:

declare @start datetime, @end datetime
select @start = '2009-10-10', @end = '2009-11-10'
select * from record where register_date >= @start
           and register_date < @end

This will allow it to use the index (if there is one on register_date), rather than a table scan.

How do I open a new window using jQuery?

It's not really something you need jQuery to do. There is a very simple plain old javascript method for doing this:

window.open('http://www.google.com','GoogleWindow', 'width=800, height=600');

That's it.

The first arg is the url, the second is the name of the window, this should be specified because IE will throw a fit about trying to use window.opener later if there was no window name specified (just a little FYI), and the last two params are width/height.

EDIT: Full specification can be found in the link mmmshuddup provided.

Javascript call() & apply() vs bind()?

    function sayHello() {
            //alert(this.message);
            return this.message;
    }
    var obj = {
            message: "Hello"
    };

    function x(country) {
            var z = sayHello.bind(obj);
            setTimeout(y = function(w) {
//'this' reference not lost
                    return z() + ' ' + country + ' ' + w;
            }, 1000);
            return y;
    }
    var t = x('India')('World');
    document.getElementById("demo").innerHTML = t;

Create timestamp variable in bash script

If you want to get unix timestamp, then you need to use:

timestamp=$(date +%s)

%T will give you just the time; same as %H:%M:%S (via http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/)

Xcode 6 Storyboard the wrong size?

For anyone using XCode 7, it's very easy to design for a specific device size (instead of the default square-ish canvas).

In Interface Builder, select your ViewController or Scene from the left menu. Then under Show the Attributes Inspector, go to the Simulated Metrics, and pick the desired Size from the dropdown menu.

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

  1. Delete all temp files
    • search %TEMP%
    • delete all
  2. Perform a clean boot. see How to perform a clean boot in Windows
  3. Install vc_redist.x64 see Download Visual C++ Redistributable for Visual Studio 2015
  4. Restart without clean boot

Return zero if no record is found

I'm not familiar with postgresql, but in SQL Server or Oracle, using a subquery would work like below (in Oracle, the SELECT 0 would be SELECT 0 FROM DUAL)

SELECT SUM(sub.value)
FROM
( 
  SELECT SUM(columnA) as value FROM my_table
  WHERE columnB = 1
  UNION
  SELECT 0 as value
) sub

Maybe this would work for postgresql too?

How to to send mail using gmail in Laravel?

If you're developing on an XAMPP, then you'll need an SMTP service to send the email. Try using a MailGun account. It's free and easy to use.

Why does sed not replace all occurrences?

You have to put a g at the end, it stands for "global":

echo dog dog dos | sed -r 's:dog:log:g'
                                     ^

Is there a Social Security Number reserved for testing/examples?

I used this 457-55-5462 as testing SSN and it worked for me. I used it at paypal sandbox account. Hope it helps somebody

Can Javascript read the source of any web page?

You can generate a XmlHttpRequest and request the page,and then use getResponseText() to get the content.

Simple way to calculate median with MySQL

In some cases median gets calculated as follows :

The "median" is the "middle" value in the list of numbers when they are ordered by value. For even count sets, median is average of the two middle values. I've created a simple code for that :

$midValue = 0;
$rowCount = "SELECT count(*) as count {$from} {$where}";

$even = FALSE;
$offset = 1;
$medianRow = floor($rowCount / 2);
if ($rowCount % 2 == 0 && !empty($medianRow)) {
  $even = TRUE;
  $offset++;
  $medianRow--;
}

$medianValue = "SELECT column as median 
               {$fromClause} {$whereClause} 
               ORDER BY median 
               LIMIT {$medianRow},{$offset}";

$medianValDAO = db_query($medianValue);
while ($medianValDAO->fetch()) {
  if ($even) {
    $midValue = $midValue + $medianValDAO->median;
  }
  else {
    $median = $medianValDAO->median;
  }
}
if ($even) {
  $median = $midValue / 2;
}
return $median;

The $median returned would be the required result :-)

Scanner only reads first word instead of line

input.next() takes in the first whitsepace-delimited word of the input string. So by design it does what you've described. Try input.nextLine().

Add/delete row from a table

Here's the code JS Bin using jQuery. Tested on all the browsers. Here, we have to click the rows in order to delete it with beautiful effect. Hope it helps.

Regular expression for exact match of a string

In malfaux's answer '^' and '$' has been used to detect the beginning and the end of the text.
These are usually used to detect the beginning and the end of a line.
However this may be the correct way in this case.
But if you wish to match an exact word the more elegant way is to use '\b'. In this case following pattern will match the exact phrase'123456'.

/\b123456\b/

How to add button in ActionBar(Android)?

you have to create an entry inside res/menu,override onCreateOptionsMenu and inflate it

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.yourentry, menu);
    return true;
}

an entry for the menu could be:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_cart"
        android:icon="@drawable/cart"
        android:orderInCategory="100"
        android:showAsAction="always"/> 
</menu>

What is Dispatcher Servlet in Spring?

I know this question is marked as solved already but I want to add a newer image explaining this pattern in detail(source: spring in action 4):

enter image description here

Explanation

When the request leaves the browser (1), it carries information about what the user is asking for. At the least, the request will be carrying the requested URL. But it may also carry additional data, such as the information submitted in a form by the user.

The first stop in the request’s travels is at Spring’s DispatcherServlet. Like most Java- based web frameworks, Spring MVC funnels requests through a single front controller servlet. A front controller is a common web application pattern where a single servlet delegates responsibility for a request to other components of an application to per- form actual processing. In the case of Spring MVC, DispatcherServlet is the front controller. The DispatcherServlet’s job is to send the request on to a Spring MVC controller. A controller is a Spring component that processes the request. But a typical application may have several controllers, and DispatcherServlet needs some help deciding which controller to send the request to. So the DispatcherServlet consults one or more handler mappings (2) to figure out where the request’s next stop will be. The handler mapping pays particular attention to the URL carried by the request when making its decision. Once an appropriate controller has been chosen, DispatcherServlet sends the request on its merry way to the chosen controller (3). At the controller, the request drops off its payload (the information submitted by the user) and patiently waits while the controller processes that information. (Actually, a well-designed controller per- forms little or no processing itself and instead delegates responsibility for the business logic to one or more service objects.) The logic performed by a controller often results in some information that needs to be carried back to the user and displayed in the browser. This information is referred to as the model. But sending raw information back to the user isn’t suffi- cient—it needs to be formatted in a user-friendly format, typically HTML. For that, the information needs to be given to a view, typically a JavaServer Page (JSP). One of the last things a controller does is package up the model data and identify the name of a view that should render the output. It then sends the request, along with the model and view name, back to the DispatcherServlet (4). So that the controller doesn’t get coupled to a particular view, the view name passed back to DispatcherServlet doesn’t directly identify a specific JSP. It doesn’t even necessarily suggest that the view is a JSP. Instead, it only carries a logical name that will be used to look up the actual view that will produce the result. The DispatcherServlet consults a view resolver (5) to map the logical view name to a spe- cific view implementation, which may or may not be a JSP. Now that DispatcherServlet knows which view will render the result, the request’s job is almost over. Its final stop is at the view implementation (6), typically a JSP, where it delivers the model data. The request’s job is finally done. The view will use the model data to render output that will be carried back to the client by the (not- so-hardworking) response object (7).

How can I check if PostgreSQL is installed or not via Linux script?

And if everything else fails from these great choice of answers, you can always use "find" like this. Or you may need to use sudo

If you are root, just type $$> find / -name 'postgres'

If you are a user, you will need sudo priv's to run it through all the directories

I run it this way, from the / base to find the whole path that the element is found in. This will return any files or directories with the "postgres" in it.

You could do the same thing looking for the pg_hba.conf or postgresql.conf files also.

Find size of object instance in bytes in c#

For unmanaged types aka value types, structs:

        Marshal.SizeOf(object);

For managed objects the closer i got is an approximation.

        long start_mem = GC.GetTotalMemory(true);

        aclass[] array = new aclass[1000000];
        for (int n = 0; n < 1000000; n++)
            array[n] = new aclass();

        double used_mem_median = (GC.GetTotalMemory(false) - start_mem)/1000000D;

Do not use serialization.A binary formatter adds headers, so you can change your class and load an old serialized file into the modified class.

Also it won't tell you the real size in memory nor will take into account memory alignment.

[Edit] By using BiteConverter.GetBytes(prop-value) recursivelly on every property of your class you would get the contents in bytes, that doesn't count the weight of the class or references but is much closer to reality. I would recommend to use a byte array for data and an unmanaged proxy class to access values using pointer casting if size matters, note that would be non-aligned memory so on old computers is gonna be slow but HUGE datasets on MODERN RAM is gonna be considerably faster, as minimizing the size to read from RAM is gonna be a bigger impact than unaligned.

What is the difference between a pandas Series and a single-column DataFrame?

from the pandas doc http://pandas.pydata.org/pandas-docs/stable/dsintro.html Series is a one-dimensional labeled array capable of holding any data type. To read data in form of panda Series:

import pandas as pd
ds = pd.Series(data, index=index)

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types.

import pandas as pd
df = pd.DataFrame(data, index=index)

In both of the above index is list

for example: I have a csv file with following data:

,country,popuplation,area,capital
BR,Brazil,10210,12015,Brasile
RU,Russia,1025,457,Moscow
IN,India,10458,457787,New Delhi

To read above data as series and data frame:

import pandas as pd
file_data = pd.read_csv("file_path", index_col=0)
d = pd.Series(file_data.country, index=['BR','RU','IN'] or index =  file_data.index)

output:

>>> d
BR           Brazil
RU           Russia
IN            India

df = pd.DataFrame(file_data.area, index=['BR','RU','IN'] or index = file_data.index )

output:

>>> df
      area
BR   12015
RU     457
IN  457787

What is the difference between SessionState and ViewState?

SessionState

  • Can be persisted in memory, which makes it a fast solution. Which means state cannot be shared in the Web Farm/Web Garden.
  • Can be persisted in a Database, useful for Web Farms / Web Gardens.
  • Is Cleared when the session dies - usually after 20min of inactivity.

ViewState

  • Is sent back and forth between the server and client, taking up bandwidth.
  • Has no expiration date.
  • Is useful in a Web Farm / Web Garden

How do I add slashes to a string in Javascript?

A string can be escaped comprehensively and compactly using JSON.stringify. It is part of JavaScript as of ECMAScript 5 and supported by major newer browser versions.

str = JSON.stringify(String(str));
str = str.substring(1, str.length-1);

Using this approach, also special chars as the null byte, unicode characters and line breaks \r and \n are escaped properly in a relatively compact statement.

matplotlib: Group boxplots

Here is my version. It stores data based on categories.

import matplotlib.pyplot as plt
import numpy as np

data_a = [[1,2,5], [5,7,2,2,5], [7,2,5]]
data_b = [[6,4,2], [1,2,5,3,2], [2,3,5,1]]

ticks = ['A', 'B', 'C']

def set_box_color(bp, color):
    plt.setp(bp['boxes'], color=color)
    plt.setp(bp['whiskers'], color=color)
    plt.setp(bp['caps'], color=color)
    plt.setp(bp['medians'], color=color)

plt.figure()

bpl = plt.boxplot(data_a, positions=np.array(xrange(len(data_a)))*2.0-0.4, sym='', widths=0.6)
bpr = plt.boxplot(data_b, positions=np.array(xrange(len(data_b)))*2.0+0.4, sym='', widths=0.6)
set_box_color(bpl, '#D7191C') # colors are from http://colorbrewer2.org/
set_box_color(bpr, '#2C7BB6')

# draw temporary red and blue lines and use them to create a legend
plt.plot([], c='#D7191C', label='Apples')
plt.plot([], c='#2C7BB6', label='Oranges')
plt.legend()

plt.xticks(xrange(0, len(ticks) * 2, 2), ticks)
plt.xlim(-2, len(ticks)*2)
plt.ylim(0, 8)
plt.tight_layout()
plt.savefig('boxcompare.png')

I am short of reputation so I cannot post an image to here. You can run it and see the result. Basically it's very similar to what Molly did.

Note that, depending on the version of python you are using, you may need to replace xrange with range

Result of this code

Redirect Windows cmd stdout and stderr to a single file

You want:

dir > a.txt 2>&1

The syntax 2>&1 will redirect 2 (stderr) to 1 (stdout). You can also hide messages by redirecting to NUL, more explanation and examples on MSDN.

How to change password using TortoiseSVN?

To change your password for accessing Subversion

Typically this would be handled by your Subversion server administrator. If that's you and you are using the built-in authentication, then edit your [repository]\conf\passwd file on your Subversion server machine.

To delete locally-cached credentials

Follow these steps:

  • Right-click your desktop and select TortoiseSVN->Settings
  • Select Saved Data.
  • Click Clear against Authentication Data.

Next time you attempt an action that requires credentials you'll be asked for them.

If you're using the command-line svn.exe use the --no-auth-cache option so that you can specify alternate credentials without having them cached against your Windows user.

MVC Razor view nested foreach's model

It is clear from the error.

The HtmlHelpers appended with "For" expects lambda expression as a parameter.

If you are passing the value directly, better use Normal one.

e.g.

Instead of TextboxFor(....) use Textbox()

syntax for TextboxFor will be like Html.TextBoxFor(m=>m.Property)

In your scenario you can use basic for loop, as it will give you index to use.

@for(int i=0;i<Model.Theme.Count;i++)
 {
   @Html.LabelFor(m=>m.Theme[i].name)
   @for(int j=0;j<Model.Theme[i].Products.Count;j++) )
     {
      @Html.LabelFor(m=>m.Theme[i].Products[j].name)
      @for(int k=0;k<Model.Theme[i].Products[j].Orders.Count;k++)
          {
           @Html.TextBoxFor(m=>Model.Theme[i].Products[j].Orders[k].Quantity)
           @Html.TextAreaFor(m=>Model.Theme[i].Products[j].Orders[k].Note)
           @Html.EditorFor(m=>Model.Theme[i].Products[j].Orders[k].DateRequestedDeliveryFor)
      }
   }
}

How do I convert a byte array to Base64 in Java?

In case you happen to be using Spring framework along with java, there is an easy way around.

  1. Import the following.

    import org.springframework.util.Base64Utils;
  2. Convert like this.

    byte[] bytearr ={0,1,2,3,4};
    String encodedText = Base64Utils.encodeToString(bytearr);
    

    To decode you can use the decodeToString method of the Base64Utils class.

Android Studio: “Execution failed for task ':app:mergeDebugResources'” if project is created on drive C:

I encountered the same error.

In the end, the problem was that I used an image in res/drawable that I copied in there and saved it as .png although the original file was .jpg .

I deleted the file (there's a warning message if there are still usages for the item in your code, but you can ignore it) and pasted it in with the original .jpg ending.

After a cleanup and gradle syncronization the error disappeared.

Count specific character occurrences in a string

Conversion of Ujjwal Manandhar's code to VB.NET as follows...

Dim a As String = "this is test"
Dim pattern As String = "t"
Dim ex As New System.Text.RegularExpressions.Regex(pattern)
Dim m As System.Text.RegularExpressions.MatchCollection
m = ex.Matches(a)
MsgBox(m.Count.ToString())

Establish a VPN connection in cmd

Have you looked into rasdial?

Just incase anyone wanted to do this and finds this in the future, you can use rasdial.exe from command prompt to connect to a VPN network

ie rasdial "VPN NETWORK NAME" "Username" *

it will then prompt for a password, else you can use "username" "password", this is however less secure

http://www.msfn.org/board/topic/113128-connect-to-vpn-from-cmdexe-vista/?p=747265

phpinfo() is not working on my CentOS server

This happened to me as well. The fix was wrapping it in HTML tags. Then I saved the file as /var/www/html/info.php and ran http://localhost/info.php in the browser. That's it.

<html>
    <body>
        <?php
            phpinfo();
        ?>
    </body>
</html>

How do I return a proper success/error message for JQuery .ajax() using PHP?

Just so you know, you can use this for debugging. It helped me a lot, and still does

error:function(x,e) {
    if (x.status==0) {
        alert('You are offline!!\n Please Check Your Network.');
    } else if(x.status==404) {
        alert('Requested URL not found.');
    } else if(x.status==500) {
        alert('Internel Server Error.');
    } else if(e=='parsererror') {
        alert('Error.\nParsing JSON Request failed.');
    } else if(e=='timeout'){
        alert('Request Time out.');
    } else {
        alert('Unknow Error.\n'+x.responseText);
    }
}

Can you 'exit' a loop in PHP?

You can use the break keyword.

Angular JS - angular.forEach - How to get key of the object?

var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
    console.log(key + ': ' + value);
});

yields the attributes of obj with their respective values:

name: Krishna
gender: male

How to start new activity on button click

Implement the View.OnClickListener interface and override the onClick method.

ImageView btnSearch;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search1);
        ImageView btnSearch = (ImageView) findViewById(R.id.btnSearch);
        btnSearch.setOnClickListener(this);
    }

@Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnSearch: {
                Intent intent = new Intent(Search.this,SearchFeedActivity.class);
                startActivity(intent);
                break;
            }

Create a string with n characters

RandomStringUtils has a provision to create a string from given input size. Cant comment on the speed, but its a one liner.

RandomStringUtils.random(5,"\t");

creates an output

\t\t\t\t\t

preferable if you dont want to see \0 in your code.

Image comparison - fast algorithm

Picking 100 random points could mean that similar (or occasionally even dissimilar) images would be marked as the same, which I assume is not what you want. MD5 hashes wouldn't work if the images were different formats (png, jpeg, etc), had different sizes, or had different metadata. Reducing all images to a smaller size is a good bet, doing a pixel-for- pixel comparison shouldn't take too long as long as you're using a good image library / fast language, and the size is small enough.

You could try making them tiny, then if they are the same perform another comparison on a larger size - could be a good combination of speed and accuracy...

Display MessageBox in ASP

If you want to do it from code behind, try this:

System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Message');", true);

Make the first character Uppercase in CSS

There's a property for that:

a.m_title {
    text-transform: capitalize;
}

If your links can contain multiple words and you only want the first letter of the first word to be uppercase, use :first-letter with a different transform instead (although it doesn't really matter). Note that in order for :first-letter to work your a elements need to be block containers (which can be display: block, display: inline-block, or any of a variety of other combinations of one or more properties):

a.m_title {
    display: block;
}

a.m_title:first-letter {
    text-transform: uppercase;
}

Eclipse Problems View not showing Errors anymore

In my case Eclipse wasn't properly picking up a Java project that a current project was dependent on.

You can go to Project > BuildPath > Configure BuildPath and then delete and re-add the project.

How to convert time milliseconds to hours, min, sec format in JavaScript?

This one returns time like youtube videos

    function getYoutubeLikeToDisplay(millisec) {
        var seconds = (millisec / 1000).toFixed(0);
        var minutes = Math.floor(seconds / 60);
        var hours = "";
        if (minutes > 59) {
            hours = Math.floor(minutes / 60);
            hours = (hours >= 10) ? hours : "0" + hours;
            minutes = minutes - (hours * 60);
            minutes = (minutes >= 10) ? minutes : "0" + minutes;
        }

        seconds = Math.floor(seconds % 60);
        seconds = (seconds >= 10) ? seconds : "0" + seconds;
        if (hours != "") {
            return hours + ":" + minutes + ":" + seconds;
        }
        return minutes + ":" + seconds;
    }

Output:

  • getYoutubeLikeToDisplay(129900) = "2:10"
  • getYoutubeLikeToDisplay(1229900) = "20:30"
  • getYoutubeLikeToDisplay(21229900) = "05:53:50"

Python Dictionary contains List as Value - How to update?

Probably something like this:

original_list = dictionary.get('C1')
new_list = []
for item in original_list:
  new_list.append(item+10)
dictionary['C1'] = new_list

How to Import .bson file format on mongodb

I have used this:

mongorestore -d databasename -c file.bson fullpath/file.bson

1.copy the file path and file name from properties (try to put all bson files in different folder), 2.use this again and again with changing file name only.

How to delete a localStorage item when the browser window/tab is closed?

localStorage.removeItem(key);  //item

localStorage.clear(); //all items

Clicking HTML 5 Video element to play, pause video, breaks play button

Adding return false; worked for me:

jQuery version:

$(document).on('click', '#video-id', function (e) {
    var video = $(this).get(0);
    if (video.paused === false) {
        video.pause();
    } else {
        video.play();
    }

    return false;
});

Vanilla JavaScript version:

var v = document.getElementById('videoid');
v.addEventListener(
    'play', 
    function() { 
        v.play();
    }, 
    false);

v.onclick = function() {
    if (v.paused) {
        v.play();
    } else {
        v.pause();
    }

    return false;
};

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

How to check for empty value in Javascript?

First, I would check what i gets initialized to, to see if the elements returned by getElementsByName are what you think they are. Maybe split the problem by trying it with a hard-coded name like timetemp0, without the concatenation. You can also run the code through a browser debugger (FireBug, Chrome Dev Tools, IE Dev Tools).

Also, for your if-condition, this should suffice:

if (!timetemp[0].value) {
    // The value is empty.
}
else {
    // The value is not empty.
}

The empty string in Javascript is a falsey value, so the logical negation of that will get you into the if-block.

Find and replace strings in vim on multiple lines

You can do it with two find/replace sequences

  :6,10s/<search_string>/<replace_string>/g
  :14,18s/<search_string>/<replace_string>/g

The second time all you need to adjust is the range so instead of typing it all out, I would recall the last command and edit just the range

unknown type name 'uint8_t', MinGW

Try including stdint.h or inttypes.h.

handling dbnull data in vb.net

For the rows containing strings, I can convert them to strings as in changing

tmpStr = nameItem("lastname") + " " + nameItem("initials")

to

tmpStr = myItem("lastname").toString + " " + myItem("intials").toString

For the comparison in the if statement myItem("sID")=sID, it needs to be change to

myItem("sID").Equals(sID)

Then the code will run without any runtime errors due to vbNull data.

What is the difference between pip and conda?

Here is a short rundown:

pip

  • Python packages only.
  • Compiles everything from source. EDIT: pip now installs binary wheels, if they are available.
  • Blessed by the core Python community (i.e., Python 3.4+ includes code that automatically bootstraps pip).

conda

  • Python agnostic. The main focus of existing packages are for Python, and indeed Conda itself is written in Python, but you can also have Conda packages for C libraries, or R packages, or really anything.
  • Installs binaries. There is a tool called conda build that builds packages from source, but conda install itself installs things from already built Conda packages.
  • External. Conda is the package manager of Anaconda, the Python distribution provided by Continuum Analytics, but it can be used outside of Anaconda too. You can use it with an existing Python installation by pip installing it (though this is not recommended unless you have a good reason to use an existing installation).

In both cases:

  • Written in Python
  • Open source (Conda is BSD and pip is MIT)

The first two bullet points of Conda are really what make it advantageous over pip for many packages. Since pip installs from source, it can be painful to install things with it if you are unable to compile the source code (this is especially true on Windows, but it can even be true on Linux if the packages have some difficult C or FORTRAN library dependencies). Conda installs from binary, meaning that someone (e.g., Continuum) has already done the hard work of compiling the package, and so the installation is easy.

There are also some differences if you are interested in building your own packages. For instance, pip is built on top of setuptools, whereas Conda uses its own format, which has some advantages (like being static, and again, Python agnostic).

Shell script to get the process ID on Linux

Using grep on the results of ps is a bad idea in a script, since some proportion of the time it will also match the grep process you've just invoked. The command pgrep avoids this problem, so if you need to know the process ID, that's a better option. (Note that, of course, there may be many processes matched.)

However, in your example, you could just use the similar command pkill to kill all matching processes:

pkill ruby

Incidentally, you should be aware that using -9 is overkill (ho ho) in almost every case - there's some useful advice about that in the text of the "Useless Use of kill -9 form letter ":

No no no. Don't use kill -9.

It doesn't give the process a chance to cleanly:

  1. shut down socket connections
  2. clean up temp files
  3. inform its children that it is going away
  4. reset its terminal characteristics

and so on and so on and so on.

Generally, send 15, and wait a second or two, and if that doesn't work, send 2, and if that doesn't work, send 1. If that doesn't, REMOVE THE BINARY because the program is badly behaved!

Don't use kill -9. Don't bring out the combine harvester just to tidy up the flower pot.

Transparent background in JPEG image

You can't make a JPEG image transparent. You should use a format that allows transparency, like GIF or PNG.

Paint will open these files, but AFAIK it'll erase transparency if you edit the file. Use some other application like Paint.NET (it's free).

Edit: since other people have mentioned it: you can convert JPEG images into PNG, in any editor that's capable of working with both types.

Node - how to run app.js?

Node manages dependencies ie; third party code using package.json so that 3rd party modules names and versions can be kept stable for all installs of the project. This also helps keep the file be light-weight as only actual program code is present in the code repository. Whenever repository is cloned, for it to work(as 3rd party modules may be used in the code), you would need to install all dependencies. Use npm install on CMD within root of the project structure to complete installing all dependencies. This should resolve all dependencies issues if dependencies get properly installed.

Why is list initialization (using curly braces) better than the alternatives?

There are already great answers about the advantages of using list initialization, however my personal rule of thumb is NOT to use curly braces whenever possible, but instead make it dependent on the conceptual meaning:

  • If the object I'm creating conceptually holds the values I'm passing in the constructor (e.g. containers, POD structs, atomics, smart pointers etc.), then I'm using the braces.
  • If the constructor resembles a normal function call (it performs some more or less complex operations that are parametrized by the arguments) then I'm using the normal function call syntax.
  • For default initialization I always use curly braces.
    For one, that way I'm always sure that the object gets initialized irrespective of whether it e.g. is a "real" class with a default constructor that would get called anyway or a builtin / POD type. Second it is - in most cases - consistent with the first rule, as a default initialized object often represents an "empty" object.

In my experience, this ruleset can be applied much more consistently than using curly braces by default, but having to explicitly remember all the exceptions when they can't be used or have a different meaning than the "normal" function-call syntax with parenthesis (calls a different overload).

It e.g. fits nicely with standard library-types like std::vector:

vector<int> a{10,20};   //Curly braces -> fills the vector with the arguments

vector<int> b(10,20);   //Parentheses -> uses arguments to parametrize some functionality,                          
vector<int> c(it1,it2); //like filling the vector with 10 integers or copying a range.

vector<int> d{};      //empty braces -> default constructs vector, which is equivalent
                      //to a vector that is filled with zero elements

React-router urls don't work when refreshing or writing manually

I found the solution for my SPA with react router (Apache). Just add in .htaccess

<IfModule mod_rewrite.c>

  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]

</IfModule>

source: https://gist.github.com/alexsasharegan/173878f9d67055bfef63449fa7136042

How to change options of <select> with jQuery?

Does this help?

$("#SelectName option[value='theValueOfOption']")[0].selected = true;

milliseconds to days

int days = (int) (milliseconds / 86 400 000 )

Cannot implicitly convert type 'int?' to 'int'.

Well you're casting OrdersPerHour to an int?

OrdersPerHour = (int?)dbcommand.ExecuteScalar();

Yet your method signature is int:

static int OrdersPerHour(string User)

The two have to match.


Also a quick suggestion -> Use parameters in your query, something like:

string query = "SELECT COUNT(ControlNumber) FROM Log WHERE DateChanged > ? AND User = ? AND Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery', 'CA Review', '1TSI To Be Delivered')";
OleDbCommand dbcommand = new OleDbCommand(query, conn);
dbcommand.Parameters.Add(curTime.AddHours(-1));
dbcommand.Parameters.Add(User);

Pro JavaScript programmer interview questions (with answers)

Because JavaScript is such a small language, yet with incredible complexity, you should be able to ask relatively basic questions and find out if they are really that good based on their answers. For instance, my standard first question to gauge the rest of the interview is:

In JavaScript, what is the difference between var x = 1 and x = 1? Answer in as much or as little detail as you feel comfortable.

Novice JS programmers might have a basic answer about locals vs globals. Intermediate JS guys should definitely have that answer, and should probably mention function-level scope. Anyone calling themselves an "advanced" JS programmer should be prepared to talk about locals, implied globals, the window object, function-scope, declaration hoisting, and scope chains. Furthermore, I'd love to hear about [[DontDelete]], hoisting precedence (parameters vs var vs function), and undefined.

Another good question is to ask them to write a sum() function that accepts any number of arguments, and returns their sum. Then, ask them to use that function (without modification) to sum all the values in an array. They should write a function that looks like this:

function sum() {
  var i, l, result = 0;
  for (i = 0, l = arguments.length; i < l; i++) {
    result += arguments[i];
  }
  return result;
}
sum(1,2,3); // 6

And they should invoke it on your array like this (context for apply can be whatever, I usually use null in that case):

var data = [1,2,3];
sum.apply(null, data); // 6

If they've got those answers, they probably know their JavaScript. You should then proceed to asking them about non-JS specific stuff like testing, workflows, version control, etc. to find out if they're a good programmer.

Fatal error: Call to undefined function mb_strlen()

The function mb_strlen() is not enabled by default in PHP. Please read the manual for installation details:

http://www.php.net/manual/en/mbstring.installation.php

How to use `replace` of directive definition?

Replace [True | False (default)]

Effect

1.  Replace the directive element. 

Dependency:

1. When replace: true, the template or templateUrl must be required. 

recursion versus iteration

Besides being slower, recursion can also result in stack overflow errors depending on how deep it goes.

How do I use grep to search the current directory for all files having the a string "hello" yet display only .h and .cc files?

find . -name \*.cc -print0 -or -name \*.h -print0 | xargs -0 grep "hello".

Check the manual pages for find and xargs for details.

Custom Drawable for ProgressBar/ProgressDialog

Custom progress with scale!

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_no_smile_eyes_off"
            android:scaleGravity="center" />
    </item>
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_no_smile_eyes_on"
            android:scaleGravity="center" />
    </item>
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_smile_eyes_off"
            android:scaleGravity="center" />
    </item>
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_smile_eyes_on"
            android:scaleGravity="center" />
    </item>

</animation-list>

Change type of varchar field to integer: "cannot be cast automatically to type integer"

There is no implicit (automatic) cast from text or varchar to integer (i.e. you cannot pass a varchar to a function expecting integer or assign a varchar field to an integer one), so you must specify an explicit cast using ALTER TABLE ... ALTER COLUMN ... TYPE ... USING:

ALTER TABLE the_table ALTER COLUMN col_name TYPE integer USING (col_name::integer);

Note that you may have whitespace in your text fields; in that case, use:

ALTER TABLE the_table ALTER COLUMN col_name TYPE integer USING (trim(col_name)::integer);

to strip white space before converting.

This shoud've been obvious from an error message if the command was run in psql, but it's possible PgAdmin-III isn't showing you the full error. Here's what happens if I test it in psql on PostgreSQL 9.2:

=> CREATE TABLE test( x varchar );
CREATE TABLE
=> insert into test(x) values ('14'), (' 42  ');
INSERT 0 2
=> ALTER TABLE test ALTER COLUMN x TYPE integer;
ERROR:  column "x" cannot be cast automatically to type integer
HINT:  Specify a USING expression to perform the conversion. 
=> ALTER TABLE test ALTER COLUMN x TYPE integer USING (trim(x)::integer);
ALTER TABLE        

Thanks @muistooshort for adding the USING link.

See also this related question; it's about Rails migrations, but the underlying cause is the same and the answer applies.

If the error still occurs, then it may be related not to column values, but indexes over this column or column default values might fail typecast. Indexes need to be dropped before ALTER COLUMN and recreated after. Default values should be changed appropriately.

Converting Integer to Long

Convert an integer directly to long by adding 'L' to the end of Integer.

Long i = 1234L;

Java variable number or arguments for a method

That's correct. You can find more about it in the Oracle guide on varargs.

Here's an example:

void foo(String... args) {
    for (String arg : args) {
        System.out.println(arg);
    }
}

which can be called as

foo("foo"); // Single arg.
foo("foo", "bar"); // Multiple args.
foo("foo", "bar", "lol"); // Don't matter how many!
foo(new String[] { "foo", "bar" }); // Arrays are also accepted.
foo(); // And even no args.

Exporting data In SQL Server as INSERT INTO

You could also check out the "Data Scripter Add-In" for SQL Server Management Studio 2008 from:

http://www.mssql-vehicle-data.com/SSMS


Their features list:

  • It was developed on SSMS 2008 and is not supported on the 2005 version at this time (soon!)

  • Export data quickly to T-SQL for MSSQL and MySQL syntax

  • CSV, TXT, XML are also supported! Harness the full potential, power, and speed that SQL has to offer.

  • Don't wait for Access or Excel to do scripting work for you that could take several minutes to do -- let SQL Server do it for you and take all the guess work out of exporting your data!

  • Customize your data output for rapid backups, DDL manipulation, and more...

  • Change table names and database schemas to your needs, quickly and efficiently

  • Export column names or simply generate data without the names.

  • You can chose individual columns to script.

  • You can chose sub-sets of data (WHERE clause).

  • You can chose ordering of data (ORDER BY clause).

  • Great backup utility for those grungy database debugging operations that require data manipulation. Don't lose data while experimenting. Manipulate data on the fly!

How to detect Adblock on my website?

Just add small script on your site:

var isAdsDisplayed = true;

With name adsbygoogle.js

Then do following:

<script src="/js/adsbygoogle.js"></script>
<script>
if(window.isAdsDisplayed === undefined ) {
  // AdBlock is enabled. Show message or track custom data here
}
</script>

Found this solution here

How to simulate a button click using code?

Just write this simple line of code :-

button.performClick();

where button is the reference variable of Button class and defined as follows:-

private Button buttonToday ;
buttonToday = (Button) findViewById(R.id.buttonToday);

That's it.

How prevent CPU usage 100% because of worker process in iis

There are a lot of reasons that you can be seeing w3wp.exe high CPU usage. I have selected six common causes to cover.

  1. High error rates within your ASP.NET web application
  2. Increase in web traffic causing high CPU
  3. Problems with application dependencies
  4. Garbage collection
  5. Requests getting blocked or hung somewhere in the ASP.NET pipeline
  6. Inefficient .NET code that needs to be optimized

What's the correct way to convert bytes to a hex string in Python 3?

The method binascii.hexlify() will convert bytes to a bytes representing the ascii hex string. That means that each byte in the input will get converted to two ascii characters. If you want a true str out then you can .decode("ascii") the result.

I included an snippet that illustrates it.

import binascii

with open("addressbook.bin", "rb") as f: # or any binary file like '/bin/ls'
    in_bytes = f.read()
    print(in_bytes) # b'\n\x16\n\x04'
    hex_bytes = binascii.hexlify(in_bytes) 
    print(hex_bytes) # b'0a160a04' which is twice as long as in_bytes
    hex_str = hex_bytes.decode("ascii")
    print(hex_str) # 0a160a04

from the hex string "0a160a04" to can come back to the bytes with binascii.unhexlify("0a160a04") which gives back b'\n\x16\n\x04'

Empty or Null value display in SSRS text boxes

While probably not any better than your solution, you could adjust your T-SQL to return the same result using COALESCE:

SELECT MyField = COALESCE(table.MyField, " NA")

The reasoning for the extra space before the NA is to allow sorting to place the NA results at the top. Since your data may vary, that may not be a great option.

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

I have got the same error but I have resolved the issue in the following ways:

  1. Provide all the mandatory filed of your bean/model class
  2. Don't violet the concept of the unique constraint, Provide unique value in Unique constraints.

Setting the selected attribute on a select list using jQuery

Code:

var select = function(dropdown, selectedValue) {
    var options = $(dropdown).find("option");
    var matches = $.grep(options,
        function(n) { return $(n).text() == selectedValue; });
    $(matches).attr("selected", "selected");
};

Example:

select("#dropdown", "B");

How can I create an executable JAR with dependencies using Maven?

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.4.1</version>
            <configuration>
                <!-- get all project dependencies -->
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
            <executions>
                <execution>
                    <id>make-assembly</id>
                    <!-- bind to the packaging phase -->
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

How to list physical disks?

Thic WMIC command combination works fine:

wmic volume list brief

What's the name for hyphen-separated case?

Adding the correct link here Kebab Case

which is All lowercase with - separating words.

compression and decompression of string data in java

You can't convert binary data to String. As a solution you can encode binary data and then convert to String. For example, look at this How do you convert binary data to Strings and back in Java?

What's the difference between [ and [[ in Bash?

The most important difference will be the clarity of your code. Yes, yes, what's been said above is true, but [[ ]] brings your code in line with what you would expect in high level languages, especially in regards to AND (&&), OR (||), and NOT (!) operators. Thus, when you move between systems and languages you will be able to interpret script faster which makes your life easier. Get the nitty gritty from a good UNIX/Linux reference. You may find some of the nitty gritty to be useful in certain circumstances, but you will always appreciate clear code! Which script fragment would you rather read? Even out of context, the first choice is easier to read and understand.


if [[ -d $newDir && -n $(echo $newDir | grep "^${webRootParent}") && -n $(echo $newDir | grep '/$') ]]; then ...

or

if [ -d "$newDir" -a -n "$(echo "$newDir" | grep "^${webRootParent}")" -a -n "$(echo "$newDir" | grep '/$')" ]; then ...

Redirect output of mongo query to a csv file

Here is what you can try:

print("id,name,startDate")
cursor = db.<collection_name>.find();
while (cursor.hasNext()) {
    jsonObject = cursor.next();
    print(jsonObject._id.valueOf() + "," + jsonObject.name + ",\"" + jsonObject.stateDate.toUTCString() +"\"")

}

Save that in a file, say "export.js". Run the following command:

mongo <host>/<dbname> -u <username> -p <password> export.js > out.csv

How can I use async/await at the top level?

Node -
You can run node --experimental-repl-await while in the REPL. I'm not so sure about scripting.

Deno -
Deno already has it built in.

Execute a terminal command from a Cocoa app

You can use NSTask. Here's an example that would run '/usr/bin/grep foo bar.txt'.

int pid = [[NSProcessInfo processInfo] processIdentifier];
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;

NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/grep";
task.arguments = @[@"foo", @"bar.txt"];
task.standardOutput = pipe;

[task launch];

NSData *data = [file readDataToEndOfFile];
[file closeFile];

NSString *grepOutput = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"grep returned:\n%@", grepOutput);

NSPipe and NSFileHandle are used to redirect the standard output of the task.

For more detailed information on interacting with the operating system from within your Objective-C application, you can see this document on Apple's Development Center: Interacting with the Operating System.

Edit: Included fix for NSLog problem

If you are using NSTask to run a command-line utility via bash, then you need to include this magic line to keep NSLog working:

//The magic line that keeps your log where it belongs
task.standardOutput = pipe;

An explanation is here: https://web.archive.org/web/20141121094204/https://cocoadev.com/HowToPipeCommandsWithNSTask

Get timezone from users browser using moment(timezone).js

When using moment.js, use:

var tz = moment.tz.guess();

It will return an IANA time zone identifier, such as America/Los_Angeles for the US Pacific time zone.

It is documented here.

Internally, it first tries to get the time zone from the browser using the following call:

Intl.DateTimeFormat().resolvedOptions().timeZone

If you are targeting only modern browsers that support this function, and you don't need Moment-Timezone for anything else, then you can just call that directly.

If Moment-Timezone doesn't get a valid result from that function, or if that function doesn't exist, then it will "guess" the time zone by testing several different dates and times against the Date object to see how it behaves. The guess is usually a good enough approximation, but not guaranteed to exactly match the time zone setting of the computer.

How do I detect when someone shakes an iPhone?

In 3.0, there's now an easier way - hook into the new motion events.

The main trick is that you need to have some UIView (not UIViewController) that you want as firstResponder to receive the shake event messages. Here's the code that you can use in any UIView to get shake events:

@implementation ShakingView

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if ( event.subtype == UIEventSubtypeMotionShake )
    {
        // Put in code here to handle shake
    }

    if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] )
        [super motionEnded:motion withEvent:event];
}

- (BOOL)canBecomeFirstResponder
{ return YES; }

@end

You can easily transform any UIView (even system views) into a view that can get the shake event simply by subclassing the view with only these methods (and then selecting this new type instead of the base type in IB, or using it when allocating a view).

In the view controller, you want to set this view to become first responder:

- (void) viewWillAppear:(BOOL)animated
{
    [shakeView becomeFirstResponder];
    [super viewWillAppear:animated];
}
- (void) viewWillDisappear:(BOOL)animated
{
    [shakeView resignFirstResponder];
    [super viewWillDisappear:animated];
}

Don't forget that if you have other views that become first responder from user actions (like a search bar or text entry field) you'll also need to restore the shaking view first responder status when the other view resigns!

This method works even if you set applicationSupportsShakeToEdit to NO.

Environment Variable with Maven

You can just pass it on the command line, as

mvn -DmyVariable=someValue install

[Update] Note that the order of parameters is significant - you need to specify any options before the command(s).[/Update]

Within the POM file, you may refer to system variables (specified on the command line, or in the pom) as ${myVariable}, and environment variables as ${env.myVariable}. (Thanks to commenters for the correction.)

Update2

OK, so you want to pass your system variable to your tests. If - as I assume - you use the Surefire plugin for testing, the best is to specify the needed system variable(s) within the pom, in your plugins section, e.g.

<build>
    <plugins>
        ...
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            ...
            <configuration>
                ...
                <systemPropertyVariables>
                    <WSNSHELL_HOME>conf</WSNSHELL_HOME>
                </systemPropertyVariables>
            </configuration>
        </plugin>
        ...
    </plugins>
</build>

How to set RelativeLayout layout params in code not in xml?

Just a basic example:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
Button button1;
button1.setLayoutParams(params);

params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, button1.getId());
Button button2;
button2.setLayoutParams(params);

As you can see, this is what you have to do:

  1. Create a RelativeLayout.LayoutParams object.
  2. Use addRule(int) or addRule(int, int) to set the rules. The first method is used to add rules that don't require values.
  3. Set the parameters to the view (in this case, to each button).

Regex Explanation ^.*$

"^.*$"

literally just means select everything

"^"  // anchors to the beginning of the line
".*" // zero or more of any character
"$"  // anchors to end of line

Using awk to print all columns from the nth to the last

You could use a for-loop to loop through printing fields $2 through $NF (built-in variable that represents the number of fields on the line).

Edit: Since "print" appends a newline, you'll want to buffer the results:

awk '{out=""; for(i=2;i<=NF;i++){out=out" "$i}; print out}'

Alternatively, use printf:

awk '{for(i=2;i<=NF;i++){printf "%s ", $i}; printf "\n"}'

PHP: How to get referrer URL?

Underscore. Not space.

$_SERVER['HTTP_REFERER']

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

How to hide Table Row Overflow?

wrap the table in a div with class="container"

div.container {
    width: 100%;
    overflow-x: auto;
}

then

#table_id tr td {
   white-space:nowrap;
}

result

overflow effect

In CSS how do you change font size of h1 and h2

What have you tried? This should work.

h1 { font-size: 20pt; }
h2 { font-size: 16pt; }

Find file in directory from command line

I use this script to quickly find files across directories in a project. I have found it works great and takes advantage of Vim's autocomplete by opening up and closing an new buffer for the search. It also smartly completes as much as possible for you so you can usually just type a character or two and open the file across any directory in your project. I started using it specifically because of a Java project and it has saved me a lot of time. You just build the cache once when you start your editing session by typing :FC (directory names). You can also just use . to get the current directory and all subdirectories. After that you just type :FF (or FS to open up a new split) and it will open up a new buffer to select the file you want. After you select the file the temp buffer closes and you are inside the requested file and can start editing. In addition, here is another link on Stack Overflow that may help.

Why does the JFrame setSize() method not set the size correctly?

On OS X, you need to take into account existing window decorations. They add 22 pixels to the height. So on a JFrame, you need to tell the program this:

frame.setSize(width, height + 22);

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

There are several correct ways to display a down-pointing triangle.

Method 1 : use decimal HTML entity

HTML :

&#9660;

Method 2 : use hexidecimal HTML entity

HTML :

&#x25BC;

Method 3 : use character directly

HTML :

?

Method 4 : use CSS

HTML :

<span class='icon-down'></span>

CSS :

.icon-down:before {
    content: "\25BC";
}

Each of these three methods should have the same output. For other symbols, the same three options exist. Some even have a fourth option, allowing you to use a string based reference (eg. &hearts; to display ?).

You can use a reference website like Unicode-table.com to find which icons are supported in UNICODE and which codes they correspond with. For example, you find the values for the down-pointing triangle at http://unicode-table.com/en/25BC/.

Note that these methods are sufficient only for icons that are available by default in every browser. For symbols like ?,?,?,?,?,? or ?, this is far less likely to be the case. While it is possible to provide cross-browser support for other UNICODE symbols, the procedure is a bit more complicated.

If you want to know how to add support for less common UNICODE characters, see Create webfont with Unicode Supplementary Multilingual Plane symbols for more info on how to do this.


Background images

A totally different strategy is the use of background-images instead of fonts. For optimal performance, it's best to embed the image in your CSS file by base-encoding it, as mentioned by eg. @weasel5i2 and @Obsidian. I would recommend the use of SVG rather than GIF, however, is that's better both for performance and for the sharpness of your symbols.

This following code is the base64 for and SVG version of the enter image description here icon :

/* size: 0.9kb */
url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB3aWR0aD0iMTYiIGhlaWdodD0iMjgiIHZpZXdCb3g9IjAgMCAxNiAyOCI+PGcgaWQ9Imljb21vb24taWdub3JlIj48L2c+PHBhdGggZD0iTTE2IDE3cTAgMC40MDYtMC4yOTcgMC43MDNsLTcgN3EtMC4yOTcgMC4yOTctMC43MDMgMC4yOTd0LTAuNzAzLTAuMjk3bC03LTdxLTAuMjk3LTAuMjk3LTAuMjk3LTAuNzAzdDAuMjk3LTAuNzAzIDAuNzAzLTAuMjk3aDE0cTAuNDA2IDAgMC43MDMgMC4yOTd0MC4yOTcgMC43MDN6TTE2IDExcTAgMC40MDYtMC4yOTcgMC43MDN0LTAuNzAzIDAuMjk3aC0xNHEtMC40MDYgMC0wLjcwMy0wLjI5N3QtMC4yOTctMC43MDMgMC4yOTctMC43MDNsNy03cTAuMjk3LTAuMjk3IDAuNzAzLTAuMjk3dDAuNzAzIDAuMjk3bDcgN3EwLjI5NyAwLjI5NyAwLjI5NyAwLjcwM3oiIGZpbGw9IiMwMDAwMDAiPjwvcGF0aD48L3N2Zz4=

When to use background-images or fonts

For many use cases, SVG-based background images and icon fonts are largely equivalent with regards to performance and flexibility. To decide which to pick, consider the following differences:

SVG images

  • They can have multiple colors
  • They can embed their own CSS and/or be styled by the HTML document
  • They can be loaded as a seperate file, embedded in CSS AND embedded in HTML
  • Each symbol is represented by XML code or base64 code. You cannot use the character directly within your code editor or use an HTML entity
  • Multiple uses of the same symbol implies duplication of the symbol when XML code is embedded in the HTML. Duplication is not required when embedding the file in the CSS or loading it as a seperate file
  • You can not use color, font-size, line-height, background-color or other font related styling rules to change the display of your icon, but you can reference different components of the icon as shapes individually.
  • You need some knowledge of SVG and/or base64 encoding
  • Limited or no support in old versions of IE

Icon fonts

  • An icon can have but one fill color, one background color, etc.
  • An icon can be embedded in CSS or HTML. In HTML, you can use the character directly or use an HTML entity to represent it.
  • Some symbols can be displayed without the use of a webfont. Most symbols cannot.
  • Multiple uses of the same symbol implies duplication of the symbol when your character embedded in the HTML. Duplication is not required when embedding the file in the CSS.
  • You can use color, font-size, line-height, background-color or other font related styling rules to change the display of your icon
  • You need no special technical knowledge
  • Support in all major browsers, including old versions of IE

Personally, I would recommend the use of background-images only when you need multiple colors and those color can't be achieved by means of color, background-color and other color-related CSS rules for fonts.

The main benefit of using SVG images is that you can give different components of a symbol their own styling. If you embed your SVG XML code in the HTML document, this is very similar to styling the HTML. This would, however, result in a web page that uses both HTML tags and SVG tags, which could significantly reduce the readability of a webpage. It also adds extra bloat if the symbol is repeated across multiple pages and you need to consider that old versions of IE have no or limited support for SVG.

ASP.Net MVC 4 Form with 2 submit buttons/actions

You can do it with jquery, just put two methods to submit for to diffrent urls, for example with this form:

<form id="myForm">
    <%-- form data inputs here ---%>
    <button id="edit">Edit</button>
    <button id="validate">Validate</button>
</form>

you can use this script (make sure it is located in the View, in order to use the Url.Action attribute):

<script type="text/javascript">
      $("#edit").click(function() {
          var form = $("form#myForm");
          form.attr("action", "@Url.Action("Edit","MyController")");
          form.submit();
      });

      $("#validate").click(function() {
          var form = $("form#myForm");
          form.attr("action", "@Url.Action("Validate","MyController")");
          form.submit();
      });
</script>

How to convert CLOB to VARCHAR2 inside oracle pl/sql

This is my aproximation:

  Declare 
  Variableclob Clob;
  Temp_Save Varchar2(32767); //whether it is greater than 4000

  Begin
  Select reportClob Into Temp_Save From Reporte Where Id=...;
  Variableclob:=To_Clob(Temp_Save);
  Dbms_Output.Put_Line(Variableclob);


  End;

Connecting to SQL Server with Visual Studio Express Editions

I just happened to have started my home business application in windows forms for the convenience. I'm currently using Visual C# Express 2010 / SQL Server 2008 R2 Express to develop it. I got the same problem as OP where I need to connect to an instance of SQL server. I'm skipping details here but that database will be a merged database synched between 2-3 computers that will also use the application I'm developing right now.

I found a quick workaround, at least, I think I did because I'm now able to use my stored procedures in tableadapters without any issues so far.

I copy pasted an SQL connection that I used in a different project at work (VS2010 Premium) in the app.config and changed everything I needed there. When I went back to my Settings.settings, I just had to confirm that I wanted what was inside the app.config file. The only downsides I can see is that you can't "test" the connection since when you go inside the configuration of the connection string you can't go anywhere since "SQL Server" is not an option. The other downside is that you need to input everything manually since you can't use any wizards to make it work.

I don't know if I should have done it that way but at least I can connect to my SQL server now :).

EDIT :

It only works with SQL Server 2008 R2 Express instances. If you try with SQL Server 2008 R2 Workgroup and up, you'll get a nasty warning from Visual C# 2010 Express telling you that "you can't use that connection with the current version of Visual Studio". I got that when I was trying to modify some of my tableadapters. I switched back to an SQL Express instance to develop and it's working fine again.

What's the best way to test SQL Server connection programmatically?

For what Joel Coehorn suggested, have you already tried the utility named tcping. I know this is something you are not doing programmatically. It is a standalone executable which allows you to ping every specified time interval. It is not in C# though. Also..I am not sure If this would work If the target machine has firewall..hmmm..

[I am kinda new to this site and mistakenly added this as a comment, now added this as an answer. Let me know If this can be done here as I have duplicate comments (as comment and as an answer) here. I can not delete comments here.]

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

That usually means a null is being posted to the query instead of your desired value, you might try to run the SQL Profiler to see exactly what is getting passed to SQL Server from linq.

CodeIgniter: How to use WHERE clause and OR clause

What worked for me :

  $where = '';
   /* $this->db->like('ust.title',$query_data['search'])
        ->or_like('usr.f_name',$query_data['search'])
        ->or_like('usr.l_name',$query_data['search']);*/
        $where .= "(ust.title like '%".$query_data['search']."%'";
        $where .= " or usr.f_name like '%".$query_data['search']."%'";
        $where .= "or usr.l_name like '%".$query_data['search']."%')";
        $this->db->where($where);



$datas = $this->db->join(TBL_USERS.' AS usr','ust.user_id=usr.id')
            ->where_in('ust.id', $blog_list) 
            ->select('ust.*,usr.f_name as f_name,usr.email as email,usr.avatar as avatar, usr.sex as sex')
            ->get_where(TBL_GURU_BLOG.' AS ust',[
                'ust.deleted_at'     =>  NULL,
                'ust.status'     =>  1,
            ]); 

I have to do this to create a query like this :

SELECT `ust`.*, `usr`.`f_name` as `f_name`, `usr`.`email` as `email`, `usr`.`avatar` as `avatar`, `usr`.`sex` as `sex` FROM `blog` AS `ust` JOIN `users` AS `usr` ON `ust`.`user_id`=`usr`.`id` WHERE (`ust`.`title` LIKE '%mer%' ESCAPE '!' OR  `usr`.`f_name` LIKE '%lok%' ESCAPE '!' OR  `usr`.`l_name` LIKE '%mer%' ESCAPE '!') AND `ust`.`id` IN('36', '37', '38') AND `ust`.`deleted_at` IS NULL AND `ust`.`status` = 1 ;

How to declare 2D array in bash

Another approach is you can represent each row as a string, i.e. mapping the 2D array into an 1D array. Then, all you need to do is unpack and repack the row's string whenever you make an edit:

# Init a 4x5 matrix
a=("00 01 02 03 04" "10 11 12 13 14" "20 21 22 23 24" "30 31 32 33 34")

aset() {
  row=$1
  col=$2
  value=$3
  IFS=' ' read -r -a tmp <<< "${a[$row]}"
  tmp[$col]=$value
  a[$row]="${tmp[@]}"
}

# Set a[2][3] = 9999
aset 2 3 9999

# Show result
for r in "${a[@]}"; do
  echo $r
done

Outputs:

00 01 02 03 04
10 11 12 13 14
20 21 22 9999 24
30 31 32 33 34

Better way to shuffle two numpy arrays in unison

Very simple solution:

randomize = np.arange(len(x))
np.random.shuffle(randomize)
x = x[randomize]
y = y[randomize]

the two arrays x,y are now both randomly shuffled in the same way

Use different Python version with virtualenv

UBUNTU 19.04 / Global Python 3.7.

This worked for me, enabling a Python 3.8 environment using the recommended venv for python 3 development.

Install 3.8 and 3.8 venv module: $ sudo apt install python3.8 python3.8-venv
plus any other modules you need

Create your Virtual Env using the python version you want in that env

$ /usr/bin/python3.8 -m venv python38-env

switch into your virtual env

$ source python38-env/bin/activate

python -V = python 3.8

How to declare global variables in Android?

You can do this using two approaches:

  1. Using Application class
  2. Using Shared Preferences

  3. Using Application class

Example:

class SessionManager extends Application{

  String sessionKey;

  setSessionKey(String key){
    this.sessionKey=key;
  }

  String getSessisonKey(){
    return this.sessionKey;
  }
}

You can use above class to implement login in your MainActivity as below. Code will look something like this:

@override 
public void onCreate (Bundle savedInstanceState){
  // you will this key when first time login is successful.
  SessionManager session= (SessionManager)getApplicationContext();
  String key=getSessisonKey.getKey();
  //Use this key to identify whether session is alive or not.
}

This method will work for temporary storage. You really do not any idea when operating system is gonna kill the application, because of low memory. When your application is in background and user is navigating through other application which demands more memory to run, then your application will be killed since operating system given more priority to foreground processes than background. Hence your application object will be null before user logs out. Hence for this I recommend to use second method Specified above.

  1. Using shared preferences.

    String MYPREF="com.your.application.session"
    
    SharedPreferences pref= context.getSharedPreferences(MyPREF,MODE_PRIVATE);
    
    //Insert key as below:
    
    Editot editor= pref.edit();
    
    editor.putString("key","value");
    
    editor.commit();
    
    //Get key as below.
    
    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    
    String key= getResources().getString("key");
    

How to check the version before installing a package using apt-get?

on debian :

apt list --upgradable

gives the list with package, version to be upgraded, and actual version of the package.

result :

base-files/stable 8+deb8u8 amd64 [upgradable from: 8+deb8u7]
bind9-host/stable 1:9.9.5.dfsg-9+deb8u11 amd64 [upgradable from: 1:9.9.5.dfsg-9+deb8u9]
ca-certificates/stable 20141019+deb8u3 all [upgradable from: 20141019+deb8u2]
certbot/jessie-backports 0.10.2-1~bpo8+1 all [upgradable from: 0.8.1-2~bpo8+1]
dnsutils/stable 1:9.9.5.dfsg-9+deb8u11 amd64 [upgradable from: 1:9.9.5.dfsg-9+deb8u9]

Stick button to right side of div

change the CSS as follows:

div button {
position:absolute;
    right:10px;
    top:25px;
}

C# Parsing JSON array of objects

Use newtonsoft like so:

using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;

class Program
{
    static void Main()
    {
        string json = "{'results':[{'SwiftCode':'','City':'','BankName':'Deutsche    Bank','Bankkey':'10020030','Bankcountry':'DE'},{'SwiftCode':'','City':'10891    Berlin','BankName':'Commerzbank Berlin (West)','Bankkey':'10040000','Bankcountry':'DE'}]}";

        var resultObjects = AllChildren(JObject.Parse(json))
            .First(c => c.Type == JTokenType.Array && c.Path.Contains("results"))
            .Children<JObject>();

        foreach (JObject result in resultObjects) {
            foreach (JProperty property in result.Properties()) {
                // do something with the property belonging to result
            }
        }
    }

    // recursively yield all children of json
    private static IEnumerable<JToken> AllChildren(JToken json)
    {
        foreach (var c in json.Children()) {
            yield return c;
            foreach (var cc in AllChildren(c)) {
                yield return cc;
            }
        }
    }
}

How to find duplicate records in PostgreSQL

From "Find duplicate rows with PostgreSQL" here's smart solution:

select * from (
  SELECT id,
  ROW_NUMBER() OVER(PARTITION BY column1, column2 ORDER BY id asc) AS Row
  FROM tbl
) dups
where 
dups.Row > 1

Checking if a string array contains a value, and if so, getting its position

string[] strArray = { "text1", "text2", "text3", "text4" };
string value = "text3";

if(Array.contains(strArray , value))
{
    // Do something if the value is available in Array.
}

Regex to check if valid URL that ends in .jpg, .png, or .gif

This expression will match all the image urls -

^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+(?:png|jpg|jpeg|gif|svg)+$

Examples -

Valid -

https://itelligencegroup.com/wp-content/usermedia/de_home_teaser-box_puzzle_in_the_sun.png
http://sweetytextmessages.com/wp-content/uploads/2016/11/9-Happy-Monday-images.jpg
example.com/de_home_teaser-box_puzzle_in_the_sun.png
www.example.com/de_home_teaser-box_puzzle_in_the_sun.png
https://www.greetingseveryday.com/wp-content/uploads/2016/08/Happy-Independence-Day-Greetings-Cards-Pictures-in-Urdu-Marathi-1.jpg
http://thuglifememe.com/wp-content/uploads/2017/12/Top-Happy-tuesday-quotes-1.jpg
https://1.bp.blogspot.com/-ejYG9pr06O4/Wlhn48nx9cI/AAAAAAAAC7s/gAVN3tEV3NYiNPuE-Qpr05TpqLiG79tEQCLcBGAs/s1600/Republic-Day-2017-Wallpapers.jpg

Invalid -

https://www.example.com
http://www.example.com
www.example.com
example.com
http://blog.example.com
http://www.example.com/product
http://www.example.com/products?id=1&page=2
http://www.example.com#up
http://255.255.255.255
255.255.255.255
http://invalid.com/perl.cgi?key= | http://web-site.com/cgi-bin/perl.cgi?key1=value1&key2
http://www.siteabcd.com:8008

Remove json element

Do NOT have trailing commas in your OBJECT (JSON is a string notation)

UPDATE: you need to use array.splice and not delete if you want to remove items from the array in the object. Alternatively filter the array for undefined after removing

_x000D_
_x000D_
var data = {
  "result": [{
    "FirstName": "Test1",
    "LastName": "User"
  }, {
    "FirstName": "user",
    "LastName": "user"
  }]
}
console.log(data.result);
console.log("------------ deleting -------------");
delete data.result[1];
console.log(data.result); // note the "undefined" in the array.


data = {
  "result": [{
    "FirstName": "Test1",
    "LastName": "User"
  }, {
    "FirstName": "user",
    "LastName": "user"
  }]
}

console.log(data.result);
console.log("------------ slicing -------------");
var deletedItem = data.result.splice(1,1);
console.log(data.result); // here no problem with undefined.
_x000D_
_x000D_
_x000D_

How to send string from one activity to another?

Intents are intense.

Intents are useful for passing data around the android framework. You can communicate with your own Activities and even other processes. Check the developer guide and if you have specific questions (it's a lot to digest up front) come back.

What is meant with "const" at end of function declaration?

Similar to this question.

In essence it means that the method Bar will not modify non mutable member variables of Foo.

Creating a script for a Telnet session?

Check for the SendCommand tool.

You can use it as follows:

perl sendcommand.pl -i login.txt -t cisco -c "show ip route"

How to center cards in bootstrap 4?

You can also use Bootstrap 4 flex classes

Like: .align-item-center and .justify-content-center

We can use these classes identically for all device view.

Like: .align-item-sm-center, .align-item-md-center, .justify-content-xl-center, .justify-content-lg-center, .justify-content-xs-center

.text-center class is used to align text in center.

Google Maps v3 - limit viewable area and zoom level

Good news. Starting from the version 3.35 of Maps JavaScript API, that was launched on February 14, 2019, you can use new restriction option in order to limit the viewport of the map.

According to the documentation

MapRestriction interface

A restriction that can be applied to the Map. The map's viewport will not exceed these restrictions.

source: https://developers.google.com/maps/documentation/javascript/reference/map#MapRestriction

So, now you just add restriction option during a map initialization and that it. Have a look at the following example that limits viewport to Switzerland

_x000D_
_x000D_
var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 46.818188, lng: 8.227512},
    minZoom: 7,
    maxZoom: 14,
    zoom: 7,
    restriction: {
      latLngBounds: {
        east: 10.49234,
        north: 47.808455,
        south: 45.81792,
        west: 5.95608
      },
      strictBounds: true
    },
  });
}
_x000D_
#map {
  height: 100%;
}
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
_x000D_
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap" async defer></script>
_x000D_
_x000D_
_x000D_

I hope this helps!

Https Connection Android

Any of this answers didn't work for me so here is code which trust any certificates.

import java.io.IOException;

    import java.net.Socket;
    import java.security.KeyManagementException;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.UnrecoverableKeyException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;

    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;

    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.conn.scheme.PlainSocketFactory;
    import org.apache.http.conn.scheme.Scheme;
    import org.apache.http.conn.scheme.SchemeRegistry;
    import org.apache.http.conn.ssl.SSLSocketFactory;
    import org.apache.http.conn.ssl.X509HostnameVerifier;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
    import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

    public class HttpsClientBuilder {
        public static DefaultHttpClient getBelieverHttpsClient() {

            DefaultHttpClient client = null;

            SchemeRegistry Current_Scheme = new SchemeRegistry();
            Current_Scheme.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            try {
                Current_Scheme.register(new Scheme("https", new Naive_SSLSocketFactory(), 8443));
            } catch (KeyManagementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (UnrecoverableKeyException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (KeyStoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            HttpParams Current_Params = new BasicHttpParams();
            int timeoutConnection = 8000;
            HttpConnectionParams.setConnectionTimeout(Current_Params, timeoutConnection);
            int timeoutSocket = 10000;
            HttpConnectionParams.setSoTimeout(Current_Params, timeoutSocket);
            ThreadSafeClientConnManager Current_Manager = new ThreadSafeClientConnManager(Current_Params, Current_Scheme);
            client = new DefaultHttpClient(Current_Manager, Current_Params);
            //HttpPost httpPost = new HttpPost(url);
            //client.execute(httpPost);

         return client;
         }

    public static class Naive_SSLSocketFactory extends SSLSocketFactory
    {
        protected SSLContext Cur_SSL_Context = SSLContext.getInstance("TLS");

        public Naive_SSLSocketFactory ()
                throws NoSuchAlgorithmException, KeyManagementException,
                KeyStoreException, UnrecoverableKeyException
        {
            super(null, null, null, null, null, (X509HostnameVerifier)null);
            Cur_SSL_Context.init(null, new TrustManager[] { new X509_Trust_Manager() }, null);
        }

        @Override
        public Socket createSocket(Socket socket, String host, int port,
                boolean autoClose) throws IOException
        {
            return Cur_SSL_Context.getSocketFactory().createSocket(socket, host, port, autoClose);
        }

        @Override
        public Socket createSocket() throws IOException
        {
            return Cur_SSL_Context.getSocketFactory().createSocket();
        }
    }

    private static class X509_Trust_Manager implements X509TrustManager
    {

        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub

        }

        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub

        }

        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }

    };
}

How to go back last page

The way I did it while navigating to different page add a query param by passing current location

this.router.navigate(["user/edit"], { queryParams: { returnUrl: this.router.url }

Read this query param in your component

this.router.queryParams.subscribe((params) => {
    this.returnUrl = params.returnUrl;
});

If returnUrl is present enable the back button and when user clicks the back button

this.router.navigateByUrl(this.returnUrl); // Hint taken from Sasxa

This should able to navigate to previous page. Instead of using location.back I feel the above method is more safe consider the case where user directly lands to your page and if he presses the back button with location.back it will redirects user to previous page which will not be your web page.

Compare two different files line by line in python

Once the file object is iterated, it is exausted.

>>> f = open('1.txt', 'w')
>>> f.write('1\n2\n3\n')
>>> f.close()
>>> f = open('1.txt', 'r')
>>> for line in f: print line
...
1

2

3

# exausted, another iteration does not produce anything.
>>> for line in f: print line
...
>>>

Use file.seek (or close/open the file) to rewind the file:

>>> f.seek(0)
>>> for line in f: print line
...
1

2

3

Query to check index on a table

Most modern RDBMSs support the INFORMATION_SCHEMA schema. If yours supports that, then you want either INFORMATION_SCHEMA.TABLE_CONSTRAINTS or INFORMATION_SCHEMA.KEY_COLUMN_USAGE, or maybe both.

To see if yours supports it is as simple as running

select count(*) from INFORMATION_SCHEMA.TABLE_CONSTRAINTS

EDIT: SQL Server does have INFORMATION_SCHEMA, and it's easier to use than their vendor-specific tables, so just go with it.

Exact difference between CharSequence and String in java

General differences

There are several classes which implement the CharSequence interface besides String. Among these are

  • StringBuilder for variable-length character sequences which can be modified
  • CharBuffer for fixed-length low-level character sequences which can be modified

Any method which accepts a CharSequence can operate on all of these equally well. Any method which only accepts a String will require conversion. So using CharSequence as an argument type in all the places where you don't care about the internals is prudent. However you should use String as a return type if you actually return a String, because that avoids possible conversions of returned values if the calling method actually does require a String.

Also note that maps should use String as key type, not CharSequence, as map keys must not change. In other words, sometimes the immutable nature of String is essential.

Specific code snippet

As for the code you pasted: simply compile that, and have a look at the JVM bytecode using javap -v. There you will notice that both obj and str are references to the same constant object. As a String is immutable, this kind of sharing is all right.

The + operator of String is compiled as invocations of various StringBuilder.append calls. So it is equivalent to

System.out.println(
  (new StringBuilder())
  .append("output is : ")
  .append((Object)obj)
  .append(" ")
  .append(str)
  .toString()
)

I must confess I'm a bit surprised that my compiler javac 1.6.0_33 compiles the + obj using StringBuilder.append(Object) instead of StringBuilder.append(CharSequence). The former probably involves a call to the toString() method of the object, whereas the latter should be possible in a more efficient way. On the other hand, String.toString() simply returns the String itself, so there is little penalty there. So StringBuilder.append(String) might be more efficient by about one method invocation.

Logical Operators, || or OR?

Source: http://wallstreetdeveloper.com/php-logical-operators/

Here is sample code for working with logical operators:

<html>

<head>
    <title>Logical</title>
</head>

<body>
    <?php
        $a = 10;
        $b = 20;
        if ($a>$b)
        {
            echo " A is Greater";
        }
        elseif ($a<$b)
        {
            echo " A is lesser";
        }
        else
        {
             echo "A and B are equal";
        }
    ?>
    <?php
        $c = 30;
        $d = 40;
        //if (($a<$c) AND ($b<$d))
        if (($a<$c) && ($b<$d))
        {
            echo "A and B are larger";
        }
        if (isset($d))
            $d = 100;
        echo $d;
        unset($d);
    ?>
    <?php
        $var1 = 2;
        switch($var1)
        {
            case 1:  echo "var1 is 1";
                     break;
            case 2:  echo "var1 is 2";
                     break;
            case 3:  echo "var1 is 3";
                     break;
            default: echo "var1 is unknown";
        }
    ?>
</body>
</html>

jQuery first child of "this"

Use the children function with the :first selector to get the single first child of element:

element.children(":first").toggleClass("redClass");

Get local href value from anchor (a) tag

document.getElementById("link").getAttribute("href"); If you have more than one <a> tag, for example:

_x000D_
_x000D_
<ul>_x000D_
  <li>_x000D_
    <a href="1"></a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="2"></a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="3"></a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

You can do it like this: document.getElementById("link")[0].getAttribute("href"); to access the first array of <a> tags, or depends on the condition you make.

How to download a file from a website in C#

Try this example:

public void TheDownload(string path)
{
  System.IO.FileInfo toDownload = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(path));

  HttpContext.Current.Response.Clear();
  HttpContext.Current.Response.AddHeader("Content-Disposition",
             "attachment; filename=" + toDownload.Name);
  HttpContext.Current.Response.AddHeader("Content-Length",
             toDownload.Length.ToString());
  HttpContext.Current.Response.ContentType = "application/octet-stream";
  HttpContext.Current.Response.WriteFile(patch);
  HttpContext.Current.Response.End();
} 

The implementation is done in the follows:

TheDownload("@"c:\Temporal\Test.txt"");

Source: http://www.systemdeveloper.info/2014/03/force-downloading-file-from-c.html

How to close a window using jQuery

just window.close() is OK, why should write in jQuery?

Request Monitoring in Chrome

I know this is an old thread but I thought I would chime in.

Chrome currently has a solution built in.

  1. Use CTRL+SHIFT+I (or navigate to Current Page Control > Developer > Developer Tools. In the newer versions of Chrome, click the Wrench icon > Tools > Developer Tools.) to enable the Developer Tools.
  2. From within the developer tools click on the Network button. If it isn't already, enable it for the session or always.
  3. Click the "XHR" sub-button.
  4. Initiate an AJAX call.
  5. You will see items begin to show up in the left column under "Resources".
  6. Click the resource and there are 2 tabs showing the headers and return content.

Get GMT Time in Java

Odds are good you did the right stuff on the back end in getting the date, but there's nothing to indicate that you didn't take that GMT time and format it according to your machine's current locale.

final Date currentTime = new Date();

final SimpleDateFormat sdf =
        new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");

// Give it to me in GMT time.
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("GMT time: " + sdf.format(currentTime));

The key is to use your own DateFormat, not the system provided one. That way you can set the DateFormat's timezone to what you wish, instead of it being set to the Locale's timezone.

Select top 10 records for each category

If you know what the sections are, you can do:

select top 10 * from table where section=1
union
select top 10 * from table where section=2
union
select top 10 * from table where section=3

Install IPA with iTunes 11

I always use the iPhone configuration utility for this. Allows much more control and is faster - you don't have to sync the whole device.

SQL Server Convert Varchar to Datetime

SELECT CONVERT(VARCHAR(10), GETDATE(), 105) + ' ' + CONVERT(VARCHAR(10), GETDATE(), 108)

Difference between Big-O and Little-O Notation

f ? O(g) says, essentially

For at least one choice of a constant k > 0, you can find a constant a such that the inequality 0 <= f(x) <= k g(x) holds for all x > a.

Note that O(g) is the set of all functions for which this condition holds.

f ? o(g) says, essentially

For every choice of a constant k > 0, you can find a constant a such that the inequality 0 <= f(x) < k g(x) holds for all x > a.

Once again, note that o(g) is a set.

In Big-O, it is only necessary that you find a particular multiplier k for which the inequality holds beyond some minimum x.

In Little-o, it must be that there is a minimum x after which the inequality holds no matter how small you make k, as long as it is not negative or zero.

These both describe upper bounds, although somewhat counter-intuitively, Little-o is the stronger statement. There is a much larger gap between the growth rates of f and g if f ? o(g) than if f ? O(g).

One illustration of the disparity is this: f ? O(f) is true, but f ? o(f) is false. Therefore, Big-O can be read as "f ? O(g) means that f's asymptotic growth is no faster than g's", whereas "f ? o(g) means that f's asymptotic growth is strictly slower than g's". It's like <= versus <.

More specifically, if the value of g(x) is a constant multiple of the value of f(x), then f ? O(g) is true. This is why you can drop constants when working with big-O notation.

However, for f ? o(g) to be true, then g must include a higher power of x in its formula, and so the relative separation between f(x) and g(x) must actually get larger as x gets larger.

To use purely math examples (rather than referring to algorithms):

The following are true for Big-O, but would not be true if you used little-o:

  • x² ? O(x²)
  • x² ? O(x² + x)
  • x² ? O(200 * x²)

The following are true for little-o:

  • x² ? o(x³)
  • x² ? o(x!)
  • ln(x) ? o(x)

Note that if f ? o(g), this implies f ? O(g). e.g. x² ? o(x³) so it is also true that x² ? O(x³), (again, think of O as <= and o as <)

How to find most common elements of a list?

Is't it just this ....

word_list=['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 
 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 
 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 
 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 
 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 
 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 
 'Moon', 'to', 'rise.', ''] 

from collections import Counter
c = Counter(word_list)
c.most_common(3)

Which should output

[('Jellicle', 6), ('Cats', 5), ('are', 3)]

How to use UIPanGestureRecognizer to move object? iPhone/iPad

UIPanGestureRecognizer * pan1 = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(moveObject:)];
pan1.minimumNumberOfTouches = 1;
[image1 addGestureRecognizer:pan1];

-(void)moveObject:(UIPanGestureRecognizer *)pan;
{
 image1.center = [pan locationInView:image1.superview];
}

nodemon command is not recognized in terminal for node js server

All above options are failed, I got the permanent solution for this. Add below line in package.json under dependencies and run npm install. This will add nodemon package to node_modules and there you go, enjoy the coding.

"nodemon": "^1.17.*"

ipython notebook clear cell output in code

You can use IPython.display.clear_output to clear the output of a cell.

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print("Hello World!")

At the end of this loop you will only see one Hello World!.

Without a code example it's not easy to give you working code. Probably buffering the latest n events is a good strategy. Whenever the buffer changes you can clear the cell's output and print the buffer again.

Write HTML string in JSON

in json everything is string between double quote ", so you need escape " if it happen in value (only in direct writing) use backslash \

and everything in json file wrapped in {} change your json to

_x000D_
_x000D_
{_x000D_
  [_x000D_
    {_x000D_
      "id": "services.html",_x000D_
      "img": "img/SolutionInnerbananer.jpg",_x000D_
      "html": "<h2 class=\"fg-white\">AboutUs</h2><p class=\"fg-white\">developing and supporting complex IT solutions.Touching millions of lives world wide by bringing in innovative technology</p>"_x000D_
    }_x000D_
  ]_x000D_
}
_x000D_
_x000D_
_x000D_

Check whether number is even or odd

I would recommend

Java Puzzlers: Traps, Pitfalls, and Corner Cases Book by Joshua Bloch and Neal Gafter

There is a briefly explanation how to check if number is odd. First try is something similar what @AseemYadav tried:

public static boolean isOdd(int i) {
     return i % 2 == 1;
}

but as was mentioned in book:

when the remainder operation returns a nonzero result, it has the same sign as its left operand

so generally when we have negative odd number then instead of 1 we'll get -1 as result of i%2. So we can use @Camilo solution or just do:

public static boolean isOdd(int i) {
     return i % 2 != 0;
}

but generally the fastest solution is using AND operator like @lucasmo write above:

public static boolean isOdd(int i) {
     return (i & 1) != 0;
}

@Edit It also worth to point Math.floorMod(int x, int y); which deals good with negative the dividend but also can return -1 if the divisor is negative

How to manually set REFERER header in Javascript?

You can change the value of the referrer in the HTTP header using the Web Request API.

It requires a background js script for it's use. You can use the onBeforeSendHeaders as it modifies the header before the request is sent.

Your code will be something like this :

    chrome.webRequest.onBeforeSendHeaders.addEventListener(function(details){
    var newRef = "http://new-referer/path";
    var hasRef = false;
    for(var n in details.requestHeaders){
        hasRef = details.requestHeaders[n].name == "Referer";
        if(hasRef){
            details.requestHeaders[n].value = newRef;
         break;
        }
    }
    if(!hasRef){
        details.requestHeaders.push({name:"Referer",value:newRef});
    }
    return {requestHeaders:details.requestHeaders};
},
{
    urls:["http://target/*"]
},
[
    "requestHeaders",
    "blocking"
]);

urls : It acts as a request filter, and invokes the listener only for certain requests.

For more info: https://developer.chrome.com/extensions/webRequest

How to resolve "git pull,fatal: unable to access 'https://github.com...\': Empty reply from server"

On Windows:

Go to Win -> Control Panel -> Credential Manager -> Windows Credentials

Search for github address and remove it.

enter image description here

Then try to execute:

git push -u origin master

Windows will ask for your git credentials again, put the right ones and that's it.

iCheck check if checkbox is checked

All callbacks and functions are documented here: http://fronteed.com/iCheck/#usage

$('input').iCheck('check'); — change input's state to checked
$('input').iCheck('uncheck'); — remove checked state
$('input').iCheck('toggle'); — toggle checked state
$('input').iCheck('disable'); — change input's state to disabled
$('input').iCheck('enable'); — remove disabled state
$('input').iCheck('indeterminate'); — change input's state to indeterminate
$('input').iCheck('determinate'); — remove indeterminate state
$('input').iCheck('update'); — apply input changes, which were done outside the plugin
$('input').iCheck('destroy'); — remove all traces of iCheck

psql: FATAL: role "postgres" does not exist

The key is "I installed the postgres.app for mac." This application sets up the local PostgreSQL installation with a database superuser whose role name is the same as your login (short) name.

When Postgres.app first starts up, it creates the $USER database, which is the default database for psql when none is specified. The default user is $USER, with no password.

Some scripts (e.g., a database backup created with pgdump on a Linux systsem) and tutorials will assume the superuser has the traditional role name of postgres.

You can make your local install look a bit more traditional and avoid these problems by doing a one time:

/Applications/Postgres.app/Contents/Versions/9.*/bin/createuser -s postgres

which will make those FATAL: role "postgres" does not exist go away.

How to get public directory?

Use public_path()

For reference:

// Path to the project's root folder    
echo base_path();

// Path to the 'app' folder    
echo app_path();        

// Path to the 'public' folder    
echo public_path();

// Path to the 'storage' folder    
echo storage_path();

// Path to the 'storage/app' folder    
echo storage_path('app');

Android WebView not loading an HTTPS URL

To properly handle SSL certificate validation and avoid application rejection from Google according new Security Policy, Change your code to invoke SslErrorHandler.proceed() whenever the certificate presented by the server meets your expectations, and invoke SslErrorHandler.cancel() otherwise.

For example, I add an alert dialog to make user have confirmed and seems Google no longer shows warning.

    @Override
    public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    String message = "SSL Certificate error.";
        switch (error.getPrimaryError()) {
            case SslError.SSL_UNTRUSTED:
                message = "The certificate authority is not trusted.";
                break;
            case SslError.SSL_EXPIRED:
                message = "The certificate has expired.";
                break;
            case SslError.SSL_IDMISMATCH:
                message = "The certificate Hostname mismatch.";
                break;
            case SslError.SSL_NOTYETVALID:
                message = "The certificate is not yet valid.";
                break;
        }
        message += " Do you want to continue anyway?";

        builder.setTitle("SSL Certificate Error");
        builder.setMessage(message);
    builder.setPositiveButton("continue", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            handler.proceed();
        }
    });
    builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            handler.cancel();
        }
    });
    final AlertDialog dialog = builder.create();
    dialog.show();
}

After this changes it will not show warning.

Escape double quotes in parameter

Another way to escape quotes (though probably not preferable), which I've found used in certain places is to use multiple double-quotes. For the purpose of making other people's code legible, I'll explain.

Here's a set of basic rules:

  1. When not wrapped in double-quoted groups, spaces separate parameters:
    program param1 param2 param 3 will pass four parameters to program.exe:
         param1, param2, param, and 3.
  2. A double-quoted group ignores spaces as value separators when passing parameters to programs:
    program one two "three and more" will pass three parameters to program.exe:
         one, two, and three and more.
  3. Now to explain some of the confusion:
  4. Double-quoted groups that appear directly adjacent to text not wrapped with double-quotes join into one parameter:
    hello"to the entire"world acts as one parameter: helloto the entireworld.
  5. Note: The previous rule does NOT imply that two double-quoted groups can appear directly adjacent to one another.
  6. Any double-quote directly following a closing quote is treated as (or as part of) plain unwrapped text that is adjacent to the double-quoted group, but only one double-quote:
    "Tim says, ""Hi!""" will act as one parameter: Tim says, "Hi!"

Thus there are three different types of double-quotes: quotes that open, quotes that close, and quotes that act as plain-text.
Here's the breakdown of that last confusing line:

"   open double-quote group
T   inside ""s
i   inside ""s
m   inside ""s
    inside ""s - space doesn't separate
s   inside ""s
a   inside ""s
y   inside ""s
s   inside ""s
,   inside ""s
    inside ""s - space doesn't separate
"   close double-quoted group
"   quote directly follows closer - acts as plain unwrapped text: "
H   outside ""s - gets joined to previous adjacent group
i   outside ""s - ...
!   outside ""s - ...
"   open double-quote group
"   close double-quote group
"   quote directly follows closer - acts as plain unwrapped text: "

Thus, the text effectively joins four groups of characters (one with nothing, however):
Tim says,  is the first, wrapped to escape the spaces
"Hi! is the second, not wrapped (there are no spaces)
 is the third, a double-quote group wrapping nothing
" is the fourth, the unwrapped close quote.

As you can see, the double-quote group wrapping nothing is still necessary since, without it, the following double-quote would open up a double-quoted group instead of acting as plain-text.

From this, it should be recognizable that therefore, inside and outside quotes, three double-quotes act as a plain-text unescaped double-quote:

"Tim said to him, """What's been happening lately?""""

will print Tim said to him, "What's been happening lately?" as expected. Therefore, three quotes can always be reliably used as an escape.
However, in understanding it, you may note that the four quotes at the end can be reduced to a mere two since it technically is adding another unnecessary empty double-quoted group.

Here are a few examples to close it off:

program a b                       REM sends (a) and (b)
program """a"""                   REM sends ("a")
program """a b"""                 REM sends ("a) and (b")
program """"Hello,""" Mike said." REM sends ("Hello," Mike said.)
program ""a""b""c""d""            REM sends (abcd) since the "" groups wrap nothing
program "hello to """quotes""     REM sends (hello to "quotes")
program """"hello world""         REM sends ("hello world")
program """hello" world""         REM sends ("hello world")
program """hello "world""         REM sends ("hello) and (world")
program "hello ""world"""         REM sends (hello "world")
program "hello """world""         REM sends (hello "world")

Final note: I did not read any of this from any tutorial - I came up with all of it by experimenting. Therefore, my explanation may not be true internally. Nonetheless all the examples above evaluate as given, thus validating (but not proving) my theory.

I tested this on Windows 7, 64bit using only *.exe calls with parameter passing (not *.bat, but I would suppose it works the same).

Yahoo Finance API

Here's a simple scraper I created in c# to get streaming quote data printed out to a console. It should be easily converted to java. Based on the following post:

http://blog.underdog-projects.net/2009/02/bringing-the-yahoo-finance-stream-to-the-shell/

Not too fancy (i.e. no regex etc), just a fast & dirty solution.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;

namespace WebDataAddin
{
    public class YahooConstants
    {
        public const string AskPrice = "a00";
        public const string BidPrice = "b00";
        public const string DayRangeLow = "g00";
        public const string DayRangeHigh = "h00";
        public const string MarketCap = "j10";
        public const string Volume = "v00";
        public const string AskSize = "a50";
        public const string BidSize = "b60";
        public const string EcnBid = "b30";
        public const string EcnBidSize = "o50";
        public const string EcnExtHrBid = "z03";
        public const string EcnExtHrBidSize = "z04";
        public const string EcnAsk = "b20";
        public const string EcnAskSize = "o40";
        public const string EcnExtHrAsk = "z05";
        public const string EcnExtHrAskSize = "z07";
        public const string EcnDayHigh = "h01";
        public const string EcnDayLow = "g01";
        public const string EcnExtHrDayHigh = "h02";
        public const string EcnExtHrDayLow = "g11";
        public const string LastTradeTimeUnixEpochformat = "t10";
        public const string EcnQuoteLastTime = "t50";
        public const string EcnExtHourTime = "t51";
        public const string RtQuoteLastTime = "t53";
        public const string RtExtHourQuoteLastTime = "t54";
        public const string LastTrade = "l10";
        public const string EcnQuoteLastValue = "l90";
        public const string EcnExtHourPrice = "l91";
        public const string RtQuoteLastValue = "l84";
        public const string RtExtHourQuoteLastValue = "l86";
        public const string QuoteChangeAbsolute = "c10";
        public const string EcnQuoteAfterHourChangeAbsolute = "c81";
        public const string EcnQuoteChangeAbsolute = "c60";
        public const string EcnExtHourChange1 = "z02";
        public const string EcnExtHourChange2 = "z08";
        public const string RtQuoteChangeAbsolute = "c63";
        public const string RtExtHourQuoteAfterHourChangeAbsolute = "c85";
        public const string RtExtHourQuoteChangeAbsolute = "c64";
        public const string QuoteChangePercent = "p20";
        public const string EcnQuoteAfterHourChangePercent = "c82";
        public const string EcnQuoteChangePercent = "p40";
        public const string EcnExtHourPercentChange1 = "p41";
        public const string EcnExtHourPercentChange2 = "z09";
        public const string RtQuoteChangePercent = "p43";
        public const string RtExtHourQuoteAfterHourChangePercent = "c86";
        public const string RtExtHourQuoteChangePercent = "p44";

        public static readonly IDictionary<string, string> CodeMap = typeof(YahooConstants).GetFields().
            Where(field => field.FieldType == typeof(string)).
            ToDictionary(field => ((string)field.GetValue(null)).ToUpper(), field => field.Name);
    }

    public static class StringBuilderExtensions
    {
        public static bool HasPrefix(this StringBuilder builder, string prefix)
        {
            return ContainsAtIndex(builder, prefix, 0);
        }

        public static bool HasSuffix(this StringBuilder builder, string suffix)
        {
            return ContainsAtIndex(builder, suffix, builder.Length - suffix.Length);
        }

        private static bool ContainsAtIndex(this StringBuilder builder, string str, int index)
        {
            if (builder != null && !string.IsNullOrEmpty(str) && index >= 0
                && builder.Length >= str.Length + index)
            {
                return !str.Where((t, i) => builder[index + i] != t).Any();
            }
            return false;
        }
    }

    public class WebDataAddin
    {
        public const string ScriptStart = "<script>";
        public const string ScriptEnd = "</script>";

        public const string MessageStart = "try{parent.yfs_";
        public const string MessageEnd = ");}catch(e){}";

        public const string DataMessage = "u1f(";
        public const string InfoMessage = "mktmcb(";


        protected static T ParseJson<T>(string json)
        {
            // parse json - max acceptable value retrieved from 
            //http://forums.asp.net/t/1343461.aspx
            var deserializer = new JavaScriptSerializer { MaxJsonLength = 2147483647 };
            return deserializer.Deserialize<T>(json);
        }

        public static void Main()
        {
            const string symbols = "GBPUSD=X,SPY,MSFT,BAC,QQQ,GOOG";
            // these are constants in the YahooConstants enum above
            const string attrs = "b00,b60,a00,a50";
            const string url = "http://streamerapi.finance.yahoo.com/streamer/1.0?s={0}&k={1}&r=0&callback=parent.yfs_u1f&mktmcb=parent.yfs_mktmcb&gencallback=parent.yfs_gencb&region=US&lang=en-US&localize=0&mu=1";

            var req = WebRequest.Create(string.Format(url, symbols, attrs));
            req.Proxy.Credentials = CredentialCache.DefaultCredentials;
            var missingCodes = new HashSet<string>();
            var response = req.GetResponse();
            if(response != null)
            {
                var stream = response.GetResponseStream();
                if (stream != null)
                {
                    using (var reader = new StreamReader(stream))
                    {
                        var builder = new StringBuilder();
                        var initialPayloadReceived = false;
                        while (!reader.EndOfStream)
                        {
                            var c = (char)reader.Read();
                            builder.Append(c);
                            if(!initialPayloadReceived)
                            {
                                if (builder.HasSuffix(ScriptStart))
                                {
                                    // chop off the first part, and re-append the
                                    // script tag (this is all we care about)
                                    builder.Clear();
                                    builder.Append(ScriptStart);
                                    initialPayloadReceived = true;
                                }
                            }
                            else
                            {
                                // check if we have a fully formed message
                                // (check suffix first to avoid re-checking 
                                // the prefix over and over)
                                if (builder.HasSuffix(ScriptEnd) &&
                                    builder.HasPrefix(ScriptStart))
                                {
                                    var chop = ScriptStart.Length + MessageStart.Length;
                                    var javascript = builder.ToString(chop,
                                        builder.Length - ScriptEnd.Length - MessageEnd.Length - chop);

                                    if (javascript.StartsWith(DataMessage))
                                    {
                                        var json = ParseJson<Dictionary<string, object>>(
                                            javascript.Substring(DataMessage.Length));

                                        // parse out the data. key should be the symbol

                                        foreach(var symbol in json)
                                        {
                                            Console.WriteLine("Symbol: {0}", symbol.Key);
                                            var symbolData = (Dictionary<string, object>) symbol.Value;
                                            foreach(var dataAttr in symbolData)
                                            {
                                                var codeKey = dataAttr.Key.ToUpper();
                                                if (YahooConstants.CodeMap.ContainsKey(codeKey))
                                                {
                                                    Console.WriteLine("\t{0}: {1}", YahooConstants.
                                                        CodeMap[codeKey], dataAttr.Value);
                                                } else
                                                {
                                                    missingCodes.Add(codeKey);
                                                    Console.WriteLine("\t{0}: {1} (Warning! No Code Mapping Found)", 
                                                        codeKey, dataAttr.Value);
                                                }
                                            }
                                            Console.WriteLine();
                                        }

                                    } else if(javascript.StartsWith(InfoMessage))
                                    {
                                        var json = ParseJson<Dictionary<string, object>>(
                                            javascript.Substring(InfoMessage.Length));

                                        foreach (var dataAttr in json)
                                        {
                                            Console.WriteLine("\t{0}: {1}", dataAttr.Key, dataAttr.Value);
                                        }
                                        Console.WriteLine();
                                    } else
                                    {
                                        throw new Exception("Cannot recognize the message type");
                                    }
                                    builder.Clear();
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

How to add many functions in ONE ng-click?

ng-click "$watch(edit($index), open())"

How should I validate an e-mail address?

Can I STRONGLY recommend you don't try to 'validate' email addresses, you'll just get yourself into a lot of work for no good reason.

Just make sure what is entered won't break your own code - e.g. no spaces or illegal characters which might cause an Exception.

Anything else will just cause you a lot of work for minimal return...

How does facebook, gmail send the real time notification?

Update

As I continue to recieve upvotes on this, I think it is reasonable to remember that this answer is 4 years old. Web has grown in a really fast pace, so please be mindful about this answer.


I had the same issue recently and researched about the subject.

The solution given is called long polling, and to correctly use it you must be sure that your AJAX request has a "large" timeout and to always make this request after the current ends (timeout, error or success).

Long Polling - Client

Here, to keep code short, I will use jQuery:

function pollTask() { 

    $.ajax({

        url: '/api/Polling',
        async: true,            // by default, it's async, but...
        dataType: 'json',       // or the dataType you are working with
        timeout: 10000,          // IMPORTANT! this is a 10 seconds timeout
        cache: false

    }).done(function (eventList) {  

       // Handle your data here
       var data;
       for (var eventName in eventList) {

            data = eventList[eventName];
            dispatcher.handle(eventName, data); // handle the `eventName` with `data`

       }

    }).always(pollTask);

}

It is important to remember that (from jQuery docs):

In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.

Long Polling - Server

It is not in any specific language, but it would be something like this:

function handleRequest () {  

     while (!anythingHappened() || hasTimedOut()) { sleep(2); }

     return events();

} 

Here, hasTimedOut will make sure your code does not wait forever, and anythingHappened, will check if any event happend. The sleep is for releasing your thread to do other stuff while nothing happens. The events will return a dictionary of events (or any other data structure you may prefer) in JSON format (or any other you prefer).

It surely solves the problem, but, if you are concerned about scalability and perfomance as I was when researching, you might consider another solution I found.

Solution

Use sockets!

On client side, to avoid any compatibility issues, use socket.io. It tries to use socket directly, and have fallbacks to other solutions when sockets are not available.

On server side, create a server using NodeJS (example here). The client will subscribe to this channel (observer) created with the server. Whenever a notification has to be sent, it is published in this channel and the subscriptor (client) gets notified.

If you don't like this solution, try APE (Ajax Push Engine).

Hope I helped.