Programs & Examples On #Qstandarditemmodel

The QStandardItemModel class provides a generic model for storing custom data.

Convert JSON String To C# Object

Here's a simple class I cobbled together from various posts.... It's been tested for about 15 minutes, but seems to work for my purposes. It uses JavascriptSerializer to do the work, which can be referenced in your app using the info detailed in this post.

The below code can be run in LinqPad to test it out by:

  • Right clicking on your script tab in LinqPad, and choosing "Query Properties"
  • Referencing the "System.Web.Extensions.dll" in "Additional References"
  • Adding an "Additional Namespace Imports" of "System.Web.Script.Serialization".

Hope it helps!

void Main()
{
  string json = @"
  {
    'glossary': 
    {
      'title': 'example glossary',
        'GlossDiv': 
        {
          'title': 'S',
          'GlossList': 
          {
            'GlossEntry': 
            {
              'ID': 'SGML',
              'ItemNumber': 2,          
              'SortAs': 'SGML',
              'GlossTerm': 'Standard Generalized Markup Language',
              'Acronym': 'SGML',
              'Abbrev': 'ISO 8879:1986',
              'GlossDef': 
              {
                'para': 'A meta-markup language, used to create markup languages such as DocBook.',
                'GlossSeeAlso': ['GML', 'XML']
              },
              'GlossSee': 'markup'
            }
          }
        }
    }
  }

  ";

  var d = new JsonDeserializer(json);
  d.GetString("glossary.title").Dump();
  d.GetString("glossary.GlossDiv.title").Dump();  
  d.GetString("glossary.GlossDiv.GlossList.GlossEntry.ID").Dump();  
  d.GetInt("glossary.GlossDiv.GlossList.GlossEntry.ItemNumber").Dump();    
  d.GetObject("glossary.GlossDiv.GlossList.GlossEntry.GlossDef").Dump();   
  d.GetObject("glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso").Dump(); 
  d.GetObject("Some Path That Doesnt Exist.Or.Another").Dump();   
}


// Define other methods and classes here

public class JsonDeserializer
{
  private IDictionary<string, object> jsonData { get; set; }

  public JsonDeserializer(string json)
  {
    var json_serializer = new JavaScriptSerializer();

    jsonData = (IDictionary<string, object>)json_serializer.DeserializeObject(json);
  }

  public string GetString(string path)
  {
    return (string) GetObject(path);
  }

  public int? GetInt(string path)
  {
    int? result = null;

    object o = GetObject(path);
    if (o == null)
    {
      return result;
    }

    if (o is string)
    {
      result = Int32.Parse((string)o);
    }
    else
    {
      result = (Int32) o;
    }

    return result;
  }

  public object GetObject(string path)
  {
    object result = null;

    var curr = jsonData;
    var paths = path.Split('.');
    var pathCount = paths.Count();

    try
    {
      for (int i = 0; i < pathCount; i++)
      {
        var key = paths[i];
        if (i == (pathCount - 1))
        {
          result = curr[key];
        }
        else
        {
          curr = (IDictionary<string, object>)curr[key];
        }
      }
    }
    catch
    {
      // Probably means an invalid path (ie object doesn't exist)
    }

    return result;
  }
}

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

For me it was important to delete the "php.executablePath" path from the VS code settings and leave only the path to PHP in the Path variable.

When I had the Path variable together with php.executablePath, an irritating error still occurred (despite the fact that the path to php was correct).

Finding three elements in an array whose sum is closest to a given number

Very simple N^2*logN solution: sort the input array, then go through all pairs Ai, Aj (N^2 time), and for each pair check whether (S - Ai - Aj) is in array (logN time).

Another O(S*N) solution uses classical dynamic programming approach.

In short:

Create an 2-d array V[4][S + 1]. Fill it in such a way, that:

V[0][0] = 1, V[0][x] = 0;

V1[Ai]= 1 for any i, V1[x] = 0 for all other x

V[2][Ai + Aj]= 1, for any i, j. V[2][x] = 0 for all other x

V[3][sum of any 3 elements] = 1.

To fill it, iterate through Ai, for each Ai iterate through the array from right to left.

data.map is not a function

The SIMPLEST answer is to put "data" into a pair of square brackets (i.e. [data]):

     $.getJSON("json/products.json").done(function (data) {

         var allProducts = [data].map(function (item) {
             return new getData(item);
         });

     });

Here, [data] is an array, and the ".map" method can be used on it. It works for me! enter image description here

Getting or changing CSS class property with Javascript using DOM style

I think this is not the best way, but in my cases other methods did not work.

stylesheet = document.styleSheets[0]
stylesheet.insertRule(".have-border { border: 1px solid black;}", 0);

Example from https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript

How to sum data.frame column values?

You can just use sum(people$Weight).

sum sums up a vector, and people$Weight retrieves the weight column from your data frame.

Note - you can get built-in help by using ?sum, ?colSums, etc. (by the way, colSums will give you the sum for each column).

What's the difference between a temp table and table variable in SQL Server?

It surprises me that no one mentioned the key difference between these two is that the temp table supports parallel insert while the table variable doesn't. You should be able to see the difference from the execution plan. And here is the video from SQL Workshops on Channel 9.

This also explains why you should use a table variable for smaller tables, otherwise use a temp table, as SQLMenace answered before.

scale Image in an UIButton to AspectFit?

The cleanest solution is to use Auto Layout. I lowered Content Compression Resistance Priority of my UIButton and set the image (not Background Image) via Interface Builder. After that I added a couple of constraints that define size of my button (quite complex in my case) and it worked like a charm.

Should try...catch go inside or outside a loop?

I's like to add my own 0.02c about two competing considerations when looking at the general problem of where to position exception handling:

  1. The "wider" the responsibility of the try-catch block (i.e. outside the loop in your case) means that when changing the code at some later point, you may mistakenly add a line which is handled by your existing catch block; possibly unintentionally. In your case, this is less likely because you are explicitly catching a NumberFormatException

  2. The "narrower" the responsibility of the try-catch block, the more difficult refactoring becomes. Particularly when (as in your case) you are executing a "non-local" instruction from within the catch block (the return null statement).

Graph implementation C++

This question is ancient but for some reason I can't seem to get it out of my mind.

While all of the solutions do provide an implementation of graphs, they are also all very verbose. They are simply not elegant.

Instead of inventing your own graph class all you really need is a way to tell that one point is connected to another -- for that, std::map and std::unordered_map work perfectly fine. Simply, define a graph as a map between nodes and lists of edges. If you don't need extra data on the edge, a list of end nodes will do just fine.

Thus a succinct graph in C++, could be implemented like so:

using graph = std::map<int, std::vector<int>>;

Or, if you need additional data,

struct edge {
    int nodes[2];
    float cost; // add more if you need it
};

using graph = std::map<int, std::vector<edge>>;

Now your graph structure will plug nicely into the rest of the language and you don't have to remember any new clunky interface -- the old clunky interface will do just fine.

No benchmarks, but I have a feeling this will also outperform the other suggestions here.

NB: the ints are not indices -- they are identifiers.

Can I start the iPhone simulator without "Build and Run"?

This is an older question, but if you simply want to run the simulator from the Xcode 4.5 UI, you can do: Xcode > Open Developer Tool > iOS Simulator.

Grep for beginning and end of line?

The tricky part is a regex that includes a dash as one of the valid characters in a character class. The dash has to come immediately after the start for a (normal) character class and immediately after the caret for a negated character class. If you need a close square bracket too, then you need the close square bracket followed by the dash. Mercifully, you only need dash, hence the notation chosen.

grep '^[-d]rwx.*[0-9]$' "$@"

See: Regular Expressions and grep for POSIX-standard details.

Can not connect to local PostgreSQL

I tried most of the solutions to this problem but couldn't get any to work.

I ran lsof -P | grep ':5432' | awk '{print $2}' which showed the PID of the process running. However I couldn't kill it with kill -9 <pid>.

When I ran pkill postgresql the process finally stopped. Hope this helps.

Add a background image to shape in XML Android

I used the following for a drawable image with a circular background.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/colorAccent"/>
        </shape>
    </item>
    <item
        android:drawable="@drawable/ic_select"
        android:bottom="20dp"
        android:left="20dp"
        android:right="20dp"
        android:top="20dp"/>
</layer-list>

Here is what it looks like

enter image description here

Hope that helps someone out.

First char to upper case

Comilation error is due arguments are not properly provided, replaceFirst accepts regx as initial arg. [a-z]{1} will match string of simple alpha characters of length 1.

Try this.

betterIdea = userIdea.replaceFirst("[a-z]{1}", userIdea.substring(0,1).toUpperCase())

How do you determine the ideal buffer size when using FileInputStream?

You could use the BufferedStreams/readers and then use their buffer sizes.

I believe the BufferedXStreams are using 8192 as the buffer size, but like Ovidiu said, you should probably run a test on a whole bunch of options. Its really going to depend on the filesystem and disk configurations as to what the best sizes are.

python pip - install from local dir

All you need to do is run

pip install /opt/mypackage

and pip will search /opt/mypackage for a setup.py, build a wheel, then install it.

The problem with using the -e flag for pip install as suggested in the comments and this answer is that this requires that the original source directory stay in place for as long as you want to use the module. It's great if you're a developer working on the source, but if you're just trying to install a package, it's the wrong choice.

Alternatively, you don't even need to download the repo from Github at all. pip supports installing directly from git repos using a variety of protocols including HTTP, HTTPS, and SSH, among others. See the docs I linked to for examples.

Inner text shadow with CSS

More precise explanation of the CSS in kendo451's answer.

There's another way to get a fancy-hacky inner shadow illusion,
which I'll explain in three simple steps. Say we have this HTML:

<h1>Get this</h1>

and this CSS:

h1 {
  color: black;
  background-color: #cc8100;
}

It's a good slogan

Step 1

Let's start by making the text transparent:

h1 {
  color: transparent;
  background-color: #cc8100;
}

It's a box

Step 2

Now, we crop that background to the shape of the text:

h1 {
  color: transparent;
  background-color: #cc8100;
  background-clip: text;
}

The background is the text!

Step 3

Now, the magic: we'll put a blurred text-shadow, which will be in front of the background, thus giving the impression of an inner shadow!

h1 {
  color: transparent;
  background-color: #cc8100;
  background-clip: text;
  text-shadow: 0px 2px 5px #f9c800;
}

We got it! Yay!

See the final result.

Downsides?

  • Only works in Webkit (background-clip can't be text).
  • Multiple shadows? Don't even think.
  • You get an outer glow too.

How to customize listview using baseadapter

public class ListElementAdapter extends BaseAdapter{

    String[] data;
    Context context;
    LayoutInflater layoutInflater;


    public ListElementAdapter(String[] data, Context context) {
        super();
        this.data = data;
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {

        return data.length;
    }

    @Override
    public Object getItem(int position) {

        return null;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        convertView= layoutInflater.inflate(R.layout.item, null);

        TextView txt=(TextView)convertView.findViewById(R.id.text);

        txt.setText(data[position]);



        return convertView;
    }
}

Just call ListElementAdapter in your Main Activity and set Adapter to ListView.

Handling optional parameters in javascript

Can you override the function? Will this not work:

function doSomething(id){}
function doSomething(id,parameters){}
function doSomething(id,parameters,callback){}

How do I calculate a point on a circle’s circumference?

Calculating point around circumference of circle given distance travelled.
For comparison... This may be useful in Game AI when moving around a solid object in a direct path.

enter image description here

public static Point DestinationCoordinatesArc(Int32 startingPointX, Int32 startingPointY,
    Int32 circleOriginX, Int32 circleOriginY, float distanceToMove,
    ClockDirection clockDirection, float radius)
{
    // Note: distanceToMove and radius parameters are float type to avoid integer division
    // which will discard remainder

    var theta = (distanceToMove / radius) * (clockDirection == ClockDirection.Clockwise ? 1 : -1);
    var destinationX = circleOriginX + (startingPointX - circleOriginX) * Math.Cos(theta) - (startingPointY - circleOriginY) * Math.Sin(theta);
    var destinationY = circleOriginY + (startingPointX - circleOriginX) * Math.Sin(theta) + (startingPointY - circleOriginY) * Math.Cos(theta);

    // Round to avoid integer conversion truncation
    return new Point((Int32)Math.Round(destinationX), (Int32)Math.Round(destinationY));
}

/// <summary>
/// Possible clock directions.
/// </summary>
public enum ClockDirection
{
    [Description("Time moving forwards.")]
    Clockwise,
    [Description("Time moving moving backwards.")]
    CounterClockwise
}

private void ButtonArcDemo_Click(object sender, EventArgs e)
{
    Brush aBrush = (Brush)Brushes.Black;
    Graphics g = this.CreateGraphics();

    var startingPointX = 125;
    var startingPointY = 75;
    for (var count = 0; count < 62; count++)
    {
        var point = DestinationCoordinatesArc(
            startingPointX: startingPointX, startingPointY: startingPointY,
            circleOriginX: 75, circleOriginY: 75,
            distanceToMove: 5,
            clockDirection: ClockDirection.Clockwise, radius: 50);
        g.FillRectangle(aBrush, point.X, point.Y, 1, 1);

        startingPointX = point.X;
        startingPointY = point.Y;

        // Pause to visually observe/confirm clock direction
        System.Threading.Thread.Sleep(35);

        Debug.WriteLine($"DestinationCoordinatesArc({point.X}, {point.Y}");
    }
}

How to create an Explorer-like folder browser control?

Take a look at Shell MegaPack control set. It provides Windows Explorer like folder/file browsing with most of the features and functionality like context menus, renaming, drag-drop, icons, overlay icons, thumbnails, etc

Change Default branch in gitlab

In Gitlab version v11.4.4-ee, you can:

  1. Setting
  2. Repository
  3. Default Branch

Click me

javascript date to string

Relying on JQuery Datepicker, but it could be done easily:

var mydate = new Date();
$.datepicker.formatDate('yy-mm-dd', mydate);

Changing Locale within the app itself

After a good night of sleep, I found the answer on the Web (a simple Google search on the following line "getBaseContext().getResources().updateConfiguration(mConfig, getBaseContext().getResources().getDisplayMetrics());"), here it is :

link text => this link also shows screenshots of what is happening !

Density was the issue here, I needed to have this in the AndroidManifest.xml

<supports-screens
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="true"
/>

The most important is the android:anyDensity =" true ".

Don't forget to add the following in the AndroidManifest.xml for every activity (for Android 4.1 and below):

android:configChanges="locale"

This version is needed when you build for Android 4.2 (API level 17) explanation here:

android:configChanges="locale|layoutDirection"

Use a content script to access the page context variables and functions

I've also faced the problem of ordering of loaded scripts, which was solved through sequential loading of scripts. The loading is based on Rob W's answer.

function scriptFromFile(file) {
    var script = document.createElement("script");
    script.src = chrome.extension.getURL(file);
    return script;
}

function scriptFromSource(source) {
    var script = document.createElement("script");
    script.textContent = source;
    return script;
}

function inject(scripts) {
    if (scripts.length === 0)
        return;
    var otherScripts = scripts.slice(1);
    var script = scripts[0];
    var onload = function() {
        script.parentNode.removeChild(script);
        inject(otherScripts);
    };
    if (script.src != "") {
        script.onload = onload;
        document.head.appendChild(script);
    } else {
        document.head.appendChild(script);
        onload();
    }
}

The example of usage would be:

var formulaImageUrl = chrome.extension.getURL("formula.png");
var codeImageUrl = chrome.extension.getURL("code.png");

inject([
    scriptFromSource("var formulaImageUrl = '" + formulaImageUrl + "';"),
    scriptFromSource("var codeImageUrl = '" + codeImageUrl + "';"),
    scriptFromFile("EqEditor/eq_editor-lite-17.js"),
    scriptFromFile("EqEditor/eq_config.js"),
    scriptFromFile("highlight/highlight.pack.js"),
    scriptFromFile("injected.js")
]);

Actually, I'm kinda new to JS, so feel free to ping me to the better ways.

Android ListView selected item stay highlighted

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            for (int j = 0; j < adapterView.getChildCount(); j++)
                adapterView.getChildAt(j).setBackgroundColor(Color.TRANSPARENT);

            // change the background color of the selected element
            view.setBackgroundColor(Color.LTGRAY);
});

Perhaps you might want to save the current selected element in a global variable using the index i.

Arrays in cookies PHP

To store the array values in cookie, first you need to convert them to string, so here is some options.

Storing cookies as JSON

Storing code

setcookie('your_cookie_name', json_encode($info), time()+3600);

Reading code

$data = json_decode($_COOKIE['your_cookie_name'], true);

JSON can be good choose also if you need read cookie in front end with JavaScript.

Actually you can use any encrypt_array_to_string/decrypt_array_from_string methods group that will convert array to string and convert string back to same array. For example you can also use explode/implode for array of integers.

Warning: Do not use serialize/unserialize

From PHP.net

enter image description here

Do not pass untrusted user input to unserialize(). - Anything that coming by HTTP including cookies is untrusted!

References related to security

As an alternative solution, you can do it also without converting array to string.

setcookie('my_array[0]', 'value1' , time()+3600);
setcookie('my_array[1]', 'value2' , time()+3600);
setcookie('my_array[2]', 'value3' , time()+3600);

And after if you will print $_COOKIE variable, you will see the following

echo '<pre>';
print_r( $_COOKIE );
die();
Array
(   
    [my_array] => Array
        (
            [0] => value1
            [1] => value2
            [2] => value3
        )

)

This is documented PHP feature.

From PHP.net

Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system.

What does "dereferencing" a pointer mean?

Reviewing the basic terminology

It's usually good enough - unless you're programming assembly - to envisage a pointer containing a numeric memory address, with 1 referring to the second byte in the process's memory, 2 the third, 3 the fourth and so on....

  • What happened to 0 and the first byte? Well, we'll get to that later - see null pointers below.
  • For a more accurate definition of what pointers store, and how memory and addresses relate, see "More about memory addresses, and why you probably don't need to know" at the end of this answer.

When you want to access the data/value in the memory that the pointer points to - the contents of the address with that numerical index - then you dereference the pointer.

Different computer languages have different notations to tell the compiler or interpreter that you're now interested in the pointed-to object's (current) value - I focus below on C and C++.

A pointer scenario

Consider in C, given a pointer such as p below...

const char* p = "abc";

...four bytes with the numerical values used to encode the letters 'a', 'b', 'c', and a 0 byte to denote the end of the textual data, are stored somewhere in memory and the numerical address of that data is stored in p. This way C encodes text in memory is known as ASCIIZ.

For example, if the string literal happened to be at address 0x1000 and p a 32-bit pointer at 0x2000, the memory content would be:

Memory Address (hex)    Variable name    Contents
1000                                     'a' == 97 (ASCII)
1001                                     'b' == 98
1002                                     'c' == 99
1003                                     0
...
2000-2003               p                1000 hex

Note that there is no variable name/identifier for address 0x1000, but we can indirectly refer to the string literal using a pointer storing its address: p.

Dereferencing the pointer

To refer to the characters p points to, we dereference p using one of these notations (again, for C):

assert(*p == 'a');  // The first character at address p will be 'a'
assert(p[1] == 'b'); // p[1] actually dereferences a pointer created by adding
                     // p and 1 times the size of the things to which p points:
                     // In this case they're char which are 1 byte in C...
assert(*(p + 1) == 'b');  // Another notation for p[1]

You can also move pointers through the pointed-to data, dereferencing them as you go:

++p;  // Increment p so it's now 0x1001
assert(*p == 'b');  // p == 0x1001 which is where the 'b' is...

If you have some data that can be written to, then you can do things like this:

int x = 2;
int* p_x = &x;  // Put the address of the x variable into the pointer p_x
*p_x = 4;       // Change the memory at the address in p_x to be 4
assert(x == 4); // Check x is now 4

Above, you must have known at compile time that you would need a variable called x, and the code asks the compiler to arrange where it should be stored, ensuring the address will be available via &x.

Dereferencing and accessing a structure data member

In C, if you have a variable that is a pointer to a structure with data members, you can access those members using the -> dereferencing operator:

typedef struct X { int i_; double d_; } X;
X x;
X* p = &x;
p->d_ = 3.14159;  // Dereference and access data member x.d_
(*p).d_ *= -1;    // Another equivalent notation for accessing x.d_

Multi-byte data types

To use a pointer, a computer program also needs some insight into the type of data that is being pointed at - if that data type needs more than one byte to represent, then the pointer normally points to the lowest-numbered byte in the data.

So, looking at a slightly more complex example:

double sizes[] = { 10.3, 13.4, 11.2, 19.4 };
double* p = sizes;
assert(p[0] == 10.3);  // Knows to look at all the bytes in the first double value
assert(p[1] == 13.4);  // Actually looks at bytes from address p + 1 * sizeof(double)
                       // (sizeof(double) is almost always eight bytes)
++p;                   // Advance p by sizeof(double)
assert(*p == 13.4);    // The double at memory beginning at address p has value 13.4
*(p + 2) = 29.8;       // Change sizes[3] from 19.4 to 29.8
                       // Note earlier ++p and + 2 here => sizes[3]

Pointers to dynamically allocated memory

Sometimes you don't know how much memory you'll need until your program is running and sees what data is thrown at it... then you can dynamically allocate memory using malloc. It is common practice to store the address in a pointer...

int* p = (int*)malloc(sizeof(int)); // Get some memory somewhere...
*p = 10;            // Dereference the pointer to the memory, then write a value in
fn(*p);             // Call a function, passing it the value at address p
(*p) += 3;          // Change the value, adding 3 to it
free(p);            // Release the memory back to the heap allocation library

In C++, memory allocation is normally done with the new operator, and deallocation with delete:

int* p = new int(10); // Memory for one int with initial value 10
delete p;

p = new int[10];      // Memory for ten ints with unspecified initial value
delete[] p;

p = new int[10]();    // Memory for ten ints that are value initialised (to 0)
delete[] p;

See also C++ smart pointers below.

Losing and leaking addresses

Often a pointer may be the only indication of where some data or buffer exists in memory. If ongoing use of that data/buffer is needed, or the ability to call free() or delete to avoid leaking the memory, then the programmer must operate on a copy of the pointer...

const char* p = asprintf("name: %s", name);  // Common but non-Standard printf-on-heap

// Replace non-printable characters with underscores....
for (const char* q = p; *q; ++q)
    if (!isprint(*q))
        *q = '_';

printf("%s\n", p); // Only q was modified
free(p);

...or carefully orchestrate reversal of any changes...

const size_t n = ...;
p += n;
...
p -= n;  // Restore earlier value...
free(p);

C++ smart pointers

In C++, it's best practice to use smart pointer objects to store and manage the pointers, automatically deallocating them when the smart pointers' destructors run. Since C++11 the Standard Library provides two, unique_ptr for when there's a single owner for an allocated object...

{
    std::unique_ptr<T> p{new T(42, "meaning")};
    call_a_function(p);
    // The function above might throw, so delete here is unreliable, but...
} // p's destructor's guaranteed to run "here", calling delete

...and shared_ptr for share ownership (using reference counting)...

{
    auto p = std::make_shared<T>(3.14, "pi");
    number_storage1.may_add(p); // Might copy p into its container
    number_storage2.may_add(p); // Might copy p into its container    } // p's destructor will only delete the T if neither may_add copied it

Null pointers

In C, NULL and 0 - and additionally in C++ nullptr - can be used to indicate that a pointer doesn't currently hold the memory address of a variable, and shouldn't be dereferenced or used in pointer arithmetic. For example:

const char* p_filename = NULL; // Or "= 0", or "= nullptr" in C++
int c;
while ((c = getopt(argc, argv, "f:")) != -1)
    switch (c) {
      case f: p_filename = optarg; break;
    }
if (p_filename)  // Only NULL converts to false
    ...   // Only get here if -f flag specified

In C and C++, just as inbuilt numeric types don't necessarily default to 0, nor bools to false, pointers are not always set to NULL. All these are set to 0/false/NULL when they're static variables or (C++ only) direct or indirect member variables of static objects or their bases, or undergo zero initialisation (e.g. new T(); and new T(x, y, z); perform zero-initialisation on T's members including pointers, whereas new T; does not).

Further, when you assign 0, NULL and nullptr to a pointer the bits in the pointer are not necessarily all reset: the pointer may not contain "0" at the hardware level, or refer to address 0 in your virtual address space. The compiler is allowed to store something else there if it has reason to, but whatever it does - if you come along and compare the pointer to 0, NULL, nullptr or another pointer that was assigned any of those, the comparison must work as expected. So, below the source code at the compiler level, "NULL" is potentially a bit "magical" in the C and C++ languages...

More about memory addresses, and why you probably don't need to know

More strictly, initialised pointers store a bit-pattern identifying either NULL or a (often virtual) memory address.

The simple case is where this is a numeric offset into the process's entire virtual address space; in more complex cases the pointer may be relative to some specific memory area, which the CPU may select based on CPU "segment" registers or some manner of segment id encoded in the bit-pattern, and/or looking in different places depending on the machine code instructions using the address.

For example, an int* properly initialised to point to an int variable might - after casting to a float* - access memory in "GPU" memory quite distinct from the memory where the int variable is, then once cast to and used as a function pointer it might point into further distinct memory holding machine opcodes for the program (with the numeric value of the int* effectively a random, invalid pointer within these other memory regions).

3GL programming languages like C and C++ tend to hide this complexity, such that:

  • If the compiler gives you a pointer to a variable or function, you can dereference it freely (as long as the variable's not destructed/deallocated meanwhile) and it's the compiler's problem whether e.g. a particular CPU segment register needs to be restored beforehand, or a distinct machine code instruction used

  • If you get a pointer to an element in an array, you can use pointer arithmetic to move anywhere else in the array, or even to form an address one-past-the-end of the array that's legal to compare with other pointers to elements in the array (or that have similarly been moved by pointer arithmetic to the same one-past-the-end value); again in C and C++, it's up to the compiler to ensure this "just works"

  • Specific OS functions, e.g. shared memory mapping, may give you pointers, and they'll "just work" within the range of addresses that makes sense for them

  • Attempts to move legal pointers beyond these boundaries, or to cast arbitrary numbers to pointers, or use pointers cast to unrelated types, typically have undefined behaviour, so should be avoided in higher level libraries and applications, but code for OSes, device drivers, etc. may need to rely on behaviour left undefined by the C or C++ Standard, that is nevertheless well defined by their specific implementation or hardware.

"The operation is not valid for the state of the transaction" error and transaction scope

When I encountered this exception, there was an InnerException "Transaction Timeout". Since this was during a debug session, when I halted my code for some time inside the TransactionScope, I chose to ignore this issue.

When this specific exception with a timeout appears in deployed code, I think that the following section in you .config file will help you out:

<system.transactions> 
        <machineSettings maxTimeout="00:05:00" /> 
</system.transactions>

python location on mac osx

which python3 simply result in a path in which the interpreter settles down.

File content into unix variable with newlines

The envdir utility provides an easy way to do this. envdir uses files to represent environment variables, with file names mapping to env var names, and file contents mapping to env var values. If the file contents contain newlines, so will the env var.

See https://pypi.python.org/pypi/envdir

How to import a module given the full path?

Here is some code that works in all Python versions, from 2.7-3.5 and probably even others.

config_file = "/tmp/config.py"
with open(config_file) as f:
    code = compile(f.read(), config_file, 'exec')
    exec(code, globals(), locals())

I tested it. It may be ugly but so far is the only one that works in all versions.

How to POST request using RestSharp

As of 2017 I post to a rest service and getting the results from it like that:

        var loginModel = new LoginModel();
        loginModel.DatabaseName = "TestDB";
        loginModel.UserGroupCode = "G1";
        loginModel.UserName = "test1";
        loginModel.Password = "123";

        var client = new RestClient(BaseUrl);

        var request = new RestRequest("/Connect?", Method.POST);
        request.RequestFormat = DataFormat.Json;
        request.AddBody(loginModel);

        var response = client.Execute(request);

        var obj = JObject.Parse(response.Content);

        LoginResult result = new LoginResult
        {
            Status = obj["Status"].ToString(),
            Authority = response.ResponseUri.Authority,
            SessionID = obj["SessionID"].ToString()
        };

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

How do I get extra data from intent on Android?

This is for adapter , for activity you just need to change mContext to your Activty name and for fragment you need to change mContext to getActivity()

 public static ArrayList<String> tags_array ;// static array list if you want to pass array data

      public void sendDataBundle(){
            tags_array = new ArrayList();
            tags_array.add("hashtag");//few array data
            tags_array.add("selling");
            tags_array.add("cityname");
            tags_array.add("more");
            tags_array.add("mobile");
            tags_array.add("android");
            tags_array.add("dress");
            Intent su = new Intent(mContext, ViewItemActivity.class);
            Bundle bun1 = new Bundle();
            bun1.putString("product_title","My Product Titile");
            bun1.putString("product_description", "My Product Discription");
            bun1.putString("category", "Product Category");
            bun1.putStringArrayList("hashtag", tags_array);//to pass array list 
            su.putExtras(bun1);
            mContext.startActivity(su);
        }

Character reading from file in Python

Ref: http://docs.python.org/howto/unicode

Reading Unicode from a file is therefore simple:

import codecs
with codecs.open('unicode.rst', encoding='utf-8') as f:
    for line in f:
        print repr(line)

It's also possible to open files in update mode, allowing both reading and writing:

with codecs.open('test', encoding='utf-8', mode='w+') as f:
    f.write(u'\u4500 blah blah blah\n')
    f.seek(0)
    print repr(f.readline()[:1])

EDIT: I'm assuming that your intended goal is just to be able to read the file properly into a string in Python. If you're trying to convert to an ASCII string from Unicode, then there's really no direct way to do so, since the Unicode characters won't necessarily exist in ASCII.

If you're trying to convert to an ASCII string, try one of the following:

  1. Replace the specific unicode chars with ASCII equivalents, if you are only looking to handle a few special cases such as this particular example

  2. Use the unicodedata module's normalize() and the string.encode() method to convert as best you can to the next closest ASCII equivalent (Ref https://web.archive.org/web/20090228203858/http://techxplorer.com/2006/07/18/converting-unicode-to-ascii-using-python):

    >>> teststr
    u'I don\xe2\x80\x98t like this'
    >>> unicodedata.normalize('NFKD', teststr).encode('ascii', 'ignore')
    'I donat like this'
    

Detect if a jQuery UI dialog box is open

If you read the docs.

$('#mydialog').dialog('isOpen')

This method returns a Boolean (true or false), not a jQuery object.

SQL Query To Obtain Value that Occurs more than once

From Oracle (but works in most SQL DBs):

SELECT LASTNAME, COUNT(*)
FROM STUDENTS
GROUP BY LASTNAME
HAVING COUNT(*) >= 3

P.S. it's faster one, because you have no Select withing Select methods here

Content Security Policy: The page's settings blocked the loading of a resource

You have said you can only load scripts from your own site (self). You have then tried to load a script from another site (www.google.com) and, because you've restricted this, you can't. That's the whole point of Content Security Policy (CSP).

You can change your first line to:

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' http://www.google.com">

Or, alternatively, it may be worth removing that line completely until you find out more about CSP. Your current CSP is pretty lax anyway (allowing unsafe-inline, unsafe-eval and a default-src of *), so it is probably not adding too much value, to be honest.

How do I add to the Windows PATH variable using setx? Having weird problems

Steps: 1. Open a command prompt with administrator's rights.

Steps: 2. Run the command: setx /M PATH "path\to;%PATH%"

[Note: Be sure to alter the command so that path\to reflects the folder path from your root.]

Example : setx /M PATH "C:\Program Files;%PATH%"

Stacking DIVs on top of each other?

You can now use CSS Grid to fix this.

<div class="outer">
  <div class="top"> </div>
  <div class="below"> </div>
</div>

And the css for this:

.outer {
  display: grid;
  grid-template: 1fr / 1fr;
  place-items: center;
}
.outer > * {
  grid-column: 1 / 1;
  grid-row: 1 / 1;
}
.outer .below {
  z-index: 2;
}
.outer .top {
  z-index: 1;
}

Including a groovy script in another groovy

Here's a complete example of including one script within another.
Just run the Testmain.groovy file
Explanatory comments included because I'm nice like that ;]

Testutils.groovy

// This is the 'include file'
// Testmain.groovy will load it as an implicit class
// Each method in here will become a method on the implicit class

def myUtilityMethod(String msg) {
    println "myUtilityMethod running with: ${msg}"
}

Testmain.groovy

// Run this file

// evaluate implicitly creates a class based on the filename specified
evaluate(new File("./Testutils.groovy"))
// Safer to use 'def' here as Groovy seems fussy about whether the filename (and therefore implicit class name) has a capital first letter
def tu = new Testutils()
tu.myUtilityMethod("hello world")

jQuery: Wait/Delay 1 second without executing code

delay() doesn't halt the flow of code then re-run it. There's no practical way to do that in JavaScript. Everything has to be done with functions which take callbacks such as setTimeout which others have mentioned.

The purpose of jQuery's delay() is to make an animation queue wait before executing. So for example $(element).delay(3000).fadeIn(250); will make the element fade in after 3 seconds.

Reading and writing value from a textfile by using vbscript code

Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("listfile.txt")
Dim inFile: Set inFile = obj.OpenTextFile("listfile.txt")

' read file
data = inFile.ReadAll
inFile.Close

' write file
outFile.write (data)
outFile.Close

Build not visible in itunes connect

Check the status of the new build on the "Activity" tab. Once the "Processing" label disappears from the build you should be able to use it.

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

I have no idea why, maybe it is because I develop in Kotlin but to fix this error I finally have to create a class that extends MultiDexApplication like this:

class MyApplication : MultiDexApplication() {
}

and in my Manifest.xml I have to set

<application
        ...
        android:name=".MyApplication">

to not confuse anyone, I also do:

multiDexEnabled true
implementation 'com.android.support:multidex:1.0.3'

for androidx, this also works for me:

implementation 'androidx.multidex:multidex:2.0.0'

...

<application android:name="android.support.multidex.MultiDexApplication">

does not work for me

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

Another way to solve this using xpath

WebDriver driver =  new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath(//*[@id='email'])).sendKeys("[email protected]");

Hope that will help. :)

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.

How to download PDF automatically using js?

Use the download attribute.

var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));

Resource files not found from JUnit test cases

Main classes should be under src/main/java
and
test classes should be under src/test/java

If all in the correct places and still main classes are not accessible then
Right click project => Maven => Update Project
Hope so this will resolve the issue

Insert line break inside placeholder attribute of a textarea?

Salaamun Alekum

&#10;

Works For Google Chrome

enter image description here

<textarea placeholder="Enter Choice#1 &#10;Enter Choice#2 &#10;Enter Choice#3"></textarea>

I Tested This On Windows 10.0 (Build 10240) And Google Chrome Version 47.0.2526.80 m

08:43:08 AST 6 Rabi Al-Awwal, 1437 Thursday, 17 December 2015

Thank You

Undo a Git merge that hasn't been pushed yet

You have to change your HEAD, Not yours of course but git HEAD....

So before answering let's add some background, explaining what is this HEAD.

First of all what is HEAD?

HEAD is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD at any given time. (excluding git worktree)

The content of HEAD is stored inside .git/HEAD and it contains the 40 bytes SHA-1 of the current commit.


detached HEAD

If you are not on the latest commit - meaning that HEAD is pointing to a prior commit in history its called detached HEAD.

enter image description here

On the command line, it will look like this- SHA-1 instead of the branch name since the HEAD is not pointing to the tip of the current branch

enter image description here

enter image description here

A few options on how to recover from a detached HEAD:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.

# Checkout a given commit. 
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

You can always use the reflog as well.
git reflog will display any change which updated the HEAD and checking out the desired reflog entry will set the HEAD back to this commit.

Every time the HEAD is modified there will be a new entry in the reflog

git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

enter image description here


git reset --hard <commit_id>

"Move" your HEAD back to the desired commit.

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
  • Note: (Since Git 2.7)
    you can also use the git rebase --no-autostash as well.

git revert <sha-1>

"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.

# add new commit with the undo of the original one.
# the <sha-1> can be any commit(s) or commit range
git revert <sha-1>

This schema illustrates which command does what.
As you can see there reset && checkout modify the HEAD.

enter image description here

How to create a notification with NotificationCompat.Builder?

Notification in depth

CODE

Intent intent = new Intent(this, SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);

NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.your_notification_icon)
                        .setContentTitle("Notification Title")
                        .setContentText("Notification ")
                        .setContentIntent(pendingIntent );

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mBuilder.build());

Depth knowledge

Notification can be build using Notification. Builder or NotificationCompat.Builder classes.
But if you want backward compatibility you should use NotificationCompat.Builder class as it is part of v4 Support library as it takes care of heavy lifting for providing consistent look and functionalities of Notification for API 4 and above.

Core Notification Properties

A notification has 4 core properties (3 Basic display properties + 1 click action property)

  • Small icon
  • Title
  • Text
  • Button click event (Click event when you tap the notification )

Button click event is made optional on Android 3.0 and above. It means that you can build your notification using only display properties if your minSdk targets Android 3.0 or above. But if you want your notification to run on older devices than Android 3.0 then you must provide Click event otherwise you will see IllegalArgumentException.

Notification Display

Notification are displayed by calling notify() method of NotificationManger class

notify() parameters

There are two variants available for notify method

notify(String tag, int id, Notification notification)

or

notify(int id, Notification notification)

notify method takes an integer id to uniquely identify your notification. However, you can also provide an optional String tag for further identification of your notification in case of conflict.

This type of conflict is rare but say, you have created some library and other developers are using your library. Now they create their own notification and somehow your notification and other dev's notification id is same then you will face conflict.

Notification after API 11 (More control)

API 11 provides additional control on Notification behavior

  • Notification Dismissal
    By default, if a user taps on notification then it performs the assigned click event but it does not clear away the notification. If you want your notification to get cleared when then you should add this

    mBuilder.setAutoClear(true);

  • Prevent user from dismissing notification
    A user may also dismiss the notification by swiping it. You can disable this default behavior by adding this while building your notification

    mBuilder.setOngoing(true);

  • Positioning of notification
    You can set the relative priority to your notification by

    mBuilder.setOngoing(int pri);

If your app runs on lower API than 11 then your notification will work without above mentioned additional features. This is the advantage to choosing NotificationCompat.Builder over Notification.Builder

Notification after API 16 (More informative)

With the introduction of API 16, notifications were given so many new features
Notification can be so much more informative.
You can add a bigPicture to your logo. Say you get a message from a person now with the mBuilder.setLargeIcon(Bitmap bitmap) you can show that person's photo. So in the statusbar you will see the icon when you scroll you will see the person photo in place of the icon. There are other features too

  • Add a counter in the notification
  • Ticker message when you see the notification for the first time
  • Expandable notification
  • Multiline notification and so on

Creating a new DOM element from an HTML string using built-in DOM methods or Prototype

You can use the following function to convert the text "HTML" to the element

_x000D_
_x000D_
function htmlToElement(html)_x000D_
{_x000D_
  var element = document.createElement('div');_x000D_
  element.innerHTML = html;_x000D_
  return(element);_x000D_
}_x000D_
var html="<li>text and html</li>";_x000D_
var e=htmlToElement(html);
_x000D_
_x000D_
_x000D_

How to add buttons at top of map fragment API v2 layout

extending de Almeida's answer I am editing code little bit here. since previous code was hiding gps location icon I did following way which worked better.

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"

>

<RadioGroup 
    android:id="@+id/radio_group_list_selector"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:orientation="horizontal" 
    android:background="#80000000"
    android:padding="4dp" >

    <RadioButton
        android:id="@+id/radioPopular"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="@string/Popular"
        android:gravity="center_horizontal|center_vertical"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton"
        android:textColor="@drawable/textcolor_radiobutton" />
    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioAZ"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/AZ"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton2"
        android:textColor="@drawable/textcolor_radiobutton" />

    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioCategory"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/Category"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton2"
        android:textColor="@drawable/textcolor_radiobutton" />
    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioNearBy"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/NearBy"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton3"
        android:textColor="@drawable/textcolor_radiobutton" />
</RadioGroup>

<fragment
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:scrollbars="vertical" />

Adding an onclick event to a table row

Something like this.

function addRowHandlers() {
  var table = document.getElementById("tableId");
  var rows = table.getElementsByTagName("tr");
  for (i = 0; i < rows.length; i++) {
    var currentRow = table.rows[i];
    var createClickHandler = function(row) {
      return function() {
        var cell = row.getElementsByTagName("td")[0];
        var id = cell.innerHTML;
        alert("id:" + id);
      };
    };
    currentRow.onclick = createClickHandler(currentRow);
  }
}

EDIT

Working demo.

Transfer data between iOS and Android via Bluetooth?

Maybe a bit delayed, but technologies have evolved since so there is certainly new info around which draws fresh light on the matter...

As iOS has yet to open up an API for WiFi Direct and Multipeer Connectivity is iOS only, I believe the best way to approach this is to use BLE, which is supported by both platforms (some better than others).

On iOS a device can act both as a BLE Central and BLE Peripheral at the same time, on Android the situation is more complex as not all devices support the BLE Peripheral state. Also the Android BLE stack is very unstable (to date).

If your use case is feature driven, I would suggest to look at Frameworks and Libraries that can achieve cross platform communication for you, without you needing to build it up from scratch.

For example: http://p2pkit.io or google nearby

Disclaimer: I work for Uepaa, developing p2pkit.io for Android and iOS.

Java reading a file into an ArrayList?

    Scanner scr = new Scanner(new File(filePathInString));
/*Above line for scanning data from file*/

    enter code here

ArrayList<DataType> list = new ArrayList<DateType>();
/*this is a object of arraylist which in data will store after scan*/

while (scr.hasNext()){

list.add(scr.next()); } /*above code is responsible for adding data in arraylist with the help of add function */

Step-by-step debugging with IPython

If you type exit() in embed() console the code continue and go to the next embed() line.

How to send parameters with jquery $.get()

If you say that it works with accessing directly manageproducts.do?option=1 in the browser then it should work with:

$.get('manageproducts.do', { option: '1' }, function(data) {
    ...
});

as it would send the same GET request.

How to implement a confirmation (yes/no) DialogPreference?

Use Intent Preference if you are using preference xml screen or you if you are using you custom screen then the code would be like below

intentClearCookies = getPreferenceManager().createPreferenceScreen(this);
    Intent clearcookies = new Intent(PopupPostPref.this, ClearCookies.class);

    intentClearCookies.setIntent(clearcookies);
    intentClearCookies.setTitle(R.string.ClearCookies);
    intentClearCookies.setEnabled(true);
    launchPrefCat.addPreference(intentClearCookies);

And then Create Activity Class somewhat like below, As different people as different approach you can use any approach you like this is just an example.

public class ClearCookies extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    showDialog();
}

/**
 * @throws NotFoundException
 */
private void showDialog() throws NotFoundException {
    new AlertDialog.Builder(this)
            .setTitle(getResources().getString(R.string.ClearCookies))
            .setMessage(
                    getResources().getString(R.string.ClearCookieQuestion))
            .setIcon(
                    getResources().getDrawable(
                            android.R.drawable.ic_dialog_alert))
            .setPositiveButton(
                    getResources().getString(R.string.PostiveYesButton),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            //Do Something Here

                        }
                    })
            .setNegativeButton(
                    getResources().getString(R.string.NegativeNoButton),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            //Do Something Here
                        }
                    }).show();
}}

As told before there are number of ways doing this. this is one of the way you can do your task, please accept the answer if you feel that you have got it what you wanted.

Powershell import-module doesn't find modules

try with below on powershell:

Set-ExecutionPolicy -ExecutionPolicy Unrestricted
import-module [\path\]XMLHelpers.psm1

Instead of [] put the full path

Full explanation of this and that

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Problem solved, I've not added the index.html. Which is point out in the web.xml

enter image description here

Note: a project may have more than one web.xml file.

if there are another web.xml in

src/main/webapp/WEB-INF

Then you might need to add another index (this time index.jsp) to

src/main/webapp/WEB-INF/pages/

MySql: is it possible to 'SUM IF' or to 'COUNT IF'?

There is a slight difference between the top answers, namely SUM(case when kind = 1 then 1 else 0 end) and SUM(kind=1).

When all values in column kind happen to be NULL, the result of SUM(case when kind = 1 then 1 else 0 end) is 0, whereas the result of SUM(kind=1) is NULL.

An example (http://sqlfiddle.com/#!9/b23807/2):

Schema:

CREATE TABLE Table1
(`first_col` int, `second_col` int)
;

INSERT INTO Table1
    (`first_col`, `second_col`)
VALUES
       (1, NULL),
       (1, NULL),
       (NULL, NULL)
;

Query results:

SELECT SUM(first_col=1) FROM Table1;
-- Result: 2
SELECT SUM(first_col=2) FROM Table1;
-- Result: 0
SELECT SUM(second_col=1) FROM Table1;
-- Result: NULL
SELECT SUM(CASE WHEN second_col=1 THEN 1 ELSE 0 END) FROM Table1;
-- Result: 0

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at

You cannot session_start(); when your buffer has already been partly sent.

This mean, if your script already sent informations (something you want, or an error report) to the client, session_start() will fail.

Sticky Header after scrolling down

This was not working for me in Firefox.

We added a conditional based on whether the code places the overflow at the html level. See Animate scrollTop not working in firefox.

  var $header = $("#header #menu-wrap-left"),
  $clone = $header.before($header.clone().addClass("clone"));

  $(window).on("scroll", function() {
    var fromTop = Array(); 
    fromTop["body"] = $("body").scrollTop();
    fromTop["html"] = $("body,html").scrollTop();

if (fromTop["body"]) 
    $('body').toggleClass("down", (fromTop["body"] > 650));

if (fromTop["html"]) 
    $('body,html').toggleClass("down", (fromTop["html"] > 650));

  });

How to run Java program in command prompt

You can use javac *.java command to compile all you java sources. Also you should learn a little about classpath because it seems that you should set appropriate classpath for succesful compilation (because your IDE use some libraries for building WebService clients). Also I can recommend you to check wich command your IDE use to build your project.

Python script to copy text to clipboard

I try this clipboard 0.0.4 and it works well.

https://pypi.python.org/pypi/clipboard/0.0.4

import clipboard
clipboard.copy("abc")  # now the clipboard content will be string "abc"
text = clipboard.paste()  # text will have the content of clipboard

Using grep and sed to find and replace a string

You can use find and -exec directly into sed rather than first locating oldstr with grep. It's maybe a bit less efficient, but that might not be important. This way, the sed replacement is executed over all files listed by find, but if oldstr isn't there it obviously won't operate on it.

find /path -type f -exec sed -i 's/oldstr/newstr/g' {} \;

HTML checkbox onclick called in Javascript

Label without an onclick will behave as you would expect. It changes the input. What you relly want is to execute selectAll() when you click on a label, right? Then only add select all to the label onclick. Or wrap the input into the the label and assign onclick only for the label

<label for="check_all_1" onclick="selectAll(document.wizard_form, this);">
  <input type="checkbox" id="check_all_1" name="check_all_1" title="Select All">
  Select All
</label>

ssh: connect to host github.com port 22: Connection timed out

Basic URL Rewriting

Git provides a way to rewrite URLs using git config. Simply issue the following command:

git config --global url."https://".insteadOf git://

Now, as if by magic, all git commands will perform a substitution of git:// to https://

source: git:// protocol blocked by company, how can I get around that?

How do I repair an InnoDB table?

stop your application...or stop your slave so no new rows are being added

create table <new table> like <old table>;
insert <new table> select * from <old table>;
truncate table  <old table>;
insert <old table> select * from <new table>;

restart your server or slave

java.util.NoSuchElementException: No line found

For whatever reason, the Scanner class also issues this same exception if it encounters special characters it cannot read. Beyond using the hasNextLine() method before each call to nextLine(), make sure the correct encoding is passed to the Scanner constructor, e.g.:

Scanner scanner = new Scanner(new FileInputStream(filePath), "UTF-8");

Android: set view style programmatically

if inside own custom view : val editText = TextInputEditText(context, attrs, defStyleAttr)

Display Two <div>s Side-by-Side

I removed the float from the second div to make it work.

http://jsfiddle.net/rhEyM/2/

Error: Jump to case label

The problem is that variables declared in one case are still visible in the subsequent cases unless an explicit { } block is used, but they will not be initialized because the initialization code belongs to another case.

In the following code, if foo equals 1, everything is ok, but if it equals 2, we'll accidentally use the i variable which does exist but probably contains garbage.

switch(foo) {
  case 1:
    int i = 42; // i exists all the way to the end of the switch
    dostuff(i);
    break;
  case 2:
    dostuff(i*2); // i is *also* in scope here, but is not initialized!
}

Wrapping the case in an explicit block solves the problem:

switch(foo) {
  case 1:
    {
        int i = 42; // i only exists within the { }
        dostuff(i);
        break;
    }
  case 2:
    dostuff(123); // Now you cannot use i accidentally
}

Edit

To further elaborate, switch statements are just a particularly fancy kind of a goto. Here's an analoguous piece of code exhibiting the same issue but using a goto instead of a switch:

int main() {
    if(rand() % 2) // Toss a coin
        goto end;

    int i = 42;

  end:
    // We either skipped the declaration of i or not,
    // but either way the variable i exists here, because
    // variable scopes are resolved at compile time.
    // Whether the *initialization* code was run, though,
    // depends on whether rand returned 0 or 1.
    std::cout << i;
}

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

The error you receive is from another method than the one you show here. It's a method that takes a parameter with the name "source". In your Visual Studio Options dialog, disable "Just my code", disable "Step over properties and operators" and enable "Enable .NET Framework source stepping". Make sure the .NET symbols can be found. Then the debugger will break inside the .NET method if it isn't your own. then check the stacktrace to find which value is passed that's null, but shouldn't.

What you should look for is a value that becomes null and prevent that. From looking at your code, it may be the itemsal.Add line that breaks.

Edit

Since you seem to have trouble with debugging in general and LINQ especially, let's try to help you out step by step (also note the expanded first section above if you still want to try it the classic way, I wasn't complete the first time around):

  • Narrow down the possible error scenarios by splitting your code;
  • Replace locations that can end up null with something deliberately not null;
  • If all fails, rewrite your LINQ statement as loop and go through it step by step.

Step 1

First make the code a bit more readable by splitting it in manageable pieces:

// in your using-section, add this:
using Roundsman.BAL;

// keep this in your normal location
var nCounts = from sale in sal
              select new
              {
                  SaleID = sale.OrderID,
                  LineItem = GetLineItem(sale.LineItems)
              };

foreach (var item in nCounts)
{
    foreach (var itmss in item.LineItem)
    {
        itemsal.Add(CreateWeeklyStockList(itmss));
    }
}


// add this as method somewhere
WeeklyStockList CreateWeeklyStockList(LineItem lineItem)
{
    string name = itmss.Item.Name.ToString();  // isn't Name already a string?
    string code = itmss.Item.Code.ToString();  // isn't Code already a string?
    string description = itmss.Item.Description.ToString();  // isn't Description already a string?
    int quantity = Convert.ToInt32(itmss.Item.Quantity); // wouldn't (int) or "as int" be enough?

    return new WeeklyStockList(
                 name, 
                 code, 
                 description,
                 quantity, 
                 2, 2, 2, 2, 2, 2, 2, 2, 2
              );
}

// also add this as a method
LineItem GetLineItem(IEnumerable<LineItem> lineItems)
{
    // add a null-check
    if(lineItems == null)
        throw new ArgumentNullException("lineItems", "Argument cannot be null!");

    // your original code
    from sli in lineItems
    group sli by sli.Item into ItemGroup
    select new
    {
        Item = ItemGroup.Key,
        Weeks = ItemGroup.Select(s => s.Week)
    }
}

The code above is from the top of my head, of course, because I cannot know what type of classes you have and thus cannot test the code before posting. Nevertheless, if you edit it until it is correct (if it isn't so out of the box), then you already stand a large chance the actual error becomes a lot clearer. If not, you should at the very least see a different stacktrace this time (which we still eagerly await!).

Step 2

The next step is to meticulously replace each part that can result in a null reference exception. By that I mean that you replace this:

select new
{
    SaleID = sale.OrderID,
    LineItem = GetLineItem(sale.LineItems)
};

with something like this:

select new
{
    SaleID = 123,
    LineItem = GetLineItem(new LineItem(/*ctor params for empty lineitem here*/))
};

This will create rubbish output, but will narrow the problem down even further to your potential offending line. Do the same as above for other places in the LINQ statements that can end up null (just about everything).

Step 3

This step you'll have to do yourself. But if LINQ fails and gives you such headaches and such unreadable or hard-to-debug code, consider what would happen with the next problem you encounter? And what if it fails on a live environment and you have to solve it under time pressure=

The moral: it's always good to learn new techniques, but sometimes it's even better to grab back to something that's clear and understandable. Nothing against LINQ, I love it, but in this particular case, let it rest, fix it with a simple loop and revisit it in half a year or so.

Conclusion

Actually, nothing to conclude. I went a bit further then I'd normally go with the long-extended answer. I just hope it helps you tackling the problem better and gives you some tools understand how you can narrow down hard-to-debug situations, even without advanced debugging techniques (which we haven't discussed).

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

Pure datetime solution, does not depend on language or DATEFORMAT, no strings

SELECT
    DATEADD(year, [year]-1900, DATEADD(month, [month]-1, DATEADD(day, [day]-1, 0)))
FROM
    dbo.Table

How to use a servlet filter in Java to change an incoming servlet request url?

A simple JSF Url Prettyfier filter based in the steps of BalusC's answer. The filter forwards all the requests starting with the /ui path (supposing you've got all your xhtml files stored there) to the same path, but adding the xhtml suffix.

public class UrlPrettyfierFilter implements Filter {

    private static final String JSF_VIEW_ROOT_PATH = "/ui";

    private static final String JSF_VIEW_SUFFIX = ".xhtml";

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
        String requestURI = httpServletRequest.getRequestURI();
        //Only process the paths starting with /ui, so as other requests get unprocessed. 
        //You can register the filter itself for /ui/* only, too
        if (requestURI.startsWith(JSF_VIEW_ROOT_PATH) 
                && !requestURI.contains(JSF_VIEW_SUFFIX)) {
            request.getRequestDispatcher(requestURI.concat(JSF_VIEW_SUFFIX))
                .forward(request,response);
        } else {
            chain.doFilter(httpServletRequest, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Request-scoped beans can be autowired with the request object.

private @Autowired HttpServletRequest request;

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 set font size based on container size?

I had a similar issue but I had to consider other issues that @apaul34208 example did not tackle. In my case;

  • I have a container that changed size depending on the viewport using media queries
  • Text inside is dynamically generated
  • I want to scale up as well as down

Not the most elegant of examples but it does the trick for me. Consider using throttling the window resize (https://lodash.com/)

_x000D_
_x000D_
var TextFit = function(){_x000D_
 var container = $('.container');_x000D_
  container.each(function(){_x000D_
    var container_width = $(this).width(),_x000D_
      width_offset = parseInt($(this).data('width-offset')),_x000D_
        font_container = $(this).find('.font-container');_x000D_
 _x000D_
     if ( width_offset > 0 ) {_x000D_
         container_width -= width_offset;_x000D_
     }_x000D_
                _x000D_
    font_container.each(function(){_x000D_
      var font_container_width = $(this).width(),_x000D_
          font_size = parseFloat( $(this).css('font-size') );_x000D_
_x000D_
      var diff = Math.max(container_width, font_container_width) - Math.min(container_width, font_container_width);_x000D_
 _x000D_
      var diff_percentage = Math.round( ( diff / Math.max(container_width, font_container_width) ) * 100 );_x000D_
      _x000D_
      if (diff_percentage !== 0){_x000D_
          if ( container_width > font_container_width ) {_x000D_
            new_font_size = font_size + Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
          } else if ( container_width < font_container_width ) {_x000D_
            new_font_size = font_size - Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
          }_x000D_
      }_x000D_
      $(this).css('font-size', new_font_size + 'px');_x000D_
    });_x000D_
  });_x000D_
}_x000D_
_x000D_
$(function(){_x000D_
  TextFit();_x000D_
  $(window).resize(function(){_x000D_
   TextFit();_x000D_
  });_x000D_
});
_x000D_
.container {_x000D_
  width:341px;_x000D_
  height:341px;_x000D_
  background-color:#000;_x000D_
  padding:20px;_x000D_
 }_x000D_
 .font-container {_x000D_
  font-size:131px;_x000D_
  text-align:center;_x000D_
  color:#fff;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container" data-width-offset="10">_x000D_
 <span class="font-container">£5000</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/Merch80/b8hoctfb/7/

Search for an item in a Lua list

function valid(data, array)
 local valid = {}
 for i = 1, #array do
  valid[array[i]] = true
 end
 if valid[data] then
  return false
 else
  return true
 end
end

Here's the function I use for checking if data is in an array.

What is a thread exit code?

There actually doesn't seem to be a lot of explanation on this subject apparently but the exit codes are supposed to be used to give an indication on how the thread exited, 0 tends to mean that it exited safely whilst anything else tends to mean it didn't exit as expected. But then this exit code can be set in code by yourself to completely overlook this.

The closest link I could find to be useful for more information is this

Quote from above link:

What ever the method of exiting, the integer that you return from your process or thread must be values from 0-255(8bits). A zero value indicates success, while a non zero value indicates failure. Although, you can attempt to return any integer value as an exit code, only the lowest byte of the integer is returned from your process or thread as part of an exit code. The higher order bytes are used by the operating system to convey special information about the process. The exit code is very useful in batch/shell programs which conditionally execute other programs depending on the success or failure of one.


From the Documentation for GetEXitCodeThread

Important The GetExitCodeThread function returns a valid error code defined by the application only after the thread terminates. Therefore, an application should not use STILL_ACTIVE (259) as an error code. If a thread returns STILL_ACTIVE (259) as an error code, applications that test for this value could interpret it to mean that the thread is still running and continue to test for the completion of the thread after the thread has terminated, which could put the application into an infinite loop.


My understanding of all this is that the exit code doesn't matter all that much if you are using threads within your own application for your own application. The exception to this is possibly if you are running a couple of threads at the same time that have a dependency on each other. If there is a requirement for an outside source to read this error code, then you can set it to let other applications know the status of your thread.

Authorize a non-admin developer in Xcode / Mac OS

Ned Deily's solution works perfectly fine, provided your user is allowed to sudo.

If he's not, you can su to an admin account, then use his dscl . append /Groups/_developer GroupMembership $user, where $user is the username.

However, I mistakenly thought it did not because I wrongly typed in the user's name in the command and it silently fails.

Therefore, after entering this command, you should proof-check it. This will check if $user is in $group, where the variables represent respectively the user name and the group name.

dsmemberutil checkmembership -U $user -G $group

This command will either print the message user is not a member of the group or user is a member of the group.

jQuery checkbox check/uncheck

 $('mainCheckBox').click(function(){
    if($(this).prop('checked')){
        $('Id or Class of checkbox').prop('checked', true);
    }else{
        $('Id or Class of checkbox').prop('checked', false);
    }
});

How to link to part of the same document in Markdown?

In addition to the above answers,

When setting the option number_sections: true in the YAML header:

number_sections: TRUE

RMarkdown will autonumber your sections.

To reference those autonumbered sections simply put the following in your R Markdown file:

[My Section]

Where My Section is the name of the section

This seems to work regardless of the section level:

# My section

## My section

### My section

importing a CSV into phpmyadmin

Using the LOAD DATA INFILE SQL statement you can import the CSV file, but you can't update data. However, there is a trick you can use.

  • Create another temporary table to use for the import
  • Load onto this table from the CSC

    LOAD DATA LOCAL INFILE '/file.csv'
    INTO TABLE temp_table
    FIELDS TERMINATED BY ','
    LINES TERMINATED BY '\n'
    (field1, field2, field3); 
    
  • UPDATE the real table joining the table

    UPDATE maintable
    INNER JOIN temp_table A USING (field1)
    SET maintable.field1 = temp_table.field1
    

How can I match a string with a regex in Bash?

Since you are using bash, you don't need to create a child process for doing this. Here is one solution which performs it entirely within bash:

[[ $TEST =~ ^(.*):\ +(.*)$ ]] && TEST=${BASH_REMATCH[1]}:${BASH_REMATCH[2]}

Explanation: The groups before and after the sequence "colon and one or more spaces" are stored by the pattern match operator in the BASH_REMATCH array.

What is 0x10 in decimal?

0x means the number is hexadecimal, or base 16.

0x10 is 16.

Correct file permissions for WordPress

Giving the full access to all wp files to www-data user (which is in this case the web server user) can be dangerous. So rather do NOT do this:

chown www-data:www-data -R *

It can be useful however in the moment when you're installing or upgrading WordPress and its plug-ins. But when you finished it's no longer a good idea to keep wp files owned by the web server.

It basically allows the web server to put or overwrite any file in your website. This means that there is a possibility to take over your site if someone manage to use the web server (or a security hole in some .php script) to put some files in your website.

To protect your site against such an attack you should to the following:

All files should be owned by your user account, and should be writable by you. Any file that needs write access from WordPress should be writable by the web server, if your hosting set up requires it, that may mean those files need to be group-owned by the user account used by the web server process.

/

The root WordPress directory: all files should be writable only by your user account, except .htaccess if you want WordPress to automatically generate rewrite rules for you.

/wp-admin/

The WordPress administration area: all files should be writable only by your user account.

/wp-includes/

The bulk of WordPress application logic: all files should be writable only by your user account.

/wp-content/

User-supplied content: intended to be writable by your user account and the web server process.

Within /wp-content/ you will find:

/wp-content/themes/

Theme files. If you want to use the built-in theme editor, all files need to be writable by the web server process. If you do not want to use the built-in theme editor, all files can be writable only by your user account.

/wp-content/plugins/

Plugin files: all files should be writable only by your user account.

Other directories that may be present with /wp-content/ should be documented by whichever plugin or theme requires them. Permissions may vary.

Source and additional information: http://codex.wordpress.org/Hardening_WordPress

How can I print a quotation mark in C?

Without a backslash, special characters have a natural special meaning. With a backslash they print as they appear.

\   -   escape the next character
"   -   start or end of string
’   -   start or end a character constant
%   -   start a format specification
\\  -   print a backslash
\"  -   print a double quote
\’  -   print a single quote
%%  -   print a percent sign

The statement

printf("  \"  "); 

will print you the quotes. You can also print these special characters \a, \b, \f, \n, \r, \t and \v with a (slash) preceeding it.

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

  1. Save and close all Internet Explorer windows and then, run Windows Task Manager to end the running processes in background.
  2. Go to Control Panel.
  3. Click Programs and choose the View installed updates instead.
  4. Locate the following Windows Internet Explorer 11 or you can type "Internet Explorer" for a quick search.
  5. Choose the Yes option from the following "Uninstall an update".
  6. Please wait while Windows Internet Explorer 10 is being restored and reconfigured automatically.
  7. Follow the Microsoft Windows wizard to restart your system.

Note: You can do it for as many earlier versions you want, i.e. IE9, IE8 and so on.

C++, How to determine if a Windows Process is running?

You may find if a process (given its name or PID) is running or not by iterating over the running processes simply by taking a snapshot of running processes via CreateToolhelp32Snapshot, and by using Process32First and Process32Next calls on that snapshot.

Then you may use th32ProcessID field or szExeFile field of the resulting PROCESSENTRY32 struct depending on whether you want to search by PID or executable name. A simple implementation can be found here.

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

Hopefully it helps someone: I ran into this error and the cause was wrong permission on the log folder for phpfpm, after changing it so phpfpm could write to it, everything was fine.

How can I reorder a list?

You can provide your own sort function to list.sort():

The sort() method takes optional arguments for controlling the comparisons.

  • cmp specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.

  • key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None.

  • reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once.

Is there an alternative to string.Replace that is case-insensitive?

The regular expression method should work. However what you can also do is lower case the string from the database, lower case the %variables% you have, and then locate the positions and lengths in the lower cased string from the database. Remember, positions in a string don't change just because its lower cased.

Then using a loop that goes in reverse (its easier, if you do not you will have to keep a running count of where later points move to) remove from your non-lower cased string from the database the %variables% by their position and length and insert the replacement values.

What is the difference between Forking and Cloning on GitHub?

Basically, yes. A fork is just a request for GitHub to clone the project and registers it under your username; GitHub also keeps track of the relationship between the two repositories, so you can visualize the commits and pulls between the two projects (and other forks).

You can still request that people pull from your cloned repository, even if you don't use fork -- but you'd have to deal with making it publicly available yourself. Or send the developers patches (see git format-patch) that they can apply to their trees.

SQL Server: how to select records with specific date from datetime column

The easiest way is to convert to a date:

SELECT *
FROM dbo.LogRequests
WHERE cast(dateX as date) = '2014-05-09';

Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as this and this.

I would be inclined to use the following, just out of habit:

SELECT *
FROM dbo.LogRequests
WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

Go to android studio setting (by pressing Ctrl+Alt+S in windows), search for Instant Run and uncheck Enable Instant Run.

By disabling Instant Run and running your application again, problem will be resolved.

XPath to select multiple tags

Why not a/b/(c|d|e)? I just tried with Saxon XML library (wrapped up nicely with some Clojure goodness), and it seems to work. abc.xml is the doc described by OP.

(require '[saxon :as xml])
(def abc-doc (xml/compile-xml (slurp "abc.xml")))
(xml/query "a/b/(c|d|e)" abc-doc)
=> (#<XdmNode <c>C1</c>>
    #<XdmNode <d>D1</d>>
    #<XdmNode <e>E1</e>>
    #<XdmNode <c>C2</c>>
    #<XdmNode <d>D2</d>>
    #<XdmNode <e>E1</e>>)

Count number of cells with any value (string or number) in a column in Google Docs Spreadsheet

An additional trick beside using =COUNTIF(...) and =COUNTA(...) is:

=COUNTBLANK(A2:C100)

That will count all the empty cells.

This is useful for:

  • empty cells that doesn't contain data
  • formula that return blank or null
  • survey with missing answer fields which can be used for diff criterias

Simulate limited bandwidth from within Chrome?

If you are running Linux, the following command is really useful for this:

trickle -s -d 50 -w 100 firefox

The -s tells the command to run standalone, the -d 50 tells it to limit bandwidth to 50 KB/s, the -w 100 set the peak detection window size to 100 KB. firefox tells the command to start firefox with all of this rate limiting applied to any sites it attempts to load.

Update

Chrome 38 is out now and includes throttling. To find it, bring up the Developer Tools: Ctrl+Shift+I does it on my machine, otherwise Menu->More Tools->Developer Tools will bring you there.

Then Toggle Device Mode by clicking the phone in the upper left of the Developer Tools Panel (see the tooltip below).

Toggle device mode

Then activate throttling like so.

Activate Chrome throttling

If you find this a bit clunky, my suggestion above works for both Chrome and Firefox.

MongoDB relationships: embed or reference?

If I want to edit a specified comment, how to get its content and its question?

You can query by sub-document: db.question.find({'comments.content' : 'xxx'}).

This will return the whole Question document. To edit the specified comment, you then have to find the comment on the client, make the edit and save that back to the DB.

In general, if your document contains an array of objects, you'll find that those sub-objects will need to be modified client side.

AngularJS: Can't I set a variable value on ng-click?

If you are using latest versions of Angular (2/5/6) :

In your component.ts

//x.component.ts
prefs = false;

hidePrefs(){
   this.prefs = true;
}

LINQ Where with AND OR condition

from item in db.vw_Dropship_OrderItems
    where (listStatus != null ? listStatus.Contains(item.StatusCode) : true) &&
    (listMerchants != null ? listMerchants.Contains(item.MerchantId) : true)
    select item;

Might give strange behavior if both listMerchants and listStatus are both null.

How to get config parameters in Symfony2 Twig Templates

You can simply bind $this->getParameter('app.version') in controller to twig param and then render it.

Error 6 (net::ERR_FILE_NOT_FOUND): The files c or directory could not be found

I have solved this issue as follows:

removed from chrome extension and install ext again. It will work ISA

json_encode/json_decode - returns stdClass instead of Array in PHP

$arrayDecoded = json_decode($arrayEncoded, true);

gives you an array.

NameError: global name 'xrange' is not defined in Python 3

You are trying to run a Python 2 codebase with Python 3. xrange() was renamed to range() in Python 3.

Run the game with Python 2 instead. Don't try to port it unless you know what you are doing, most likely there will be more problems beyond xrange() vs. range().

For the record, what you are seeing is not a syntax error but a runtime exception instead.


If you do know what your are doing and are actively making a Python 2 codebase compatible with Python 3, you can bridge the code by adding the global name to your module as an alias for range. (Take into account that you may have to update any existing range() use in the Python 2 codebase with list(range(...)) to ensure you still get a list object in Python 3):

try:
    # Python 2
    xrange
except NameError:
    # Python 3, xrange is now named range
    xrange = range

# Python 2 code that uses xrange(...) unchanged, and any
# range(...) replaced with list(range(...))

or replace all uses of xrange(...) with range(...) in the codebase and then use a different shim to make the Python 3 syntax compatible with Python 2:

try:
    # Python 2 forward compatibility
    range = xrange
except NameError:
    pass

# Python 2 code transformed from range(...) -> list(range(...)) and
# xrange(...) -> range(...).

The latter is preferable for codebases that want to aim to be Python 3 compatible only in the long run, it is easier to then just use Python 3 syntax whenever possible.

Counting unique / distinct values by group in a data frame

my.1 <- table(myvec)

my.1[my.1 != 0] <- 1

rowSums(my.1)

What is the difference between XML and XSD?


Take an example

<root>
  <parent>
     <child_one>Y</child_one>
     <child_two>12</child_two>
  </parent>
</root>

and design an xsd for that:

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" 
xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="root">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="parent">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="child_one" type="xs:string" />
              <xs:element name="child_two" type="xs:int" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>


What isn't possible with XSD: would like to write it first as the list is very small
1) You can't validate a node/attribute using the value of another node/attribute.
2) This is a restriction : An element defined in XSD file must be defined with only one datatype. [in the above example, for <child_two> appearing in another <parent> node, datatype cannot be defined other than int.
3) You can't ignore the validation of elements and attributes, ie, if an element/attribute appears in XML, it must be well-defined in the corresponding XSD. Though usage of <xsd:any> allows it, but it has got its own rules. Abiding which leads to the validation error. I had tried for a similar approach, and certainly wasn't successful, here is the Q&A


what are possible with XSD:
1) You can test the proper hierarchy of the XML nodes. [xsd defines which child should come under which parent, etc, abiding which will be counted as error, in above example, child_two cannot be the immediate child of root, but it is the child of "parent" tag which is in-turn a child of "root" node, there is a hierarchy..]
2) You can define Data type of the values of the nodes. [in above example child_two cannot have any-other data than number]
3) You can also define custom data_types, [example, for node <month>, the possible data can be one of the 12 months.. so you need to define all the 12 months in a new data type writing all the 12 month names as enumeration values .. validation shows error if the input XML contains any-other value than these 12 values .. ]
4) You can put the restriction on the occurrence of the elements, using minOccurs and maxOccurs, the default values are 1 and 1.

.. and many more ...

What is the parameter "next" used for in Express?

Next is used to pass control to the next middleware function. If not the request will be left hanging or open.

Is a Python dictionary an example of a hash table?

Yes. Internally it is implemented as open hashing based on a primitive polynomial over Z/2 (source).

How to start activity in another application?

If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest

android:exported="true"

Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.

finish();

The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class in the code, so compile will fail.

I searched on the web and found something like this below, and it works well.

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);

You can also use the setClassName method:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();

You can also pass the values from one app to another app :

Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
    launchIntent.putExtra("AppID", "MY-CHILD-APP1");
    launchIntent.putExtra("UserID", "MY-APP");
    launchIntent.putExtra("Password", "MY-PASSWORD");
    startActivity(launchIntent);
    finish();
} else {
    Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}

How can I see the size of files and directories in linux?

Use ls command for files and du command for directories.

Checking File Sizes

ls -l filename   #Displays Size of the specified file
ls -l *          #Displays Size of All the files in the current directory
ls -al *         #Displays Size of All the files including hidden files in the current directory
ls -al dir/      #Displays Size of All the files including hidden files in the 'dir' directory

ls command will not list the actual size of directories(why?). Therefore, we use du for this purpose.

Checking Directory sizes

du -sh directory_name    #Gives you the summarized(-s) size of the directory in human readable(-h) format
du -bsh *                #Gives you the apparent(-b) summarized(-s) size of all the files and directories in the current directory in human readable(-h) format

Including -h option in any of the above commands (for Ex: ls -lh * or du -sh) will give you size in human readable format (kb, mb,gb, ...)

For more information see man ls and man du

Trust Store vs Key Store - creating with keytool

There is no difference between keystore and truststore files. Both are files in the proprietary JKS file format. The distinction is in the use: To the best of my knowledge, Java will only use the store that is referenced by the -Djavax.net.ssl.trustStore system property to look for certificates to trust when creating SSL connections. Same for keys and -Djavax.net.ssl.keyStore. But in theory it's fine to use one and the same file for trust- and keystores.

How do I get the coordinates of a mouse click on a canvas element?

If you like simplicity but still want cross-browser functionality I found this solution worked best for me. This is a simplification of @Aldekein´s solution but without jQuery.

function getCursorPosition(canvas, event) {
    const rect = canvas.getBoundingClientRect()
    const x = event.clientX - rect.left
    const y = event.clientY - rect.top
    console.log("x: " + x + " y: " + y)
}

const canvas = document.querySelector('canvas')
canvas.addEventListener('mousedown', function(e) {
    getCursorPosition(canvas, e)
})

json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

I wrote a class to normalize the data in my dictionary. The 'element' in the NormalizeData class below, needs to be of dict type. And you need to replace in the __iterate() with either your custom class object or any other object type that you would like to normalize.

class NormalizeData:

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

    def execute(self):
        if isinstance(self.element, dict):
            self.__iterate()
        else:
            return

    def __iterate(self):
        for key in self.element:
            if isinstance(self.element[key], <ClassName>):
                self.element[key] = str(self.element[key])

            node = NormalizeData(self.element[key])
            node.execute()

Try/catch does not seem to have an effect

Adding "-EA Stop" solved this for me.

What is the difference between single-quoted and double-quoted strings in PHP?

PHP strings can be specified not just in two ways, but in four ways.

  1. Single quoted strings will display things almost completely "as is." Variables and most escape sequences will not be interpreted. The exception is that to display a literal single quote, you can escape it with a back slash \', and to display a back slash, you can escape it with another backslash \\ (So yes, even single quoted strings are parsed).
  2. Double quote strings will display a host of escaped characters (including some regexes), and variables in the strings will be evaluated. An important point here is that you can use curly braces to isolate the name of the variable you want evaluated. For example let's say you have the variable $type and you want to echo "The $types are". That will look for the variable $types. To get around this use echo "The {$type}s are" You can put the left brace before or after the dollar sign. Take a look at string parsing to see how to use array variables and such.
  3. Heredoc string syntax works like double quoted strings. It starts with <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. You don't need to escape quotes in this syntax.
  4. Nowdoc (since PHP 5.3.0) string syntax works essentially like single quoted strings. The difference is that not even single quotes or backslashes have to be escaped. A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. No parsing is done in nowdoc.

Notes: Single quotes inside of single quotes and double quotes inside of double quotes must be escaped:

$string = 'He said "What\'s up?"';
$string = "He said \"What's up?\"";

Speed:
I would not put too much weight on single quotes being faster than double quotes. They probably are faster in certain situations. Here's an article explaining one manner in which single and double quotes are essentially equally fast since PHP 4.3 (Useless Optimizations toward the bottom, section C). Also, this benchmarks page has a single vs double quote comparison. Most of the comparisons are the same. There is one comparison where double quotes are slower than single quotes.

Changing upload_max_filesize on PHP

Since I just ran in to this problem on a shared host and was unable to add the values to my .htaccess file I thought I'd share my solution.

I made an ini file with the values in it. Simple as that:

Make a file called ".user.ini" and add your values

upload_max_filesize = 150M
post_max_size = 150M

Boom, problem solved.

CodeIgniter - File upload required validation

I found a solution that works exactly how I want.

I changed

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
$this->form_validation->set_rules('userfile', 'Document', 'required');

To

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
if (empty($_FILES['userfile']['name']))
{
    $this->form_validation->set_rules('userfile', 'Document', 'required');
}

Set HTML element's style property in javascript

You can set the style attribute of any element... the trick is that in IE you have to do it differently. (bug 245)

//Standards base browsers
elem.setAttribute('style', styleString);

//Non Standards based IE browser
elem.style.setAttribute('cssText', styleString);

Note that in IE8, in Standards Mode, the first way does work.

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

The canvas element provides a toDataURL method which returns a data: URL that includes the base64-encoded image data in a given format. For example:

var jpegUrl = canvas.toDataURL("image/jpeg");
var pngUrl = canvas.toDataURL(); // PNG is the default

Although the return value is not just the base64 encoded binary data, it's a simple matter to trim off the scheme and the file type to get just the data you want.

The toDataURL method will fail if the browser thinks you've drawn to the canvas any data that was loaded from a different origin, so this approach will only work if your image files are loaded from the same server as the HTML page whose script is performing this operation.

For more information see the MDN docs on the canvas API, which includes details on toDataURL, and the Wikipedia article on the data: URI scheme, which includes details on the format of the URI you'll receive from this call.

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

Using @angular/forms when you use a <form> tag it automatically creates a FormGroup.

For every contained ngModel tagged <input> it will create a FormControl and add it into the FormGroup created above; this FormControl will be named into the FormGroup using attribute name.

Example:

<form #f="ngForm">
    <input type="text" [(ngModel)]="firstFieldVariable" name="firstField">
    <span>{{ f.controls['firstField']?.value }}</span>
</form>

Said this, the answer to your question follows.

When you mark it as standalone: true this will not happen (it will not be added to the FormGroup).

Reference: https://github.com/angular/angular/issues/9230#issuecomment-228116474

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

For Java 8 the following method works:

  1. Form an URI from file URI string
  2. Create a file from the URI (not directly from URI string, absolute URI string are not paths)

Refer, below code snippet

    String fileURiString="file:///D:/etc/MySQL.txt";
    URI fileURI=new URI(fileURiString);
    File file=new File(fileURI);//File file=new File(fileURiString) - will generate exception

    FileInputStream fis=new FileInputStream(file);
    fis.close();

Show only two digit after decimal

Many other answers only do formatting. This approach will return value instead of only print format.

double number1 = 10.123456;
double number2 = (int)(Math.round(number1 * 100))/100.0;
System.out.println(number2);

Lua String replace

Try:

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

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

CSS selector based on element text?

Not with CSS directly, you could set CSS properties via JavaScript based on the internal contents but in the end you would still need to be operating in the definitions of CSS.

Java default constructor

General terminology is that if you don't provide any constructor in your object a no argument constructor is automatically placed which is called default constructor.

If you do define a constructor same as the one which would be placed if you don't provide any it is generally termed as no arguments constructor.Just a convention though as some programmer prefer to call this explicitly defined no arguments constructor as default constructor. But if we go by naming if we are explicitly defining one than it does not make it default.

As per the docs

If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.

Example

public class Dog
{
}

will automatically be modified(by adding default constructor) as follows

public class Dog{
    public Dog() {

    }
} 

and when you create it's object

 Dog myDog = new Dog();

this default constructor is invoked.

How do I format a date in Jinja2?

If you are dealing with a lower level time object (I often just use integers), and don't want to write a custom filter for whatever reason, an approach I use is to pass the strftime function into the template as a variable, where it can be called where you need it.

For example:

import time
context={
    'now':int(time.time()),
    'strftime':time.strftime }  # Note there are no brackets () after strftime
                                # This means we are passing in a function, 
                                # not the result of a function.

self.response.write(jinja2.render_template('sometemplate.html', **context))

Which can then be used within sometemplate.html:

<html>
    <body>
        <p>The time is {{ strftime('%H:%M%:%S',now) }}, and 5 seconds ago it was {{ strftime('%H:%M%:%S',now-5) }}.
    </body>
</html>

How can I stop .gitignore from appearing in the list of untracked files?

After you add the .gitignore file and commit it, it will no longer show up in the "untracked files" list.

git add .gitignore
git commit -m "add .gitignore file"
git status

jQuery: checking if the value of a field is null (empty)

The value of a field can not be null, it's always a string value.

The code will check if the string value is the string "NULL". You want to check if it's an empty string instead:

if ($('#person_data[document_type]').val() != ''){}

or:

if ($('#person_data[document_type]').val().length != 0){}

If you want to check if the element exist at all, you should do that before calling val:

var $d = $('#person_data[document_type]');
if ($d.length != 0) {
  if ($d.val().length != 0 ) {...}
}

Set transparent background of an imageview on Android

Try to use the following code. It will help you in full or more.

  1. A .xml file designed to use this code to set background color:

    android:background="#000000"
    

    or

    android:background="#FFFFFF"
    

    Image is here

    Or you can set it programmatically as well.

  2. Also you can use this code programmatically:

    image.setBackgroundDrawable(getResources().getDrawable(
        R.drawable.llabackground));
    
  3. Also this code for setting the background color as well programmatically:

    image.setBackgroundColor(Color.parseColor("#FFFFFF"));
    
  4. This code for the same programmatically:

    image.setBackgroundColor(getResources().getColor(Color.WHITE));
    

The color depends on your choice of which color you want to use for transparent. Mostly use a white or #FFFFFF color.

Regarding R.drawable.llabackground: This line of code is for your style of the background, like something special or different for your purpose. You can also use this.

How do I pass parameters into a PHP script through a webpage?

Presumably you're passing the arguments in on the command line as follows:

php /path/to/wwwpublic/path/to/script.php arg1 arg2

... and then accessing them in the script thusly:

<?php
// $argv[0] is '/path/to/wwwpublic/path/to/script.php'
$argument1 = $argv[1];
$argument2 = $argv[2];
?>

What you need to be doing when passing arguments through HTTP (accessing the script over the web) is using the query string and access them through the $_GET superglobal:

Go to http://yourdomain.com/path/to/script.php?argument1=arg1&argument2=arg2

... and access:

<?php
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
?>

If you want the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:

EDIT: as pointed out by Cthulhu in the comments, the most direct way to test which environment you're executing in is to use the PHP_SAPI constant. I've updated the code accordingly:

<?php
if (PHP_SAPI === 'cli') {
    $argument1 = $argv[1];
    $argument2 = $argv[2];
}
else {
    $argument1 = $_GET['argument1'];
    $argument2 = $_GET['argument2'];
}
?>

Combine Regexp?

1 + 2 + 4 conditions: starts|ends, but not in the middle

/^@[^@]*@?$|^@?[^@]*@$/

is almost the same that:

/^@?[^@]*@?$/

but this one matches any string without @, sample 'my name is hal9000'

SQL query to find record with ID not in another table

There are basically 3 approaches to that: not exists, not in and left join / is null.

LEFT JOIN with IS NULL

SELECT  l.*
FROM    t_left l
LEFT JOIN
        t_right r
ON      r.value = l.value
WHERE   r.value IS NULL

NOT IN

SELECT  l.*
FROM    t_left l
WHERE   l.value NOT IN
        (
        SELECT  value
        FROM    t_right r
        )

NOT EXISTS

SELECT  l.*
FROM    t_left l
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    t_right r
        WHERE   r.value = l.value
        )

Which one is better? The answer to this question might be better to be broken down to major specific RDBMS vendors. Generally speaking, one should avoid using select ... where ... in (select...) when the magnitude of number of records in the sub-query is unknown. Some vendors might limit the size. Oracle, for example, has a limit of 1,000. Best thing to do is to try all three and show the execution plan.

Specifically form PostgreSQL, execution plan of NOT EXISTS and LEFT JOIN / IS NULL are the same. I personally prefer the NOT EXISTS option because it shows better the intent. After all the semantic is that you want to find records in A that its pk do not exist in B.

Old but still gold, specific to PostgreSQL though: https://explainextended.com/2009/09/16/not-in-vs-not-exists-vs-left-join-is-null-postgresql/

Intellij reformat on file save

IntellIJ 14 && 15: When you are checking in code in Commit changes dialog, tick the Reformat code checkbox, then IntelliJ will reformatting all the code that you are checking in.

Source: www.udemy.com/intellij-idea-secrets-double-your-coding-speed-in-2-hours

Check if String / Record exists in DataTable

Something like this

 string find = "item_manuf_id = 'some value'";
 DataRow[] foundRows = table.Select(find);

How do I remove a MySQL database?

I needed to correct the privileges.REVOKE ALL PRIVILEGES ONlogs.* FROM 'root'@'root'; GRANT ALL PRIVILEGES ONlogs.* TO 'root'@'root'WITH GRANT OPTION;

cell format round and display 2 decimal places

Another way is to use FIXED function, you can specify the number of decimal places but it defaults to 2 if the places aren't specified, i.e.

=FIXED(E5,2)

or just

=FIXED(E5)

Node.js connect only works on localhost

Working for me with this line (simply add --listen when running) :

node server.js -p 3000 -a : --listen 192.168.1.100

Hope it helps...

Leading zeros for Int in Swift

Details

Xcode 9.0.1, swift 4.0

Solutions

Data

import Foundation

let array = [0,1,2,3,4,5,6,7,8]

Solution 1

extension Int {

    func getString(prefix: Int) -> String {
        return "\(prefix)\(self)"
    }

    func getString(prefix: String) -> String {
        return "\(prefix)\(self)"
    }
}

for item in array {
    print(item.getString(prefix: 0))
}

for item in array {
    print(item.getString(prefix: "0x"))
}

Solution 2

for item in array {
    print(String(repeatElement("0", count: 2)) + "\(item)")
}

Solution 3

extension String {

    func repeate(count: Int, string: String? = nil) -> String {

        if count > 1 {
            let repeatedString = string ?? self
            return repeatedString + repeate(count: count-1, string: repeatedString)
        }
        return self
    }
}

for item in array {
    print("0".repeate(count: 3) + "\(item)")
}

How to force a line break on a Javascript concatenated string?

You need to use \n inside quotes.

document.getElementById("address_box").value = (title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4)

\n is called a EOL or line-break, \n is a common EOL marker and is commonly refereed to as LF or line-feed, it is a special ASCII character

Clear git local cache

When you think your git is messed up, you can use this command to do everything up-to-date.

git rm -r --cached .
git add .
git commit -am 'git cache cleared'
git push

Also to revert back last commit use this :

git reset HEAD^ --hard

How does createOrReplaceTempView work in Spark?

SparkSQl support writing programs using Dataset and Dataframe API, along with it need to support sql.

In order to support Sql on DataFrames, first it requires a table definition with column names are required, along with if it creates tables the hive metastore will get lot unnecessary tables, because Spark-Sql natively resides on hive. So it will create a temporary view, which temporarily available in hive for time being and used as any other hive table, once the Spark Context stop it will be removed.

In order to create the view, developer need an utility called createOrReplaceTempView

bad operand types for binary operator "&" java

== has higher precedence than &. You might want to wrap your operations in () to specify how you want your operands to bind to the operators.

((a[0] & 1) == 0)

Similarly for all parts of the if condition.

What is the difference between screenX/Y, clientX/Y and pageX/Y?

clientX/Y refers to relative screen coordinates, for instance if your web-page is long enough then clientX/Y gives clicked point's coordinates location in terms of its actual pixel position while ScreenX/Y gives the ordinates in reference to start of page.

Testing whether a value is odd or even

A simple modification/improvement of Steve Mayne answer!

function isEvenOrOdd(n){
    if(n === parseFloat(n)){
        return isNumber(n) && (n % 2 == 0);
    }
    return false;
}

Note: Returns false if invalid!

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies

For me, it was the missing 'web.config' file. After adding it to the deployed project directory in asp net core 3.1 app, the problem was solved.

SQL Server: How to check if CLR is enabled?

select *
from sys.configurations
where name = 'clr enabled'

Setting the height of a DIV dynamically

Try this simple, specific function:

function resizeElementHeight(element) {
  var height = 0;
  var body = window.document.body;
  if (window.innerHeight) {
      height = window.innerHeight;
  } else if (body.parentElement.clientHeight) {
      height = body.parentElement.clientHeight;
  } else if (body && body.clientHeight) {
      height = body.clientHeight;
  }
  element.style.height = ((height - element.offsetTop) + "px");
}

It does not depend on the current distance from the top of the body being specified (in case your 300px changes).


EDIT: By the way, you would want to call this on that div every time the user changed the browser's size, so you would need to wire up the event handler for that, of course.

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

I had the same issue and I could solve it like this:

1) If your minSdkVersion is set to 21 or a higher value, the only thing you need to do is to set multiDexEnabled in your build.gradle file at the module level, as shown below:

android {
    defaultConfig {
        ...
        minSdkVersion 21 
        targetSdkVersion 28
        multiDexEnabled true
    }
    ...
}

2) However, if your minSdkVersion is set to 20 or less, you should use the MultiDex compatibility library, as follows:

2.1) Modify the module-level build.gradle file to enable MultiDex and add the MultiDex library as dependency, as shown below

android {
    defaultConfig {
        ...
        minSdkVersion 15 
        targetSdkVersion 28
        multiDexEnabled true
    }
    ...
}

dependencies {
  implementation 'com.android.support:multidex:1.0.3'
}

2.2) According to the Application class or not, do one of the following actions:

2.2.1) If you do not cancel the Application class, modify your manifest file to set android: name in the <application> tag as shown below:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
            android:name="android.support.multidex.MultiDexApplication" >
        ...
    </application>
</manifest>

2.2.2) If you cancel the Application class, you must change it to extend MultiDexApplication (if possible) as shown below:

public class MyApplication extends MultiDexApplication { ... }

2.2.3) Also, if you override the Application class and can not change the base class, alternatively you can override the attachBaseContext () method and invoke MultiDex.install (this) to enable MultiDex:

public class MyApplication extends SomeOtherApplication {
  @Override
  protected void attachBaseContext(Context base) {
     super.attachBaseContext(base);
     MultiDex.install(this);
  }
}

Please use this link, it was really useful for me!

Setting timezone to UTC (0) in PHP

You can always check this maintained list to timezones

https://www.php.net/manual/en/function.date.php

Is it possible to GROUP BY multiple columns using MySQL?

If you prefer (I need to apply this) group by two columns at same time, I just saw this point:

SELECT CONCAT (col1, '_', col2) AS Group1 ... GROUP BY Group1

How to list only files and not directories of a directory Bash?

Listing content of some directory, without subdirectories

I like using ls options, for sample:

  • -l use a long listing format
  • -t sort by modification time, newest first
  • -r reverse order while sorting
  • -F, --classify append indicator (one of */=>@|) to entries
  • -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc...

Sometime --color and all others. (See ls --help)

Listing everything but folders

This will show files, symlinks, devices, pipe, sockets etc.

so

find /some/path -maxdepth 1 ! -type d

could be sorted by date easily:

find /some/path -maxdepth 1 ! -type d -exec ls -hltrF {} +

Listing files only:

or

find /some/path -maxdepth 1 -type f

sorted by size:

find /some/path -maxdepth 1 -type f -exec ls -lSF --color {} +

Prevent listing of hidden entries:

To not show hidden entries, where name begin by a dot, you could add ! -name '.*':

find /some/path -maxdepth 1 ! -type d ! -name '.*' -exec ls -hltrF {} +

Then

You could replace /some/path by . to list for current directory or .. for parent directory.

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

As others have already mentioned you are required to provide a default constructor public Employee(){} in your Employee class.

What happens is that the compiler automatically provides a no-argument, default constructor for any class without constructors. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor. In this case you are declaring a constructor in your class Employee therefore you must provide also the no-argument constructor.

Having said that Employee class should look like this:

Your class Employee

import java.util.Date;

public class Employee
{
      private String name, number;
      private Date date;

      public Employee(){} // No-argument Constructor

      public Employee(String name, String number, Date date)
      {
            setName(name);
            setNumber(number);
            setDate(date);
      }

      public void setName(String n)
      {
            name = n;
      }
      public void setNumber(String n)
      {
            number = n;
            // you can check the format here for correctness
      }
      public void setDate(Date d)
      {
            date = d;
      }

      public String getName()
      {
            return name;
      }
      public String getNumber()
      {
            return number;
      }
      public Date getDate()
      {
            return date;
      }
}

Here is the Java Oracle tutorial - Providing Constructors for Your Classes chapter. Go through it and you will have a clearer idea of what is going on.

What is the difference between Amazon SNS and Amazon SQS?

SNS is a distributed publish-subscribe system. Messages are pushed to subscribers as and when they are sent by publishers to SNS.

SQS is distributed queuing system. Messages are not pushed to receivers. Receivers have to poll or pull messages from SQS. Messages can't be received by multiple receivers at the same time. Any one receiver can receive a message, process and delete it. Other receivers do not receive the same message later. Polling inherently introduces some latency in message delivery in SQS unlike SNS where messages are immediately pushed to subscribers. SNS supports several end points such as email, SMS, HTTP end point and SQS. If you want unknown number and type of subscribers to receive messages, you need SNS.

You don't have to couple SNS and SQS always. You can have SNS send messages to email, SMS or HTTP end point apart from SQS. There are advantages to coupling SNS with SQS. You may not want an external service to make connections to your hosts (a firewall may block all incoming connections to your host from outside).

Your end point may just die because of heavy volume of messages. Email and SMS maybe not your choice of processing messages quickly. By coupling SNS with SQS, you can receive messages at your pace. It allows clients to be offline, tolerant to network and host failures. You also achieve guaranteed delivery. If you configure SNS to send messages to an HTTP end point or email or SMS, several failures to send message may result in messages being dropped.

SQS is mainly used to decouple applications or integrate applications. Messages can be stored in SQS for a short duration of time (maximum 14 days). SNS distributes several copies of messages to several subscribers. For example, let’s say you want to replicate data generated by an application to several storage systems. You could use SNS and send this data to multiple subscribers, each replicating the messages it receives to different storage systems (S3, hard disk on your host, database, etc.).

Overflow Scroll css is not working in the div

For Angular2 + Material2 + Sidenav, you'll need to do the following:

 ngAfterViewInit() {
   this.element.nativeElement.getElementsByClassName('md-sidenav-content')[0].style.overflow = 'hidden'; 
  }

What does the "no version information available" error from linux dynamic linker mean?

Fwiw, I had this problem when running check_nrpe on a system that had the zenoss monitoring system installed. To add to the confusion, it worked fine as root user but not as zenoss user.

I found out that the zenoss user had an LD_LIBRARY_PATH that caused it to use zenoss libraries, which issue these warnings. Ie:

root@monitoring:$ echo $LD_LIBRARY_PATH

su - zenoss
zenoss@monitoring:/root$ echo $LD_LIBRARY_PATH
/usr/local/zenoss/python/lib:/usr/local/zenoss/mysql/lib:/usr/local/zenoss/zenoss/lib:/usr/local/zenoss/common/lib::
zenoss@monitoring:/root$ /usr/lib/nagios/plugins/check_nrpe -H 192.168.61.61 -p 6969 -c check_mq
/usr/lib/nagios/plugins/check_nrpe: /usr/local/zenoss/common/lib/libcrypto.so.0.9.8: no version information available (required by /usr/lib/libssl.so.0.9.8)
(...)
zenoss@monitoring:/root$ LD_LIBRARY_PATH= /usr/lib/nagios/plugins/check_nrpe -H 192.168.61.61 -p 6969 -c check_mq
(...)

So anyway, what I'm trying to say: check your variables like LD_LIBRARY_PATH, LD_PRELOAD etc as well.

How to change value of a request parameter in laravel

Try to:

$requestData = $request->all();
$requestData['img'] = $img;

Another way to do it:

$request->merge(['img' => $img]);

Thanks to @JoelHinz for this.

If you want to add or overwrite nested data:

$data['some']['thing'] = 'value';
$request->merge($data);

If you do not inject Request $request object, you can use the global request() helper or \Request:: facade instead of $request

Do a "git export" (like "svn export")?

I just want to point out that in the case that you are

  1. exporting a sub folder of the repository (that's how I used to use SVN export feature)
  2. are OK with copying everything from that folder to the deployment destination
  3. and since you already have a copy of the entire repository in place.

Then you can just use cp foo [destination] instead of the mentioned git-archive master foo | -x -C [destination].

JSON encode MySQL results

$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');

while($row = mysql_fetch_array($sql_results))
{
    $subArray[location_id]=$row['location'];  //location_id is key and $row['location'] is value which come fron database.
    $subArray[x]=$row['x'];
    $subArray[y]=$row['y'];


 $array[] =  $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';

Clear and refresh jQuery Chosen dropdown list

$("#idofBtn").click(function(){
        $('#idofdropdown').empty(); //remove all child nodes
        var newOption = $('<option value="1">test</option>');
        $('#idofdropdown').append(newOption);
        $('#idofdropdown').trigger("chosen:updated");
    });

Python vs Bash - In which kind of tasks each one outruns the other performance-wise?

Performance wise both can do equally the same, so the question becomes which saves more development time?

Bash relies on calling other commands, and piping them for creating new ones. This has the advantage that you can quickly create new programs just with the code borrowed from other people, no matter what programming language they used.

This also has the side effect of resisting change in sub-commands pretty well, as the interface between them is just plain text.

Additionally Bash is very permissive on how you can write on it. This means it will work well for a wider variety of context, but it also relies on the programmer having the intention of coding in a clean safe manner. Otherwise Bash won't stop you from building a mess.

Python is more structured on style, so a messy programmer won't be as messy. It will also work on operating systems outside Linux, making it instantly more appropriate if you need that kind of portability.

But it isn't as simple for calling other commands. So if your operating system is Unix most likely you will find that developing on Bash is the fastest way to develop.

When to use Bash:

  • It's a non graphical program, or the engine of a graphical one.
  • It's only for Unix.

When to use Python:

  • It's a graphical program.
  • It shall work on Windows.

Editor does not contain a main type

The correct answer is: the Scala library needs to before the JRE library in the buildpath.

Go to Java Buildpath > Order and Export and move Scala library to the top

How to reload or re-render the entire page using AngularJS

Well maybe you forgot to add "$route" when declaring the dependencies of your Controller:

app.controller('NameCtrl', ['$scope','$route', function($scope,$route) {   
   // $route.reload(); Then this should work fine.
}]);

InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately

The docs give a fair indicator of what's required., however requests allow us to skip a few steps:

You only need to install the security package extras (thanks @admdrew for pointing it out)

$ pip install requests[security]

or, install them directly:

$ pip install pyopenssl ndg-httpsclient pyasn1

Requests will then automatically inject pyopenssl into urllib3


If you're on ubuntu, you may run into trouble installing pyopenssl, you'll need these dependencies:

$ apt-get install libffi-dev libssl-dev

SQL Server Management Studio, how to get execution time down to milliseconds

Turn on Client Statistics by doing one of the following:

  • Menu: Query > Include client Statistics
  • Toolbar: Click the button (next to Include Actual Execution Time)
  • Keyboard: Shift-Alt-S

Then you get a new tab which records the timings, IO data and rowcounts etc for (up to) the last 10 exections (plus averages!):

enter image description here

Create a button with rounded border

If you don't want to use OutlineButton and want to stick to normal RaisedButton, you can wrap your button in ClipRRect or ClipOval like:

ClipRRect(
  borderRadius: BorderRadius.circular(40),
  child: RaisedButton(
    child: Text("Button"),
    onPressed: () {},
  ),
),

Using $window or $location to Redirect in AngularJS

You have to put:

<html ng-app="urlApp" ng-controller="urlCtrl">

This way the angular function can access into "window" object

combining two string variables

IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:

the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog.'])

Edit: Note that join wants an iterable (e.g. a list) as its single argument.

List of standard lengths for database fields

If you need to consider localisation (for those of us outside the US!) and it's possible in your environment, I'd suggest:

Define data types for each component of the name - NOTE: some cultures have more than two names! Then have a type for the full name,

Then localisation becomes simple (as far as names are concerned).

The same applies to addresses, BTW - different formats!

Make cross-domain ajax JSONP request with jQuery

alert(xml.data[0].city);

use xml.data["Data"][0].city instead

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

Tracking it down

At first I thought this was a coercion bug where null was getting coerced to "null" and a test of "null" == null was passing. It's not. I was close, but so very, very wrong. Sorry about that!

I've since done lots of fiddling on wonderfl.net and tracing through the code in mx.rpc.xml.*. At line 1795 of XMLEncoder (in the 3.5 source), in setValue, all of the XMLEncoding boils down to

currentChild.appendChild(xmlSpecialCharsFilter(Object(value)));

which is essentially the same as:

currentChild.appendChild("null");

This code, according to my original fiddle, returns an empty XML element. But why?

Cause

According to commenter Justin Mclean on bug report FLEX-33664, the following is the culprit (see last two tests in my fiddle which verify this):

var thisIsNotNull:XML = <root>null</root>;
if(thisIsNotNull == null){
    // always branches here, as (thisIsNotNull == null) strangely returns true
    // despite the fact that thisIsNotNull is a valid instance of type XML
}

When currentChild.appendChild is passed the string "null", it first converts it to a root XML element with text null, and then tests that element against the null literal. This is a weak equality test, so either the XML containing null is coerced to the null type, or the null type is coerced to a root xml element containing the string "null", and the test passes where it arguably should fail. One fix might be to always use strict equality tests when checking XML (or anything, really) for "nullness."

Solution

The only reasonable workaround I can think of, short of fixing this bug in every damn version of ActionScript, is to test fields for "null" and escape them as CDATA values.

CDATA values are the most appropriate way to mutate an entire text value that would otherwise cause encoding/decoding problems. Hex encoding, for instance, is meant for individual characters. CDATA values are preferred when you're escaping the entire text of an element. The biggest reason for this is that it maintains human readability.

Instagram API: How to get all user media?

Use the best recursion function for getting all posts of users.

<?php
    set_time_limit(0);
    function getPost($url,$i) 
    {
        static $posts=array();  
        $json=file_get_contents($url);
        $data = json_decode($json);
        $ins_links=array();
        $page=$data->pagination;
        $pagearray=json_decode(json_encode($page),true);
        $pagecount=count($pagearray);

        foreach( $data->data as $user_data )
        {
            $posts[$i++]=$user_data->link;
        }

        if($pagecount>0)
            return getPost($page->next_url,$i);
        else
            return $posts;
    }
    $posts=getPost("https://api.instagram.com/v1/users/CLIENT-ACCOUNT-NUMBER/media/recent?client_id=CLIENT-ID&count=33",0);

    print_r($posts);

?>

ContractFilter mismatch at the EndpointDispatcher exception

If you are calling WCF method you should include interface in Header.

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url);
if (Url.Contains(".svc"))
{
    isWCFService = true;
    req.Headers.Add("SOAPAction", "http://tempuri.org/WCF_INterface/GetAPIKeys");
}
else 
{
    req.Headers.Add("SOAPAction", "\"http://tempuri.org/" + asmxMethodName+ "\"");
}

How to use onResume()?

Restarting the app will call OnCreate().

Continuing the app when it is paused will call OnResume(). From the official docs at https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle here's a diagram of the activity lifecycle.

the Android activity lifecycle, from https://developer.android.com/images/activity_lifecycle.png on https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

How to append output to the end of a text file

Use >> instead of > when directing output to a file:

your_command >> file_to_append_to

If file_to_append_to does not exist, it will be created.

Example:

$ echo "hello" > file
$ echo "world" >> file
$ cat file 
hello
world

Browse files and subfolders in Python

Slightly altered version of Sven Marnach's solution..


import os

folder_location = 'C:\SomeFolderName' file_list = create_file_list(folder_location)

def create_file_list(path): return_list = []

for filenames in os.walk(path): for file_list in filenames: for file_name in file_list: if file_name.endswith((".txt")): return_list.append(file_name) return return_list

Collections.sort with multiple fields

Here is a full example comparing 2 fields in an object, one String and one int, also using Collator to sort.

public class Test {

    public static void main(String[] args) {

        Collator myCollator;
        myCollator = Collator.getInstance(Locale.US);

        List<Item> items = new ArrayList<Item>();

        items.add(new Item("costrels", 1039737, ""));
        items.add(new Item("Costs", 1570019, ""));
        items.add(new Item("costs", 310831, ""));
        items.add(new Item("costs", 310832, ""));

        Collections.sort(items, new Comparator<Item>() {
            @Override
            public int compare(final Item record1, final Item record2) {
                int c;
                //c = record1.item1.compareTo(record2.item1); //optional comparison without Collator                
                c = myCollator.compare(record1.item1, record2.item1);
                if (c == 0) 
                {
                    return record1.item2 < record2.item2 ? -1
                            :  record1.item2 > record2.item2 ? 1
                            : 0;
                }
                return c;
            }
        });     

        for (Item item : items)
        {
            System.out.println(item.item1);
            System.out.println(item.item2);
        }       

    }

    public static class Item
    {
        public String item1;
        public int item2;
        public String item3;

        public Item(String item1, int item2, String item3)
        {
            this.item1 = item1;
            this.item2 = item2;
            this.item3 = item3;
        }       
    }

}

Output:

costrels 1039737

costs 310831

costs 310832

Costs 1570019

Xcode doesn't see my iOS device but iTunes does

To others who might have the same issue and the answers above don't work: Make sure that the iOS version installed on your device matches the iOS SDK version you have installed on your mac. If these don't match you are unable to build to the device.

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

How to set a default value in react-select

To auto-select the value of in select.

enter image description here

<div className="form-group">
    <label htmlFor="contactmethod">Contact Method</label>
    <select id="contactmethod" className="form-control"  value={this.state.contactmethod || ''} onChange={this.handleChange} name="contactmethod">
    <option value='Email'>URL</option>
    <option value='Phone'>Phone</option>
    <option value="SMS">SMS</option>
    </select>
</div>

Use the value attribute in the select tag

value={this.state.contactmethod || ''}

the solution is working for me.

INSERT INTO from two different server database

USE [mydb1]

SELECT *
INTO mytable1
FROM OPENDATASOURCE (
        'SQLNCLI'
        ,'Data Source=XXX.XX.XX.XXX;Initial Catalog=mydb2;User ID=XXX;Password=XXXX'
        ).[mydb2].dbo.mytable2
    /*  steps - 
            1-  [mydb1] means our opend connection database 
            2-  mytable1 means create copy table in mydb1 database where we want insert record
            3-  XXX.XX.XX.XXX - another server name.
            4-  mydb2 another server database.
            5-  write User id and Password of another server credential
            6-  mytable2 is another server table where u fetch record from it. */

How can I get a vertical scrollbar in my ListBox?

I added a "Height" to my ListBox and it added the scrollbar nicely.

SQL Server JOIN missing NULL values

Try using ISNULL function:

SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 
INNER JOIN Table2
   ON Table1.Col1 = Table2.Col1 
   AND ISNULL(Table1.Col2, 'ZZZZ') = ISNULL(Table2.Col2,'ZZZZ')

Where 'ZZZZ' is some arbitrary value never in the table.

How to convert JSON object to JavaScript array?

function json2array(json){
    var result = [];
    var keys = Object.keys(json);
    keys.forEach(function(key){
        result.push(json[key]);
    });
    return result;
}

See this complete explanation: http://book.mixu.net/node/ch5.html

How to create a directive with a dynamic template in AngularJS?

You should move your switch into the template by using the 'ng-switch' directive:

module.directive('testForm', function() {
    return {
        restrict: 'E',
        controllerAs: 'form',
        controller: function ($scope) {
            console.log("Form controller initialization");
            var self = this;
            this.fields = {};
            this.addField = function(field) {
                console.log("New field: ", field);
                self.fields[field.name] = field;
            };
        }
    }
});

module.directive('formField', function () {
    return {
        require: "^testForm",
        template:
            '<div ng-switch="field.fieldType">' +
            '    <span>{{title}}:</span>' +
            '    <input' +
            '        ng-switch-when="text"' +
            '        name="{{field.name}}"' +
            '        type="text"' +
            '        ng-model="field.value"' +
            '    />' +
            '    <select' +
            '        ng-switch-when="select"' +
            '        name="{{field.name}}"' +
            '        ng-model="field.value"' +
            '        ng-options="option for option in options">' +
            '        <option value=""></option>' +
            '    </select>' +
            '</div>',
        restrict: 'E',
        replace: true,
        scope: {
            fieldType: "@",
            title: "@",
            name: "@",
            value: "@",
            options: "=",
        },
        link: function($scope, $element, $attrs, form) {
            $scope.field = $scope;
            form.addField($scope);
        }
    };
});

It can be use like this:

<test-form>
    <div>
        User '{{!form.fields.email.value}}' will be a {{!form.fields.role.value}}
    </div>
    <form-field title="Email" name="email" field-type="text" value="[email protected]"></form-field>
    <form-field title="Role" name="role" field-type="select" options="['Cook', 'Eater']"></form-field>
    <form-field title="Sex" name="sex" field-type="select" options="['Awesome', 'So-so', 'awful']"></form-field>
</test-form>

How to deep watch an array in angularjs?

In my case, I needed to watch a service, which contains an address object also watched by several other controllers. I was stuck in a loop until I added the 'true' parameter, which seems to be the key to success when watching objects.

$scope.$watch(function() {
    return LocationService.getAddress();
}, function(address) {
    //handle address object
}, true);

Why do I get "warning longer object length is not a multiple of shorter object length"?

I had a similar issue and using %in% operator instead of the == (equality) operator was the solution:

# %in%

Hope it helps.

Get filename from input [type='file'] using jQuery

var file = $('#YOURID > input[type="file"]'); file.value; // filename will be,

In Chrome, it will be something like C:\fakepath\FILE_NAME or undefined if no file was selected.

It is a limitation or intention that the browser does not reveal the file structure of the local machine.

How to escape regular expression special characters using javascript?

With \ you escape special characters

Escapes special characters to literal and literal characters to special.

E.g: /\(s\)/ matches '(s)' while /(\s)/ matches any whitespace and captures the match.

Source: http://www.javascriptkit.com/javatutors/redev2.shtml