Programs & Examples On #Jagged arrays

A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays."

Using lodash to compare jagged arrays (items existence without order)

Edit: I missed the multi-dimensional aspect of this question, so I'm leaving this here in case it helps people compare one-dimensional arrays

It's an old question, but I was having issues with the speed of using .sort() or sortBy(), so I used this instead:

function arraysContainSameStrings(array1: string[], array2: string[]): boolean {
  return (
    array1.length === array2.length &&
    array1.every((str) => array2.includes(str)) &&
    array2.every((str) => array1.includes(str))
  )
}

It was intended to fail fast, and for my purposes works fine.

How can I declare a two dimensional string array?

string[,] Tablero = new string[3,3];

You can also instantiate it in the same line with array initializer syntax as follows:

string[,] Tablero = new string[3, 3] {{"a","b","c"},
                                      {"d","e","f"}, 
                                      {"g","h","i"} };

What are the differences between a multidimensional array and an array of arrays in C#?

Multi-dimension arrays are (n-1)-dimension matrices.

So int[,] square = new int[2,2] is square matrix 2x2, int[,,] cube = new int [3,3,3] is a cube - square matrix 3x3. Proportionality is not required.

Jagged arrays are just array of arrays - an array where each cell contains an array.

So MDA are proportional, JD may be not! Each cell can contains an array of arbitrary length!

Javascript - remove an array item by value

If you're going to be using this often (and on multiple arrays), extend the Array object to create an unset function.

Array.prototype.unset = function(value) {
    if(this.indexOf(value) != -1) { // Make sure the value exists
        this.splice(this.indexOf(value), 1);
    }   
}

tag_story.unset(56)

Does Google Chrome work with Selenium IDE (as Firefox does)?

While you cannot record tests using the Selenium IDE in Chrome (or any other browser other than FF), you can run them (from the IDE) in Chrome, IE and other browsers using the Webdriver playback feature of Selenium 2 IDE. Tests will need to be recorded and launched from FF - Chrome will launch before the first step of the test is executed. Instructions for setup and test execution are here and here. You will need to install Selenium 2 IDE (if you haven't already done so) and the Chrome Webdriver Server executable - both are available for download on the Selenium HQ website.

NOTE: If the above meets your needs, you may also want to consider just converting all your tests to Selenium Webdriver (which means they would be all code and no longer run from the Selenium IDE). This would be a better solution from the perspective of test maintenance and simplicity of execution. The Selenium documentation (on the Selenium website) has more information on the process to convert Selenium IDE tests to Webdriver.

How to add text inside the doughnut chart using Chart.js?

This is based on Cmyker's update for Chart.js 2. (posted as another answer as I can't comment yet)

I had an issue with the text alignment on Chrome when the legend is displayed as the chart height does not include this so it's not aligned correctly in the middle. Fixed this by accounting for this in the calculation of fontSize and textY.

I calculated percentage inside the method rather than a set value as I have multiple of these on the page. Assumptions are that your chart only has 2 values (otherwise what is the percentage of? and that the first is the one you want to show the percentage for. I have a bunch of other charts too so I do a check for type = doughnut. I'm only using doughnuts to show percentages so it works for me.

Text color seems a bit hit and miss depending on what order things run in etc so I ran into an issue when resizing that the text would change color (between black and the primary color in one case, and secondary color and white in another) so I "save" whatever the existing fill style was, draw the text (in the color of the primary data) then restore the old fill style. (Preserving the old fill style doesn't seem needed but you never know.)

https://jsfiddle.net/g733tj8h/

Chart.pluginService.register({
  beforeDraw: function(chart) {
    var width = chart.chart.width,
        height = chart.chart.height,
        ctx = chart.chart.ctx,
        type = chart.config.type;

    if (type == 'doughnut')
    {
      var percent = Math.round((chart.config.data.datasets[0].data[0] * 100) /
                    (chart.config.data.datasets[0].data[0] +
                    chart.config.data.datasets[0].data[1]));
      var oldFill = ctx.fillStyle;
      var fontSize = ((height - chart.chartArea.top) / 100).toFixed(2);

      ctx.restore();
      ctx.font = fontSize + "em sans-serif";
      ctx.textBaseline = "middle"

      var text = percent + "%",
          textX = Math.round((width - ctx.measureText(text).width) / 2),
          textY = (height + chart.chartArea.top) / 2;

      ctx.fillStyle = chart.config.data.datasets[0].backgroundColor[0];
      ctx.fillText(text, textX, textY);
      ctx.fillStyle = oldFill;
      ctx.save();
    }
  }
});

_x000D_
_x000D_
var data = {_x000D_
  labels: ["Red","Blue"],_x000D_
  datasets: [_x000D_
    {_x000D_
      data: [300, 50],_x000D_
      backgroundColor: ["#FF6384","#36A2EB"],_x000D_
    }]_x000D_
};_x000D_
_x000D_
Chart.pluginService.register({_x000D_
  beforeDraw: function(chart) {_x000D_
    var width = chart.chart.width,_x000D_
        height = chart.chart.height,_x000D_
        ctx = chart.chart.ctx,_x000D_
        type = chart.config.type;_x000D_
_x000D_
    if (type == 'doughnut')_x000D_
    {_x000D_
     var percent = Math.round((chart.config.data.datasets[0].data[0] * 100) /_x000D_
                    (chart.config.data.datasets[0].data[0] +_x000D_
                    chart.config.data.datasets[0].data[1]));_x000D_
   var oldFill = ctx.fillStyle;_x000D_
      var fontSize = ((height - chart.chartArea.top) / 100).toFixed(2);_x000D_
      _x000D_
      ctx.restore();_x000D_
      ctx.font = fontSize + "em sans-serif";_x000D_
      ctx.textBaseline = "middle"_x000D_
_x000D_
      var text = percent + "%",_x000D_
          textX = Math.round((width - ctx.measureText(text).width) / 2),_x000D_
          textY = (height + chart.chartArea.top) / 2;_x000D_
   _x000D_
      ctx.fillStyle = chart.config.data.datasets[0].backgroundColor[0];_x000D_
      ctx.fillText(text, textX, textY);_x000D_
      ctx.fillStyle = oldFill;_x000D_
      ctx.save();_x000D_
    }_x000D_
  }_x000D_
});_x000D_
_x000D_
var myChart = new Chart(document.getElementById('myChart'), {_x000D_
  type: 'doughnut',_x000D_
  data: data,_x000D_
  options: {_x000D_
   responsive: true,_x000D_
    legend: {_x000D_
      display: true_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.js"></script>_x000D_
<canvas id="myChart"></canvas>
_x000D_
_x000D_
_x000D_

SQL Statement with multiple SETs and WHEREs

Nope, this is how you do it:

UPDATE table SET ID = 111111259 WHERE ID = 2555

UPDATE table SET ID = 111111261 WHERE ID = 2724

UPDATE table SET ID = 111111263 WHERE ID = 2021

UPDATE table SET ID = 111111264 WHERE ID = 2017

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

Place the following in the CODE MODULE of a WORKSHEET to track the last value for every cell in the used range:

Option Explicit

Private r As Range
Private Const d = "||"

Public Function ValueLast(r As Range)
    On Error Resume Next
    ValueLast = Split(r.ID, d)(1)
End Function

Private Sub Worksheet_Activate()
    For Each r In Me.UsedRange: Record r: Next
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    For Each r In Target: Record r: Next
End Sub

Private Sub Record(r)
    r.ID = r.Value & d & Split(r.ID, d)(0)
End Sub

And that's it.

This solution uses the obscure and almost never used Range.ID property, which allows the old values to persist when the workbook is saved and closed.

At any time you can get at the old value of a cell and it will indeed be different than a new current value:

With Sheet1
    MsgBox .[a1].Value
    MsgBox .ValueLast(.[a1])
End With

MySQL high CPU usage

If this server is visible to the outside world, It's worth checking if it's having lots of requests to connect from the outside world (i.e. people trying to break into it)

Fastest Way to Find Distance Between Two Lat/Long Points

The full code with details about how to install as MySQL plugin are here: https://github.com/lucasepe/lib_mysqludf_haversine

I posted this last year as comment. Since kindly @TylerCollier suggested me to post as answer, here it is.

Another way is to write a custom UDF function that returns the haversine distance from two points. This function can take in input:

lat1 (real), lng1 (real), lat2 (real), lng2 (real), type (string - optinal - 'km', 'ft', 'mi')

So we can write something like this:

SELECT id, name FROM MY_PLACES WHERE haversine_distance(lat1, lng1, lat2, lng2) < 40;

to fetch all records with a distance less then 40 kilometers. Or:

SELECT id, name FROM MY_PLACES WHERE haversine_distance(lat1, lng1, lat2, lng2, 'ft') < 25;

to fetch all records with a distance less then 25 feet.

The core function is:

double
haversine_distance( UDF_INIT* initid, UDF_ARGS* args, char* is_null, char *error ) {
    double result = *(double*) initid->ptr;
    /*Earth Radius in Kilometers.*/ 
    double R = 6372.797560856;
    double DEG_TO_RAD = M_PI/180.0;
    double RAD_TO_DEG = 180.0/M_PI;
    double lat1 = *(double*) args->args[0];
    double lon1 = *(double*) args->args[1];
    double lat2 = *(double*) args->args[2];
    double lon2 = *(double*) args->args[3];
    double dlon = (lon2 - lon1) * DEG_TO_RAD;
    double dlat = (lat2 - lat1) * DEG_TO_RAD;
    double a = pow(sin(dlat * 0.5),2) + 
        cos(lat1*DEG_TO_RAD) * cos(lat2*DEG_TO_RAD) * pow(sin(dlon * 0.5),2);
    double c = 2.0 * atan2(sqrt(a), sqrt(1-a));
    result = ( R * c );
    /*
     * If we have a 5th distance type argument...
     */
    if (args->arg_count == 5) {
        str_to_lowercase(args->args[4]);
        if (strcmp(args->args[4], "ft") == 0) result *= 3280.8399;
        if (strcmp(args->args[4], "mi") == 0) result *= 0.621371192;
    }

    return result;
}

Trying to use Spring Boot REST to Read JSON String from POST

I think the simplest/handy way to consuming JSON is using a Java class that resembles your JSON: https://stackoverflow.com/a/6019761

But if you can't use a Java class you can use one of these two solutions.

Solution 1: you can do it receiving a Map<String, Object> from your controller:

@RequestMapping(
    value = "/process", 
    method = RequestMethod.POST)
public void process(@RequestBody Map<String, Object> payload) 
    throws Exception {

  System.out.println(payload);

}

Using your request:

curl -H "Accept: application/json" -H "Content-type: application/json" \
-X POST -d '{"name":"value"}' http://localhost:8080/myservice/process

Solution 2: otherwise you can get the POST payload as a String:

@RequestMapping(
    value = "/process", 
    method = RequestMethod.POST,
    consumes = "text/plain")
public void process(@RequestBody String payload) throws Exception {

  System.out.println(payload);

}

Then parse the string as you want. Note that must be specified consumes = "text/plain" on your controller. In this case you must change your request with Content-type: text/plain:

curl -H "Accept: application/json" -H "Content-type: text/plain" -X POST \
-d '{"name":"value"}' http://localhost:8080/myservice/process

Which Eclipse version should I use for an Android app?

The easiest solution is to download the Android SDK bundle:

http://developer.android.com/sdk/installing/bundle.html

The ADT Bundle provides everything you need to start developing apps, including a version of the Eclipse IDE with built-in ADT (Android Developer Tools) to streamline your Android app development.

How can I change the text inside my <span> with jQuery?

$('#abc span').html('A new text for the span.');

Broken references in Virtualenvs

All the answers are great here, I tried a couple of solutions mentioned above by Ryan, Chris and couldn't resolve the issue, so had to follow a quick and dirty way.

  1. rm -rf <project dir> (or mv <project dir> <backup projct dir> if you want to keep a backup)
  2. git clone <project git url>
  3. Move on!

Nothing novel here, but it makes life easier!

RegEx match open tags except XHTML self-contained tags

This may do:

<.*?[^/]>

Or without the ending tags:

<[^/].*?[^/]>

What's with the flame wars on HTML parsers? HTML parsers must parse (and rebuild!) the entire document before it can categorize your search. Regular expressions may be a faster / elegant in certain circumstances. My 2 cents...

How to pass macro definition from "make" command line arguments (-D) to C source code?

Because of low reputation, I cannot comment the accepted answer.

I would like to mention the predefined variable CPPFLAGS. It might represent a better fit than CFLAGS or CXXFLAGS, since it is described by the GNU Make manual as:

Extra flags to give to the C preprocessor and programs that use it (the C and Fortran compilers).

Examples of built-in implicit rules that use CPPFLAGS

  • n.o is made automatically from n.c with a recipe of the form:
    • $(CC) $(CPPFLAGS) $(CFLAGS) -c
  • n.o is made automatically from n.cc, n.cpp, or n.C with a recipe of the form:
    • $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c

One would use the command make CPPFLAGS=-Dvar=123 to define the desired macro.

More info

What is the default value for enum variable?

You can use this snippet :-D

using System;
using System.Reflection;

public static class EnumUtils
{
    public static T GetDefaultValue<T>()
        where T : struct, Enum
    {
        return (T)GetDefaultValue(typeof(T));
    }

    public static object GetDefaultValue(Type enumType)
    {
        var attribute = enumType.GetCustomAttribute<DefaultValueAttribute>(inherit: false);
        if (attribute != null)
            return attribute.Value;

        var innerType = enumType.GetEnumUnderlyingType();
        var zero = Activator.CreateInstance(innerType);
        if (enumType.IsEnumDefined(zero))
            return zero;

        var values = enumType.GetEnumValues();
        return values.GetValue(0);
    }
}

Example:

using System;

public enum Enum1
{
    Foo,
    Bar,
    Baz,
    Quux
}
public enum Enum2
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 0
}
public enum Enum3
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}
[DefaultValue(Enum4.Bar)]
public enum Enum4
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}

public static class Program 
{
    public static void Main() 
    {
        var defaultValue1 = EnumUtils.GetDefaultValue<Enum1>();
        Console.WriteLine(defaultValue1); // Foo

        var defaultValue2 = EnumUtils.GetDefaultValue<Enum2>();
        Console.WriteLine(defaultValue2); // Quux

        var defaultValue3 = EnumUtils.GetDefaultValue<Enum3>();
        Console.WriteLine(defaultValue3); // Foo

        var defaultValue4 = EnumUtils.GetDefaultValue<Enum4>();
        Console.WriteLine(defaultValue4); // Bar
    }
}

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

In my case setting the referenced object to NULL in my object before the merge o save method solve the problem, in my case the referenced object was catalog, that doesn't need to be saved, because in some cases I don't have it even.

    fisEntryEB.setCatStatesEB(null);

    (fisEntryEB) getSession().merge(fisEntryEB);

How to clear all input fields in bootstrap modal when clicking data-dismiss button?

I did it in the following way.

  1. Give your form element (which is placed inside the modal) anID.
  2. Assign your data-dimiss an ID.
  3. Call the onclick method when data-dimiss is being clicked.
  4. Use the trigger() function on the form element. I am adding the code example with it.

     $(document).ready(function()
         {
        $('#mod_cls').on('click', function () {
      $('#Q_A').trigger("reset");
        console.log($('#Q_A'));
     })
      });
    

    <div class="modal fade " id="myModal2" role="dialog" >
    <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" ID="mod_cls" data-dismiss="modal">&times;</button>
      <h4 class="modal-title" >Ask a Question</h4>
    </div>
    <div class="modal-body">
      <form role="form" action="" id="Q_A" method="POST">
        <div class="form-group">
          <label for="Question"></label>
          <input type="text" class="form-control" id="question" name="question">
        </div>

      <div class="form-group">
          <label for="sub_name">Subject*</label>
          <input type="text" class="form-control" id="sub_name" NAME="sub_name">
        </div>
        <div class="form-group">
          <label for="chapter_name">Chapter*</label>
          <input type="text" class="form-control" id="chapter_name" NAME="chapter_name">
        </div>
        <button type="submit" class="btn btn-default btn-success btn-block"> Post</button>
                               </form>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button><!--initially the visibility of "upload another note" is hidden ,but it becomes visible as soon as one note is uploaded-->
      </div>
      </div>
      </div>
      </div>

Hope this will help others as I was struggling with it since a long time.

A transport-level error has occurred when receiving results from the server

I had the same issue. I solved it, truncating the SQL Server LOG. Check doing that, and then tell us, if this solution helped you.

How do I parse command line arguments in Java?

Yeap.

I think you're looking for something like this: http://commons.apache.org/cli

The Apache Commons CLI library provides an API for processing command line interfaces.

How to read embedded resource text file

When you added the file to the resources, you should select its Access Modifiers as public than you can make something like following.

byte[] clistAsByteArray = Properties.Resources.CLIST01;

CLIST01 is the name of the embedded file.

Actually you can go to the resources.Designer.cs and see what is the name of the getter.

PostgreSQL wildcard LIKE for any of a list of words

You can use Postgres' SIMILAR TO operator which supports alternations, i.e.

select * from table where lower(value) similar to '%(foo|bar|baz)%';

Why should hash functions use a prime number modulus?

"The nature of math" regarding prime power moduli is that they are one building block of a finite field. The other two building blocks are an addition and a multiplication operation. The special property of prime moduli is that they form a finite field with the "regular" addition and multiplication operations, just taken to the modulus. This means every multiplication maps to a different integer modulo the prime, so does every addition.

Prime moduli are advantageous because:

  • They give the most freedom when choosing the secondary multiplier in secondary hashing, all multipliers except 0 will end up visiting all elements exactly once
  • If all hashes are less than the modulus there will be no collisions at all
  • Random primes mix better than power of two moduli and compress the information of all the bits not just a subset

They however have a big downside, they require an integer division, which takes many (~ 15-40) cycles, even on a modern CPU. With around half the computation one can make sure the hash is mixed up very well. Two multiplications and xorshift operations will mix better than a prime moudulus. Then we can use whatever hash table size and hash reduction is fastest, giving 7 operations in total for power of 2 table sizes and around 9 operations for arbitrary sizes.

I recently looked at many of the fastest hash table implementations and most of them don't use prime moduli.

The distribution of the hash table indices are mainly dependent on the hash function in use. A prime modulus can't fix a bad hash function and a good hash function does not benefit from a prime modulus. There are cases where they can be advantageous however. It can mend a half-bad hash function for example.

how get yesterday and tomorrow datetime in c#

The trick is to use "DateTime" to manipulate dates; only use integers and strings when you need a "final result" from the date.

For example (pseudo code):

  1. Get "DateTime tomorrow = Now + 1"

  2. Determine date, day of week, day of month - whatever you want - of the resulting date.

Enter key in textarea

You could do something like this:

<body>

<textarea id="txtArea" onkeypress="onTestChange();"></textarea>

<script>
function onTestChange() {
    var key = window.event.keyCode;

    // If the user has pressed enter
    if (key === 13) {
        document.getElementById("txtArea").value = document.getElementById("txtArea").value + "\n*";
        return false;
    }
    else {
        return true;
    }
}
</script>

</body>

Although the new line character feed from pressing enter will still be there, but its a start to getting what you want.

How to add ASP.NET 4.0 as Application Pool on IIS 7, Windows 7

Chances are you need to install .NET 4 (Which will also create a new AppPool for you)

First make sure you have IIS installed then perform the following steps:

  1. Open your command prompt (Windows + R) and type cmd and press ENTER
    You may need to start this as an administrator if you have UAC enabled.
    To do so, locate the exe (usually you can start typing with Start Menu open), right click and select "Run as Administrator"
  2. Type cd C:\Windows\Microsoft.NET\Framework\v4.0.30319\ and press ENTER.
  3. Type aspnet_regiis.exe -ir and press ENTER again.
    • If this is a fresh version of IIS (no other sites running on it) or you're not worried about the hosted sites breaking with a framework change you can use -i instead of -ir. This will change their AppPools for you and steps 5-on shouldn't be necessary.
    • at this point you will see it begin working on installing .NET's framework in to IIS for you
  4. Close the DOS prompt, re-open your start menu and right click Computer and select Manage
  5. Expand the left-hand side (Services and Applications) and select Internet Information Services
    • You'll now have a new applet within the content window exclusively for IIS.
  6. Expand out your computer and locate the Application Pools node, and select it. (You should now see ASP.NET v4.0 listed)
  7. Expand out your Sites node and locate the site you want to modify (select it)
  8. To the right you'll notice Basic Settings... just below the Edit Site text. Click this, and a new window should appear
  9. Select the .NET 4 AppPool using the Select... button and click ok.
  10. Restart the site, and you should be good-to-go.

(You can repeat steps 7-on for every site you want to apply .NET 4 on as well).


Additional References:

  1. .NET 4 Framework
    The framework for those that don't already have it.
  2. How do I run a command with elevated privileges?
    Directions on how to run the command prompt with Administrator rights.
  3. aspnet_regiis.exe options
    For those that might want to know what -ir or -i does (or the difference between them) or what other options are available. (I typically use -ir to prevent any older sites currently running from breaking on a framework change but that's up to you.)

initializing strings as null vs. empty string

Empty-ness and "NULL-ness" are two different concepts. As others mentioned the former can be achieved via std::string::empty(), the latter can be achieved with boost::optional<std::string>, e.g.:

boost::optional<string> myStr;
if (myStr) { // myStr != NULL
    // ...
}

int value under 10 convert to string two digit number

I will start my answer saying that most of previous answers were perfectly good answers at the time of writing them. So, thank you to them who wrote them.

Now, you can also use String Interpolation for same solution.

Edit: Adding this explanation after receiving a perfectively valid constructive comment from Heretic Monkey. I have preferred to use .ToString whenever I had need to convert an integer to string and not add the result to any other string. And, I have preferred to use interpolation whenever I had need to combine string(s) and an integer, like in below examples.

String Interpolation

i.ToString("00")
01

i.ToString("000")
001

i.ToString("0000")
0001

$"Prefix_{i:00}"
Prefix_01

$"Prefix_{i:000}"
Prefix_001

$"Prefix_{i:0000}_Suffix"
Prefix_0001_Suffix

Check if list<t> contains any of another list

If both the list are too big and when we use lamda expression then it will take a long time to fetch . Better to use linq in this case to fetch parameters list:

var items = (from x in parameters
                join y in myStrings on x.Source equals y
                select x)
            .ToList();

Group by multiple field names in java 8

Hi You can simply concatenate your groupingByKey such as

Map<String, List<Person>> peopleBySomeKey = people
                .collect(Collectors.groupingBy(p -> getGroupingByKey(p), Collectors.mapping((Person p) -> p, toList())));



//write getGroupingByKey() function
private String getGroupingByKey(Person p){
return p.getAge()+"-"+p.getName();
}

"Sources directory is already netbeans project" error when opening a project from existing sources

When you create a NetBeans project from existing sources, NetBeans uses the same directory to add its own files: a netbeans folder with .proj files.

Solution: delete the netbeans folder and restart the IDE. Opening a new project should now work.

Generate insert script for selected records?

You could create a view with your criteria and then export the view?

Printing *s as triangles in Java?

well for the triangle , you need to have three loops in place of two , one outer loop to iterate the no of line two parallel loops inside the main loop first loop prints decreasing no of loops second loop prints increasing no of '' well i could give the exact logic as well , but its better if you try first just concentrate how many spaces and how many '' u need in every line relate the no of symbols with loop iterating no of lines and you're done ..... if it bothers more , let me know , i'll explain with logic and code as well

What is difference between XML Schema and DTD?

Similarities between XSD and DTD

both specify elements, attributes, nesting, ordering, #occurences

Differences between XSD and DTD

XSD also has data types, (typed) pointers, namespaces, keys and more.... unlike DTD 

Moreover though XSD is little verbose its syntax is extension of XML, making it convenient to learn fast.

Change one value based on another value in pandas

You can use map, it can map vales from a dictonairy or even a custom function.

Suppose this is your df:

    ID First_Name Last_Name
0  103          a         b
1  104          c         d

Create the dicts:

fnames = {103: "Matt", 104: "Mr"}
lnames = {103: "Jones", 104: "X"}

And map:

df['First_Name'] = df['ID'].map(fnames)
df['Last_Name'] = df['ID'].map(lnames)

The result will be:

    ID First_Name Last_Name
0  103       Matt     Jones
1  104         Mr         X

Or use a custom function:

names = {103: ("Matt", "Jones"), 104: ("Mr", "X")}
df['First_Name'] = df['ID'].map(lambda x: names[x][0])

How to find all occurrences of an element in a list

One more solution(sorry if duplicates) for all occurrences:

values = [1,2,3,1,2,4,5,6,3,2,1]
map(lambda val: (val, [i for i in xrange(len(values)) if values[i] == val]), values)

Python datetime to string without microsecond component

We can try something like below

import datetime

date_generated = datetime.datetime.now()
date_generated.replace(microsecond=0).isoformat(' ').partition('+')[0]

jQuery selector for the label of a checkbox

This should do it:

$("label[for=comedyclubs]")

If you have non alphanumeric characters in your id then you must surround the attr value with quotes:

$("label[for='comedy-clubs']")

Delete duplicate records from a SQL table without a primary key

delete from employee where rowid in (select rowid from (select rowid, name_count from (select rowid, count(emp_name) as name_count from employee group by emp_id, emp_name) where name_count>1))

How to start anonymous thread class

I'm surprised that I didn't see any mention of Java's Executor framework for this question's answers. One of the main selling points of the Executor framework is so that you don't have do deal with low level threads. Instead, you're dealing with the higher level of abstraction of ExecutorServices. So, instead of manually starting a thread, just execute the executor that wraps a Runnable. Using the single thread executor, the Runnable instance you create will internally be wrapped and executed as a thread.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// ...

ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
try {
  threadExecutor.execute(
    new Runnable() {
      @Override
      public void run() {
        System.out.println("blah");
      }
    }
  );
} finally {
    threadExecutor.shutdownNow();
}

For convenience, see the code on JDoodle.

HTML table with fixed headers and a fixed column?

I see this, although an old question, is a pretty good place to plug my own script:

http://code.google.com/p/js-scroll-table-header/

It just works with no configuration and is really easy to setup.

Release generating .pdb files, why?

Actually without PDB files and symbolic information they have it would be impossible to create a successful crash report (memory dump files) and Microsoft would not have the complete picture what caused the problem.

And so having PDB improves crash reporting.

Changing precision of numeric column in Oracle

Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.

The easiest way to handle this is to rename the column, copy the data over, then drop the original column:

alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;

alter table EVAPP_FEES add AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_OLD;

alter table EVAPP_FEES drop column AMOUNT_OLD;

If you really want to retain the column ordering, you can move the data twice instead:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

HTML/JavaScript: Simple form validation on submit

You have several errors there.

First, you have to return a value from the function in the HTML markup: <form name="ff1" method="post" onsubmit="return validateForm();">

Second, in the JSFiddle, you place the code inside onLoad which and then the form won't recognize it - and last you have to return true from the function if all validation is a success - I fixed some issues in the update:

https://jsfiddle.net/mj68cq0b/

function validateURL(url) {
    var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
    return reurl.test(url);
}

function validateForm()
{
    // Validate URL
    var url = $("#frurl").val();
    if (validateURL(url)) { } else {
        alert("Please enter a valid URL, remember including http://");
        return false;
    }

    // Validate Title
    var title = $("#frtitle").val();
    if (title=="" || title==null) {
        alert("Please enter only alphanumeric values for your advertisement title");
        return false;
    }

    // Validate Email
    var email = $("#fremail").val();
    if ((/(.+)@(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
        alert("Please enter a valid email");
        return false;
    }
  return true;
}

Linux: where are environment variables stored?

Type "set" and you will get a list of all the current variables. If you want something to persist put it in ~/.bashrc or ~/.bash_profile (if you're using bash)

Create multiple threads and wait all of them to complete

If you don't want to use the Task class (for instance, in .NET 3.5) you can just start all your threads, and then add them to the list and join them in a foreach loop.

Example:

List<Thread> threads = new List<Thread>();


// Start threads
for(int i = 0; i<10; i++)
{
    int tmp = i; // Copy value for closure
    Thread t = new Thread(() => Console.WriteLine(tmp));
    t.Start;
    threads.Add(t);
}

// Await threads
foreach(Thread thread in threads)
{
    thread.Join();
}

Add A Year To Today's Date

Use the Date.prototype.setFullYear method to set the year to what you want it to be.

For example:

var aYearFromNow = new Date();
aYearFromNow.setFullYear(aYearFromNow.getFullYear() + 1);

There really isn't another way to work with dates in JavaScript if these methods aren't present in the environment you are working with.

How to set up a Web API controller for multipart/form-data

Here's another answer for the ASP.Net Core solution to this problem...

On the Angular side, I took this code example...

https://stackblitz.com/edit/angular-drag-n-drop-directive

... and modified it to call an HTTP Post endpoint:

  prepareFilesList(files: Array<any>) {

    const formData = new FormData();
    for (var i = 0; i < files.length; i++) { 
      formData.append("file[]", files[i]);
    }

    let URL = "https://localhost:44353/api/Users";
    this.http.post(URL, formData).subscribe(
      data => { console.log(data); },
      error => { console.log(error); }
    );

With this in place, here's the code I needed in the ASP.Net Core WebAPI controller:

[HttpPost]
public ActionResult Post()
{
  try
  {
    var files = Request.Form.Files;

    foreach (IFormFile file in files)
    {
        if (file.Length == 0)
            continue;
        
        string tempFilename = Path.Combine(Path.GetTempPath(), file.FileName);
        System.Diagnostics.Trace.WriteLine($"Saved file to: {tempFilename}");

        using (var fileStream = new FileStream(tempFilename, FileMode.Create))
        {
            file.CopyTo(fileStream);
        }
    }
    return new OkObjectResult("Yes");
  }
  catch (Exception ex)
  {
    return new BadRequestObjectResult(ex.Message);
  }
}

Shockingly simple, but I had to piece together examples from several (almost-correct) sources to get this to work properly.

Vim for Windows - What do I type to save and exit from a file?

  • Press i or a to get into insert mode, and type the message of choice

  • Press ESC several times to get out of insert mode, or any other mode you might have run into by accident

    • to save, :wq, :x or ZZ

    • to exit without saving, :q! or ZQ

To reload a file and undo all changes you have made...:

Press several times ESC and then enter :e!.

"Cannot update paths and switch to branch at the same time"

'origin/master' which can not be resolved as commit

Strange: you need to check your remotes:

git remote -v

And make sure origin is fetched:

git fetch origin

Then:

git branch -avv

(to see if you do have fetched an origin/master branch)

Finally, use git switch instead of the confusing git checkout, with Git 2.23+ (August 2019).

git switch -c test --track origin/master

How to bring a window to the front?

Windows has the facility to prevent windows from stealing focus; instead it flashes the taskbar icon. In XP it's on by default (the only place I've seen to change it is using TweakUI, but there is a registry setting somewhere). In Vista they may have changed the default and/or exposed it as a user accessible setting with the out-of-the-box UI.

Preventing windows from forcing themselves to the front and taking focus is a feature since Windows 2K (and I, for one, am thankful for it).

That said, I have a little Java app I use to remind me to record my activities while working, and it makes itself the active window every 30 minutes (configurable, of course). It always works consistently under Windows XP and never flashes the title bar window. It uses the following code, called in the UI thread as a result of a timer event firing:

if(getState()!=Frame.NORMAL) { setState(Frame.NORMAL); }
toFront();
repaint();

(the first line restores if minimized... actually it would restore it if maximized too, but I never have it so).

While I usually have this app minimized, quite often it's simply behind my text editor. And, like I said, it always works.

I do have an idea on what your problem could be - perhaps you have a race condition with the setVisible() call. toFront() may not be valid unless the window is actually displayed when it is called; I have had this problem with requestFocus() before. You may need to put the toFront() call in a UI listener on a window activated event.

2014-09-07: At some point in time the above code stopped working, perhaps at Java 6 or 7. After some investigation and experimentation I had to update the code to override the window's toFront method do this (in conjunction with modified code from what is above):

setVisible(true);
toFront();
requestFocus();
repaint();

...

public @Override void toFront() {
    int sta = super.getExtendedState() & ~JFrame.ICONIFIED & JFrame.NORMAL;

    super.setExtendedState(sta);
    super.setAlwaysOnTop(true);
    super.toFront();
    super.requestFocus();
    super.setAlwaysOnTop(false);
}

As of Java 8_20, this code seems to be working fine.

How to update std::map after using the find method?

You can update the value like following

   auto itr = m.find('ch'); 
     if (itr != m.end()){
           (*itr).second = 98;
     }

How to "wait" a Thread in Android

You can try this one it is short :)

SystemClock.sleep(7000);

It will sleep for 7 sec look at documentation

How to change workspace and build record Root Directory on Jenkins?

If you go into Configure under Home there is a "Help" note on how to:

Home directory /var/lib/jenkins Help for feature: Home directory

By default, Jenkins stores all of its data in this directory on the file system.

There are a few ways to change the Jenkins home directory:

Edit the JENKINS_HOME variable in your Jenkins configuration file (e.g. /etc/sysconfig/jenkins on Red Hat Linux).
Use your web container's admin tool to set the JENKINS_HOME environment variable.
Set the environment variable JENKINS_HOME before launching your web container, or before launching Jenkins directly from the WAR file.
Set the JENKINS_HOME Java system property when launching your web container, or when launching Jenkins directly from the WAR file.
Modify web.xml in jenkins.war (or its expanded image in your web container). This is not recommended. 

This value cannot be changed while Jenkins is running. It is shown here to help you ensure that your configuration is taking effect.

Mongoose limit/offset and count query

There is a library that will do all of this for you, check out mongoose-paginate-v2

jquery, selector for class within id

Just use the plain ol' class selector.

$('#my_id .my_class')

It doesn't matter if the element also has other classes. It has the .my_class class, and it's somewhere inside #my_id, so it will match that selector.

Regarding performance

According to the jQuery selector performance documentation, it's faster to use the two selectors separately, like this:

$('#my_id').find('.my_class')

Here's the relevant part of the documentation:

ID-Based Selectors

// Fast:
$( "#container div.robotarm" );

// Super-fast:
$( "#container" ).find( "div.robotarm" );

The .find() approach is faster because the first selection is handled without going through the Sizzle selector engine – ID-only selections are handled using document.getElementById(), which is extremely fast because it is native to the browser.

Selecting by ID or by class alone (among other things) invokes browser-supplied functions like document.getElementById() which are quite rapid, whereas using a descendent selector invokes the Sizzle engine as mentioned which, although fast, is slower than the suggested alternative.

How can I access the MySQL command line with XAMPP for Windows?

To access SQL via the command line we simply navigate to the xampp folder. the folder is usually on the c:\ drive.

  1. type: cd c:\xampp\mysql\bin then press enter.
  2. type: in mysql -u root -p then press enter.
  3. in the new line enter the password of the database.
  4. type: show databases; to see all the databases that you have access to.
  5. once you know what database you want to use type (ex. cms_database), type use cms_data or any other db_name, it should say Database changed

// Bonus Note you shouldn't use the root user when working with databases. you would want to create a separate account (ex. cms_user) with special privileges to limit errors.

to do that type:

GRANT ALL PRIVILEGES IN cms_database.*
TO 'cms_user'@'localhost' 
IDENTITIED BY 'yourpassword'

double check by using the command:

SHOW GRANT FOR 'cms_user'@localhost;

if you already have the name of the user and the specific database you wish to use, change step 2 to this.

mysql -u cms_user -p cms_database 

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

I am new to spring spent an hour trying to figure this out.

go to --- > application.properties

add these :

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

php timeout - set_time_limit(0); - don't work

This is an old thread, but I thought I would post this link, as it helped me quite a bit on this issue. Essentially what it's saying is the server configuration can override the php config. From the article:

For example mod_fastcgi has an option called "-idle-timeout" which controls the idle time of the script. So if the script does not output anything to the fastcgi handler for that many seconds then fastcgi would terminate it. The setup is somewhat like this:

Apache <-> mod_fastcgi <-> php processes

The article has other examples and further explanation. Hope this helps somebody else.

Linux Script to check if process is running and act on the result

Programs to monitor if a process on a system is running.

Script is stored in crontab and runs once every minute.

This works with if process is not running or process is running multiple times:

#! /bin/bash

case "$(pidof amadeus.x86 | wc -w)" in

0)  echo "Restarting Amadeus:     $(date)" >> /var/log/amadeus.txt
    /etc/amadeus/amadeus.x86 &
    ;;
1)  # all ok
    ;;
*)  echo "Removed double Amadeus: $(date)" >> /var/log/amadeus.txt
    kill $(pidof amadeus.x86 | awk '{print $1}')
    ;;
esac

0 If process is not found, restart it.
1 If process is found, all ok.
* If process running 2 or more, kill the last.


A simpler version. This just test if process is running, and if not restart it.

It just tests the exit flag $? from the pidof program. It will be 0 of process is running and 1 if not.

#!/bin/bash
pidof  amadeus.x86 >/dev/null
if [[ $? -ne 0 ]] ; then
        echo "Restarting Amadeus:     $(date)" >> /var/log/amadeus.txt
        /etc/amadeus/amadeus.x86 &
fi

And at last, a one liner

pidof amadeus.x86 >/dev/null ; [[ $? -ne 0 ]] && echo "Restarting Amadeus:     $(date)" >> /var/log/amadeus.txt && /etc/amadeus/amadeus.x86 &

cccam oscam

Python - How to sort a list of lists by the fourth element in each list?

Use sorted() with a key as follows -

>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

The lambda returns the fourth element of each of the inner lists and the sorted function uses that to sort those list. This assumes that int(elem) will not fail for the list.

Or use itemgetter (As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)

>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

Secure FTP using Windows batch script

    ftps -a -z -e:on -pfxfile:"S-PID.p12" -pfxpwfile:"S-PID.p12.pwd" -user:<S-PID number> -s:script <RemoteServerName> 2121

S-PID.p12 => certificate file name ;
S-PID.p12.pwd => certificate password file name ; 
RemoteServerName =>  abcd123 ; 
2121 => port number ; 
ftps => command is part of ftps client software ; 

Direct casting vs 'as' operator?

All given answers are good, if i might add something: To directly use string's methods and properties (e.g. ToLower) you can't write:

(string)o.ToLower(); // won't compile

you can only write:

((string)o).ToLower();

but you could write instead:

(o as string).ToLower();

The as option is more readable (at least to my opinion).

How to check if a date is greater than another in Java?

You can use Date.before() or Date.after() or Date.equals() for date comparison.

Taken from here:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDiff {

    public static void main( String[] args )
    {
        compareDates("2017-01-13 00:00:00", "2017-01-14 00:00:00");// output will be Date1 is before Date2
        compareDates("2017-01-13 00:00:00", "2017-01-12 00:00:00");//output will be Date1 is after Date2
        compareDates("2017-01-13 00:00:00", "2017-01-13 10:20:30");//output will be Date1 is before Date2 because date2 is ahead of date 1 by 10:20:30 hours
        compareDates("2017-01-13 00:00:00", "2017-01-13 00:00:00");//output will be Date1 is equal Date2 because both date and time are equal
    }

    public static void compareDates(String d1,String d2)
    {
        try{
            // If you already have date objects then skip 1

            //1
            // Create 2 dates starts
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf.parse(d1);
            Date date2 = sdf.parse(d2);

            System.out.println("Date1"+sdf.format(date1));
            System.out.println("Date2"+sdf.format(date2));System.out.println();

            // Create 2 dates ends
            //1

            // Date object is having 3 methods namely after,before and equals for comparing
            // after() will return true if and only if date1 is after date 2
            if(date1.after(date2)){
                System.out.println("Date1 is after Date2");
            }
            // before() will return true if and only if date1 is before date2
            if(date1.before(date2)){
                System.out.println("Date1 is before Date2");
            }

            //equals() returns true if both the dates are equal
            if(date1.equals(date2)){
                System.out.println("Date1 is equal Date2");
            }

            System.out.println();
        }
        catch(ParseException ex){
            ex.printStackTrace();
        }
    }

    public static void compareDates(Date date1,Date date2)
    {
        // if you already have date objects then skip 1
        //1

        //1

        //date object is having 3 methods namely after,before and equals for comparing
        //after() will return true if and only if date1 is after date 2
        if(date1.after(date2)){
            System.out.println("Date1 is after Date2");
        }

        //before() will return true if and only if date1 is before date2
        if(date1.before(date2)){
            System.out.println("Date1 is before Date2");
        }

        //equals() returns true if both the dates are equal
        if(date1.equals(date2)){
            System.out.println("Date1 is equal Date2");
        }

        System.out.println();
    }
}

Xcode 7.2 no matching provisioning profiles found

In addition to what other users posted, make sure the Team selected on the Target settings (General tab) is the correct one. Xcode will complain it cannot find the Provisioning Profile if the profile belongs to a different team than the one selected.

What does `dword ptr` mean?

Consider the figure enclosed in this other question. ebp-4 is your first local variable and, seen as a dword pointer, it is the address of a 32 bit integer that has to be cleared. Maybe your source starts with

Object x = null;

Create folder in Android

Add this permission in Manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

File folder = new File(Environment.getExternalStorageDirectory() + 
                             File.separator + "TollCulator");
boolean success = true;
if (!folder.exists()) {
    success = folder.mkdirs();
}
if (success) {
    // Do something on success
} else {
    // Do something else on failure 
}

when u run the application go too DDMS->File Explorer->mnt folder->sdcard folder->toll-creation folder

rsync error: failed to set times on "/foo/bar": Operation not permitted

This happened to me on a partition of type xfs (rw,relatime,seclabel,attr2,inode64,noquota), where the directories where owned by another user in a group we were both members of. The group membership was already established before login, and the whole directory structure was group-writeable. I had manually run sudo chown -R otheruser.group directory and sudo chmod -R g+rw directory to confirm this.

I still have no idea why it didn't work originally, but taking ownership with sudo chown -R myuser.group directory fixed it. Perhaps SELinux-related?

how to display a javascript var in html body

Index.html:

<html>
<body>
    Javascript Version: <b id="version"></b>
    <script src="app.js"></script>
</body>
</html>

app.js:

var ver="1.1";
document.getElementById("version").innerHTML = ver;

What is the difference between 'java', 'javaw', and 'javaws'?

java.exe is associated with the console, whereas javaw.exe doesn't have any such association. So, when java.exe is run, it automatically opens a command prompt window where output and error streams are shown.

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

in your baseadapter class constructor try to initialize LayoutInflater, normally i preferred this way,

public ClassBaseAdapter(Context context,ArrayList<Integer> listLoanAmount) {
    this.context = context;
    this.listLoanAmount = listLoanAmount;
    this.layoutInflater = LayoutInflater.from(context);
}

at the top of the class create LayoutInflater variable, hope this will help you

How to disable 'X-Frame-Options' response header in Spring Security?

If you are using Spring Security's Java configuration, all of the default security headers are added by default. They can be disabled using the Java configuration below:

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .headers().disable()
      ...;
  }
}

IPC performance: Named Pipe vs Socket

You can use lightweight solution like ZeroMQ [ zmq/0mq ]. It is very easy to use and dramatically faster then sockets.

Use xml.etree.ElementTree to print nicely formatted xml files

You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:

>>> print(etree.tostring(root, pretty_print=True))
<root>
  <child1/>
  <child2/>
  <child3/>
</root>

How to git reset --hard a subdirectory?

Try changing

git checkout -- a

to

git checkout -- `git ls-files -m -- a`

Since version 1.7.0, Git's ls-files honors the skip-worktree flag.

Running your test script (with some minor tweaks changing git commit... to git commit -q and git status to git status --short) outputs:

Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
 D a/a/aa
 D a/b/ab
 M b/a/ba
After checkout:
 M b/a/ba
a/a/aa
a/c/ac
a/b/ab
b/a/ba

Running your test script with the proposed checkout change outputs:

Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
 D a/a/aa
 D a/b/ab
 M b/a/ba
After checkout:
 M b/a/ba
a/a/aa
a/b/ab
b/a/ba

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

Copying a HashMap in Java

You can also use

clone()

Method to copy all elements from one hashmap to another hashmap

Program for copy all elements from one hashmap to another

import java.util.HashMap;

public class CloneHashMap {    
     public static void main(String a[]) {    
        HashMap hashMap = new HashMap();    
        HashMap hashMap1 = new HashMap();    
        hashMap.put(1, "One");
        hashMap.put(2, "Two");
        hashMap.put(3, "Three");
        System.out.println("Original HashMap : " + hashMap);
        hashMap1 = (HashMap) hashMap.clone();
        System.out.println("Copied HashMap : " + hashMap1);    
    }    
}

source : http://www.tutorialdata.com/examples/java/collection-framework/hashmap/copy-all-elements-from-one-hashmap-to-another

Finding an element in an array in Java

Use a for loop. There's nothing built into array. Or switch to a java.util Collection class.

Adding subscribers to a list using Mailchimp's API v3

BATCH LOAD - OK, so after having my previous reply deleted for just using links I have updated with the code I managed to get working. Appreciate anyone to simplify / correct / refine / put in function etc as I'm still learning this stuff, but I got batch member list add working :)

$apikey = "whatever-us99";                            
$list_id = "12ab34dc56";

$email1 = "[email protected]";
$fname1 = "Jack";
$lname1 = "Black";

$email2 = "[email protected]";
$fname2 = "Jill";
$lname2 = "Hill";

$auth = base64_encode( 'user:'.$apikey );

$data1 = array(
    "apikey"        => $apikey,
    "email_address" => $email1,
    "status"        => "subscribed",
    "merge_fields"  => array(                
            'FNAME' => $fname1,
            'LNAME' => $lname1,
    )
);

$data2 = array(
    "apikey"        => $apikey,
    "email_address" => $email2,
    "status"        => "subscribed",                
    "merge_fields"  => array(                
            'FNAME' => $fname2,
            'LNAME' => $lname2,
    )
);

$json_data1 = json_encode($data1);
$json_data2 = json_encode($data2);

$array = array(
    "operations" => array(
        array(
            "method" => "POST",
            "path" => "/lists/$list_id/members/",
            "body" => $json_data1
        ),
        array(
            "method" => "POST",
            "path" => "/lists/$list_id/members/",
            "body" => $json_data2
        )
    )
);

$json_post = json_encode($array);

$ch = curl_init();

$curlopt_url = "https://us99.api.mailchimp.com/3.0/batches";
curl_setopt($ch, CURLOPT_URL, $curlopt_url);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_post);

print_r($json_post . "\n");
$result = curl_exec($ch);

var_dump($result . "\n");
print_r ($result . "\n");

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

PDF Blob - Pop up window not showing content

problem is, it is not converted to proper format. Use function "printPreview(binaryPDFData)" to get print preview dialog of binary pdf data. you can comment script part if you don't want print dialog open.

printPreview = (data, type = 'application/pdf') => {
    let blob = null;
    blob = this.b64toBlob(data, type);
    const blobURL = URL.createObjectURL(blob);
    const theWindow = window.open(blobURL);
    const theDoc = theWindow.document;
    const theScript = document.createElement('script');
    function injectThis() {
        window.print();
    }
    theScript.innerHTML = `window.onload = ${injectThis.toString()};`;
    theDoc.body.appendChild(theScript);
};

b64toBlob = (content, contentType) => {
    contentType = contentType || '';
    const sliceSize = 512;
     // method which converts base64 to binary
    const byteCharacters = window.atob(content); 

    const byteArrays = [];
    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        const slice = byteCharacters.slice(offset, offset + sliceSize);
        const byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }
    const blob = new Blob(byteArrays, {
        type: contentType
    }); // statement which creates the blob
    return blob;
};

<Django object > is not JSON serializable

First I added a to_dict method to my model ;

def to_dict(self):
    return {"name": self.woo, "title": self.foo}

Then I have this;

class DjangoJSONEncoder(JSONEncoder):

    def default(self, obj):
        if isinstance(obj, models.Model):
            return obj.to_dict()
        return JSONEncoder.default(self, obj)


dumps = curry(dumps, cls=DjangoJSONEncoder)

and at last use this class to serialize my queryset.

def render_to_response(self, context, **response_kwargs):
    return HttpResponse(dumps(self.get_queryset()))

This works quite well

LINQ Group By into a Dictionary Object

For @atari2600, this is what the answer would look like using ToLookup in lambda syntax:

var x = listOfCustomObjects
    .GroupBy(o => o.PropertyName)
    .ToLookup(customObject => customObject);

Basically, it takes the IGrouping and materializes it for you into a dictionary of lists, with the values of PropertyName as the key.

HQL "is null" And "!= null" on an Oracle column

If you do want to use null values with '=' or '<>' operators you may find the

answer from @egallardo hier

very useful.

Short example for '=': The expression

WHERE t.field = :param

you refactor like this

WHERE ((:param is null and t.field is null) or t.field = :param)

Now you can set the parameter param either to some non-null value or to null:

query.setParameter("param", "Hello World"); // Works
query.setParameter("param", null);          // Works also

How do I create a user account for basic authentication?

in iis manager click directory to protect.

choose authorization rules.

add deny anonymous users rule.

add allow all users rule.

go back to: "in iis manager click directory to protect" click authentication disable all except basic authentication.

the directory is now protected. only people with user accounts can access the folder over the web.

Convert object array to hash map, indexed by an attribute value of the Object

This is what I'm doing in TypeScript I have a little utils library where I put things like this

export const arrayToHash = (array: any[], id: string = 'id') => 
         array.reduce((obj, item) =>  (obj[item[id]] = item , obj), {})

usage:

const hash = arrayToHash([{id:1,data:'data'},{id:2,data:'data'}])

or if you have a identifier other than 'id'

const hash = arrayToHash([{key:1,data:'data'},{key:2,data:'data'}], 'key')

How to solve "The specified service has been marked for deletion" error

If the steps provided by @MainMa didn't work follow following steps

Step 1 Try killing the process from windows task manager or using taskkill /F /PID . You can find pid of the process by command 'sc queryex '. Try next step if you still can't uninstall.

Step 2 If above

Run Autoruns for Windows Search for service by name and delete results.

Simple dynamic breadcrumb

This is the code that i personally use in my sites. Works outside of the box.

<?php
function breadcrumbs($home = 'Home') {
  global $page_title; //global varable that takes it's value from the page that breadcrubs will appear on. Can be deleted if you wish, but if you delete it, delete also the title tage inside the <li> tag inside the foreach loop.
    $breadcrumb  = '<div class="breadcrumb-container"><div class="container"><ol class="breadcrumb">';
    $root_domain = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'].'/';
    $breadcrumbs = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
    $breadcrumb .= '<li><i class="fa fa-home"></i><a href="' . $root_domain . '" title="Home Page"><span>' . $home . '</span></a></li>';
    foreach ($breadcrumbs as $crumb) {
        $link = ucwords(str_replace(array(".php","-","_"), array(""," "," "), $crumb));
        $root_domain .=  $crumb . '/';
        $breadcrumb .= '<li><a href="'. $root_domain .'" title="'.$page_title.'"><span>' . $link . '</span></a></li>';
    }
    $breadcrumb .= '</ol>';
    $breadcrumb .= '</div>';
    $breadcrumb .= '</div>';
    return $breadcrumb;
}
echo breadcrumbs();
?>

The css:

.breadcrumb-container {
    width: 100%;
    background-color: #f8f8f8;
    border-bottom-color: 1px solid #f4f4f4;
    list-style: none;
    margin-top: 72px;
    min-height: 25px;
    box-shadow: 0 3px 0 rgba(60, 57, 57, .2)
}

.breadcrumb-container li {
    display: inline
}
.breadcrumb {
    font-size: 12px;
    padding-top: 3px
}
.breadcrumb>li:last-child:after {
    content: none
}

.breadcrumb>li:last-child {
    font-weight: 700;
    font-style: italic
}
.breadcrumb>li>i {
    margin-right: 3px
}

.breadcrumb>li:after {
    font-family: FontAwesome;
    content: "\f101";
    font-size: 11px;
    margin-left: 3px;
    margin-right: 3px
}
.breadcrumb>li+li:before {
    font-size: 11px;
    padding-left: 3px
}

Feel free to play around with the css padding and margins until you get it right for your own site.

How to commit and rollback transaction in sql server?

As per http://msdn.microsoft.com/en-us/library/ms188790.aspx

@@ERROR: Returns the error number for the last Transact-SQL statement executed.

You will have to check after each statement in order to perform the rollback and return.

Commit can be at the end.

HTH

iframe to Only Show a Certain Part of the Page

Somehow I fiddled around and some how I got it to work:

<iframe src="http://www.example.com#inside" width="100%" height="100%" align="center" ></iframe>

I think this is the first time this code has been posted so share it

Round number to nearest integer

Use round(x, y). It will round up your number up to your desired decimal place.

For example:

>>> round(32.268907563, 3)
32.269

Find a file by name in Visual Studio Code

It is CMD + P (or CTRL + P) by default. However the keyboard bindings may differ according to your preferences.

To know your bindings go to the "Keyboard Shortcuts" settings and search for "Go to File"

Convert timestamp to date in MySQL query

You should convert timestamp to date.

select FROM_UNIXTIME(user.registration, '%Y-%m-%d %H:%i:%s') AS 'date_formatted'

FROM_UNIXTIME

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

Comprehensive answer is here: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/putty.html

Your problem can be related to incorrect login which varies depending on AMIs. Use following logins on following AMIs:

  • ubuntu or root on ubuntu AMIs
  • ec2-user on Amazon Linux AMI
  • centos on Centos AMI
  • debian or root on Debian AMIs
  • ec2-user or fedora on Fedora
  • ec2-user or root on: RHEL AMI, SUSE AMI, other ones.

If you are using OS:

  • Windows - get PEM key from AWS website and generate PPK file using PuttyGen. Then use Putty to use the PPK (select it using left-column: Connection->SSH->Auth: Private key for authorization)
  • Linux - run: ssh -i your-ssh-key.pem login@IP-or-DNS

Good luck.

Deleting multiple columns based on column names in Pandas

You can just pass the column names as a list with specifying the axis as 0 or 1

  • axis=1: Along the Rows
  • axis=0: Along the Columns
  • By default axis=0

    data.drop(["Colname1","Colname2","Colname3","Colname4"],axis=1)

Abstract Class:-Real Time Example

The best example of an abstract class is GenericServlet. GenericServlet is the parent class of HttpServlet. It is an abstract class.

When inheriting 'GenericServlet' in a custom servlet class, the service() method must be overridden.

Set proxy through windows command line including login parameters

cmd

Tunnel all your internet traffic through a socks proxy:

netsh winhttp set proxy proxy-server="socks=localhost:9090" bypass-list="localhost"

View the current proxy settings:

netsh winhttp show proxy

Clear all proxy settings:

netsh winhttp reset proxy

Disable time in bootstrap date time picker

This shows only date:

$('#myDateTimePicker').datetimepicker({
        format: 'dd.mm.yyyy',
        minView: 2,
        maxView: 4,
        autoclose: true
      });

More on the subject here

Android Google Maps v2 - set zoom level for myLocation

Slightly different solution than HeatfanJohn's, where I change the zoom relatively to the current zoom level:

// Zoom out just a little
map.animateCamera(CameraUpdateFactory.zoomTo(map.getCameraPosition().zoom - 0.5f));

Convert StreamReader to byte[]

For everyone saying to get the bytes, copy it to MemoryStream, etc. - if the content isn't expected to be larger than computer's memory should be reasonably be expected to allow, why not just use StreamReader's built in ReadLine() or ReadToEnd()? I saw these weren't even mentioned, and they do everything for you.

I had a use-case where I just wanted to store the path of a SQLite file from a FileDialogResult that the user picks during the synching/initialization process. My program then later needs to use this path when it is run for normal application processes. Maybe not the ideal way to capture/re-use the information, but it's not much different than writing to/reading from an .ini file - I just didn't want to set one up for one value. So I just read it from a flat, one-line text file. Here's what I did:

string filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!filePath.EndsWith(@"\")) temppath += @"\"; // ensures we have a slash on the end
filePath = filePath.Replace(@"\\", @"\"); // Visual Studio escapes slashes by putting double-slashes in their results - this ensures we don't have double-slashes
filePath += "SQLite.txt";

string path = String.Empty;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
path = sr.ReadLine();  // can also use sr.ReadToEnd();
sr.Close();
fs.Close();
fs.Flush();

return path;

If you REALLY need a byte[] instead of a string for some reason, using my example, you can always do:

byte[] toBytes;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
toBytes = Encoding.ASCII.GetBytes(path);
sr.Close();
fs.Close();
fs.Flush();

return toBytes;

(Returning toBytes instead of path.)

If you don't want ASCII you can easily replace that with UTF8, Unicode, etc.

How do I parse a string into a number with Dart?

As per dart 2.6

The optional onError parameter of int.parse is deprecated. Therefore, you should use int.tryParse instead.

Note: The same applies to double.parse. Therefore, use double.tryParse instead.

  /**
   * ...
   *
   * The [onError] parameter is deprecated and will be removed.
   * Instead of `int.parse(string, onError: (string) => ...)`,
   * you should use `int.tryParse(string) ?? (...)`.
   *
   * ...
   */
  external static int parse(String source, {int radix, @deprecated int onError(String source)});

The difference is that int.tryParse returns null if the source string is invalid.

  /**
   * Parse [source] as a, possibly signed, integer literal and return its value.
   *
   * Like [parse] except that this function returns `null` where a
   * similar call to [parse] would throw a [FormatException],
   * and the [source] must still not be `null`.
   */
  external static int tryParse(String source, {int radix});

So, in your case it should look like:

// Valid source value
int parsedValue1 = int.tryParse('12345');
print(parsedValue1); // 12345

// Error handling
int parsedValue2 = int.tryParse('');
if (parsedValue2 == null) {
  print(parsedValue2); // null
  //
  // handle the error here ...
  //
}

Creating a config file in PHP

I use a slight evolution of @hugo_leonardo 's solution:

<?php

return (object) array(
    'host' => 'localhost',
    'username' => 'root',
    'pass' => 'password',
    'database' => 'db'
);

?>

This allows you to use the object syntax when you include the php : $configs->host instead of $configs['host'].

Also, if your app has configs you need on the client side (like for an Angular app), you can have this config.php file contain all your configs (centralized in one file instead of one for JavaScript and one for PHP). The trick would then be to have another PHP file that would echo only the client side info (to avoid showing info you don't want to show like database connection string). Call it say get_app_info.php :

<?php

    $configs = include('config.php');
    echo json_encode($configs->app_info);

?>

The above assuming your config.php contains an app_info parameter:

<?php

return (object) array(
    'host' => 'localhost',
    'username' => 'root',
    'pass' => 'password',
    'database' => 'db',
    'app_info' => array(
        'appName'=>"App Name",
        'appURL'=> "http://yourURL/#/"
    )
);

?>

So your database's info stays on the server side, but your app info is accessible from your JavaScript, with for example a $http.get('get_app_info.php').then(...); type of call.

Correct way to convert size in bytes to KB, MB, GB in JavaScript

I originally used @Aliceljm's answer for a file upload project I was working on, but recently ran into an issue where a file was 0.98kb but being read as 1.02mb. Here's the updated code I'm now using.

function formatBytes(bytes){
  var kb = 1024;
  var ndx = Math.floor( Math.log(bytes) / Math.log(kb) );
  var fileSizeTypes = ["bytes", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb"];

  return {
    size: +(bytes / kb / kb).toFixed(2),
    type: fileSizeTypes[ndx]
  };
}

The above would then be called after a file was added like so

// In this case `file.size` equals `26060275` 
formatBytes(file.size);
// returns `{ size: 24.85, type: "mb" }`

Granted, Windows reads the file as being 24.8mb but I'm fine with the extra precision.

How to disable mouse scroll wheel scaling with Google Maps API

I do it with this simple examps

jQuery

$('.map').click(function(){
    $(this).find('iframe').addClass('clicked')
    }).mouseleave(function(){
    $(this).find('iframe').removeClass('clicked')
});

CSS

.map {
    width: 100%; 
}
.map iframe {
    width: 100%;
    display: block;
    pointer-events: none;
    position: relative; /* IE needs a position other than static */
}
.map iframe.clicked {
    pointer-events: auto;
}

Or use the gmap options

function init() { 
    var mapOptions = {  
        scrollwheel: false, 

PHP: How do I display the contents of a textfile on my page?

if you just want to show the file itself:

header('Content-Type: text/plain');
header('Content-Disposition: inline; filename="filename.txt"');
readfile(path);

How do you disable viewport zooming on Mobile Safari?

As mentioned this solution basically works as of late 2020:

document.addEventListener(
    'gesturestart', (e) => e.preventDefault()
);

But the downside is that while you are scrolling you'd still be able to pinch and then it gets stuck. The solution is to disable scrolling.

body {
    overflow: hidden;
}

But, what if you still wanted the page to be scrolled? You can still do it with another <div> set as overflow:auto:

<body>
    <div id='app'></div>
</div>

and then

body {
    overflow: hidden;
}

 #app {
     -webkit-overflow-scrolling: touch;
      height: 100vh;
      height: -webkit-fill-available;
      overflow: auto;
 }

How to convert String into Hashmap in java

String value = "{first_name = naresh,last_name = kumar,gender = male}"

Let's start

  1. Remove { and } from the String>>first_name = naresh,last_name = kumar,gender = male
  2. Split the String from ,>> array of 3 element
  3. Now you have an array with 3 element
  4. Iterate the array and split each element by =
  5. Create a Map<String,String> put each part separated by =. first part as Key and second part as Value

Program to find prime numbers

Prime Helper very fast calculation

public static class PrimeHelper
{

    public static IEnumerable<Int32> FindPrimes(Int32 maxNumber)
    {
        return (new PrimesInt32(maxNumber));
    }

    public static IEnumerable<Int32> FindPrimes(Int32 minNumber, Int32 maxNumber)
    {
        return FindPrimes(maxNumber).Where(pn => pn >= minNumber);
    }

    public static bool IsPrime(this Int64 number)
    {
        if (number < 2)
            return false;
        else if (number < 4 )
            return true;

        var limit = (Int32)System.Math.Sqrt(number) + 1;
        var foundPrimes = new PrimesInt32(limit);

        return !foundPrimes.IsDivisible(number);
    }

    public static bool IsPrime(this Int32 number)
    {
        return IsPrime(Convert.ToInt64(number));
    }

    public static bool IsPrime(this Int16 number)
    {
        return IsPrime(Convert.ToInt64(number));
    }

    public static bool IsPrime(this byte number)
    {
        return IsPrime(Convert.ToInt64(number));
    }
}

public class PrimesInt32 : IEnumerable<Int32>
{
    private Int32 limit;
    private BitArray numbers;

    public PrimesInt32(Int32 limit)
    {
        if (limit < 2)
            throw new Exception("Prime numbers not found.");

        startTime = DateTime.Now;
        calculateTime = startTime - startTime;
        this.limit = limit;
        try { findPrimes(); } catch{/*Overflows or Out of Memory*/}

        calculateTime = DateTime.Now - startTime;
    }

    private void findPrimes()
    {
        /*
        The Sieve Algorithm
        http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
        */
        numbers = new BitArray(limit, true);
        for (Int32 i = 2; i < limit; i++)
            if (numbers[i])
                for (Int32 j = i * 2; j < limit; j += i)
                     numbers[j] = false;
    }

    public IEnumerator<Int32> GetEnumerator()
    {
        for (Int32 i = 2; i < 3; i++)
            if (numbers[i])
                yield return i;
        if (limit > 2)
            for (Int32 i = 3; i < limit; i += 2)
                if (numbers[i])
                    yield return i;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    // Extended for Int64
    public bool IsDivisible(Int64 number)
    {
        var sqrt = System.Math.Sqrt(number);
        foreach (var prime in this)
        {
            if (prime > sqrt)
                break;
            if (number % prime == 0)
            {
                DivisibleBy = prime;
                return true;
            }
        }
        return false;
    }

    private static DateTime startTime;
    private static TimeSpan calculateTime;
    public static TimeSpan CalculateTime { get { return calculateTime; } }
    public Int32 DivisibleBy { get; set; }
}

git push says "everything up-to-date" even though I have local changes

Verify you haven't goofed your remote URL.

I just wanted to also mention that I ran into this after enabling Git as a CVS in a local Jenkins build configuration. It appears that Jenkins checked out the most recent commit of the branch I gave it and also reset my remote to correspond to the paths I gave it to the repo. Had to checkout my feature branch again and fix my origin remote url with 'git remote set-url'. Don't go pointing a build tool to your working directory or you'll have a bad time. My remote was set to a file path to my working directory, so it naturally reported everything up-to-date when I attempted to push changes with the same source and destination.

How to create a file name with the current date & time in Python?

Here's some that I needed to include the date-time stamp in the folder name for dumping files from a web scraper.

# import time and OS modules to use to build file folder name
import time
import os 

# Build string for directory to hold files
# Output Configuration
#   drive_letter = Output device location (hard drive) 
#   folder_name = directory (folder) to receive and store PDF files

drive_letter = r'D:\\' 
folder_name = r'downloaded-files'
folder_time = datetime.now().strftime("%Y-%m-%d_%I-%M-%S_%p")
folder_to_save_files = drive_letter + folder_name + folder_time 

# IF no such folder exists, create one automatically
if not os.path.exists(folder_to_save_files):
    os.mkdir(folder_to_save_files)

How to "properly" create a custom object in JavaScript?

Bascially there is no concept of class in JS so we use function as a class constructor which is relevant with the existing design patterns.

//Constructor Pattern
function Person(name, age, job){
 this.name = name;
 this.age = age;
 this.job = job;
 this.doSomething = function(){
    alert('I am Happy');
}
}

Till now JS has no clue that you want to create an object so here comes the new keyword.

var person1 = new Person('Arv', 30, 'Software');
person1.name //Arv

Ref : Professional JS for web developers - Nik Z

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

The first function in an m-file (i.e. the main function), is invoked when that m-file is called. It is not required that the main function have the same name as the m-file, but for clarity it should. When the function and file name differ, the file name must be used to call the main function.

All subsequent functions in the m-file, called local functions (or "subfunctions" in the older terminology), can only be called by the main function and other local functions in that m-file. Functions in other m-files can not call them. Starting in R2016b, you can add local functions to scripts as well, although the scoping behavior is still the same (i.e. they can only be called from within the script).

In addition, you can also declare functions within other functions. These are called nested functions, and these can only be called from within the function they are nested. They can also have access to variables in functions in which they are nested, which makes them quite useful albeit slightly tricky to work with.

More food for thought...

There are some ways around the normal function scoping behavior outlined above, such as passing function handles as output arguments as mentioned in the answers from SCFrench and Jonas (which, starting in R2013b, is facilitated by the localfunctions function). However, I wouldn't suggest making it a habit of resorting to such tricks, as there are likely much better options for organizing your functions and files.

For example, let's say you have a main function A in an m-file A.m, along with local functions D, E, and F. Now let's say you have two other related functions B and C in m-files B.m and C.m, respectively, that you also want to be able to call D, E, and F. Here are some options you have:

  • Put D, E, and F each in their own separate m-files, allowing any other function to call them. The downside is that the scope of these functions is large and isn't restricted to just A, B, and C, but the upside is that this is quite simple.

  • Create a defineMyFunctions m-file (like in Jonas' example) with D, E, and F as local functions and a main function that simply returns function handles to them. This allows you to keep D, E, and F in the same file, but it doesn't do anything regarding the scope of these functions since any function that can call defineMyFunctions can invoke them. You also then have to worry about passing the function handles around as arguments to make sure you have them where you need them.

  • Copy D, E and F into B.m and C.m as local functions. This limits the scope of their usage to just A, B, and C, but makes updating and maintenance of your code a nightmare because you have three copies of the same code in different places.

  • Use private functions! If you have A, B, and C in the same directory, you can create a subdirectory called private and place D, E, and F in there, each as a separate m-file. This limits their scope so they can only be called by functions in the directory immediately above (i.e. A, B, and C) and keeps them together in the same place (but still different m-files):

    myDirectory/
        A.m
        B.m
        C.m
        private/
            D.m
            E.m
            F.m
    

All this goes somewhat outside the scope of your question, and is probably more detail than you need, but I thought it might be good to touch upon the more general concern of organizing all of your m-files. ;)

Installing the Android USB Driver in Windows 7

Just download and install "Samsung Kies" from this link. and everything would work as required.

Before installing, uninstall the drivers you have installed for your device.

Update:

Two possible solutions:

  1. Try with the Google USB driver which comes with the SDK.
  2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

Given a view, how do I get its viewController?

If you are not familiar with the code and you want to find ViewController coresponding to given view, then you can try:

  1. Run app in debug
  2. Navigate to screen
  3. Start View inspector
  4. Grab the View you want to find (or a child view even better)
  5. From the right pane get the address (e.g. 0x7fe523bd3000)
  6. In debug console start writing commands:
    po (UIView *)0x7fe523bd3000
    po [(UIView *)0x7fe523bd3000 nextResponder]
    po [[(UIView *)0x7fe523bd3000 nextResponder] nextResponder]
    po [[[(UIView *)0x7fe523bd3000 nextResponder] nextResponder] nextResponder]
    ...

In most cases you will get UIView, but from time to time there will be UIViewController based class.

Check if a string is not NULL or EMPTY

As in many other programming and scripting languages you can do so by adding ! in front of the condition

if (![string]::IsNullOrEmpty($version))
{
    $request += "/" + $version
}

Get latitude and longitude automatically using php, API

//add urlencode to your address
$address = urlencode("technopark, Trivandrun, kerala,India");
$region = "IND";
$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region");

echo $json;

$decoded = json_decode($json);

print_r($decoded);

Proper MIME media type for PDF files

The standard MIME type is application/pdf. The assignment is defined in RFC 3778, The application/pdf Media Type, referenced from the MIME Media Types registry.

MIME types are controlled by a standards body, The Internet Assigned Numbers Authority (IANA). This is the same organization that manages the root name servers and the IP address space.

The use of x-pdf predates the standardization of the MIME type for PDF. MIME types in the x- namespace are considered experimental, just as those in the vnd. namespace are considered vendor-specific. x-pdf might be used for compatibility with old software.

What is the use of ObservableCollection in .net?

From Pro C# 5.0 and the .NET 4.5 Framework

The ObservableCollection<T> class is very useful in that it has the ability to inform external objects when its contents have changed in some way (as you might guess, working with ReadOnlyObservableCollection<T> is very similar, but read-only in nature). In many ways, working with the ObservableCollection<T> is identical to working with List<T>, given that both of these classes implement the same core interfaces. What makes the ObservableCollection<T> class unique is that this class supports an event named CollectionChanged. This event will fire whenever a new item is inserted, a current item is removed (or relocated), or if the entire collection is modified. Like any event, CollectionChanged is defined in terms of a delegate, which in this case is NotifyCollectionChangedEventHandler. This delegate can call any method that takes an object as the first parameter, and a NotifyCollectionChangedEventArgs as the second. Consider the following Main() method, which populates an observable collection containing Person objects and wires up the CollectionChanged event:

class Program
{
   static void Main(string[] args)
   {
     // Make a collection to observe and add a few Person objects.
     ObservableCollection<Person> people = new ObservableCollection<Person>()
     {
        new Person{ FirstName = "Peter", LastName = "Murphy", Age = 52 },
        new Person{ FirstName = "Kevin", LastName = "Key", Age = 48 },
     };
     // Wire up the CollectionChanged event.
     people.CollectionChanged += people_CollectionChanged;
     // Now add a new item.
     people.Add(new Person("Fred", "Smith", 32));

     // Remove an item.
     people.RemoveAt(0);

     Console.ReadLine();
   }
   static void people_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
   {
       // What was the action that caused the event?
        Console.WriteLine("Action for this event: {0}", e.Action);

        // They removed something. 
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
        {
            Console.WriteLine("Here are the OLD items:");
            foreach (Person p in e.OldItems)
            {
                Console.WriteLine(p.ToString());
            }
            Console.WriteLine();
        }

        // They added something. 
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
        {
            // Now show the NEW items that were inserted.
            Console.WriteLine("Here are the NEW items:");
            foreach (Person p in e.NewItems)
            {
                Console.WriteLine(p.ToString());
            }
        }
   }
}

The incoming NotifyCollectionChangedEventArgs parameter defines two important properties, OldItems and NewItems, which will give you a list of items that were currently in the collection before the event fired, and the new items that were involved in the change. However, you will want to examine these lists only under the correct circumstances. Recall that the CollectionChanged event can fire when items are added, removed, relocated, or reset. To discover which of these actions triggered the event, you can use the Action property of NotifyCollectionChangedEventArgs. The Action property can be tested against any of the following members of the NotifyCollectionChangedAction enumeration:

public enum NotifyCollectionChangedAction
{
Add = 0,
Remove = 1,
Replace = 2,
Move = 3,
Reset = 4,
}

Members of System.Collections.ObjectModel

How to tell bash that the line continues on the next line

The character is a backslash \

From the bash manual:

The backslash character ‘\’ may be used to remove any special meaning for the next character read and for line continuation.

How to use *ngIf else?

In Angular 4.x.x You can use ngIf in four way to achieve simple if else procedure:

  1. Just Use If

    <div *ngIf="isValid">
        If isValid is true
    </div>
    
  2. Using If with Else (Please notice to templateName)

    <div *ngIf="isValid; else templateName">
        If isValid is true
    </div>
    
    <ng-template #templateName>
        If isValid is false
    </ng-template>
    
  3. Using If with Then (Please notice to templateName)

    <div *ngIf="isValid; then templateName">
        Here is never showing
    </div>
    
    <ng-template #templateName>
        If isValid is true
    </ng-template>
    
  4. Using If with Then and Else

    <div *ngIf="isValid; then thenTemplateName else elseTemplateName">
        Here is never showing
    </div>
    
    <ng-template #thenTemplateName>
        If isValid is true
    </ng-template>
    
    <ng-template #elseTemplateName>
        If isValid is false
    </ng-template>
    

Tip: ngIf evaluates the expression and then renders the then or else template in its place when expression is truthy or falsy respectively. Typically the:

  • then template is the inline template of ngIf unless bound to a different value.
  • else template is blank unless it is bound.

How do I toggle an element's class in pure JavaScript?

This is perhaps more succinct:

function toggle(element, klass) {
  var classes = element.className.match(/\S+/g) || [],
      index = classes.indexOf(klass);

  index >= 0 ? classes.splice(index, 1) : classes.push(klass);
  element.className = classes.join(' ');
}

Adding items to a JComboBox

Wrap the values in a class and override the toString() method.

class ComboItem
{
    private String key;
    private String value;

    public ComboItem(String key, String value)
    {
        this.key = key;
        this.value = value;
    }

    @Override
    public String toString()
    {
        return key;
    }

    public String getKey()
    {
        return key;
    }

    public String getValue()
    {
        return value;
    }
}

Add the ComboItem to your comboBox.

comboBox.addItem(new ComboItem("Visible String 1", "Value 1"));
comboBox.addItem(new ComboItem("Visible String 2", "Value 2"));
comboBox.addItem(new ComboItem("Visible String 3", "Value 3"));

Whenever you get the selected item.

Object item = comboBox.getSelectedItem();
String value = ((ComboItem)item).getValue();

How to set background image in Java?

<script>
function SetBack(dir) {
    document.getElementById('body').style.backgroundImage=dir;
}
SetBack('url(myniftybg.gif)');
</script>

How can I see the specific value of the sql_mode?

You need to login to your mysql terminal first using mysql -u username -p password

Then use this:

SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;

output will be like this:

STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER,NO_ENGINE_SUB

You can also set sql mode by this:

SET GLOBAL sql_mode=TRADITIONAL;

How to access to the parent object in c#

You would need to add a property to your Production class and set it to point back at its parent, this doesn't exist by default.

Generating Random Number In Each Row In Oracle Query

At first I thought that this would work:

select DBMS_Random.Value(1,9) output
from   ...

However, this does not generate an even distribution of output values:

select output,
       count(*)
from   (
       select round(dbms_random.value(1,9)) output
       from   dual
       connect by level <= 1000000)
group by output
order by 1

1   62423
2   125302
3   125038
4   125207
5   124892
6   124235
7   124832
8   125514
9   62557

The reasons are pretty obvious I think.

I'd suggest using something like:

floor(dbms_random.value(1,10))

Hence:

select output,
       count(*)
from   (
       select floor(dbms_random.value(1,10)) output
       from   dual
       connect by level <= 1000000)
group by output
order by 1

1   111038
2   110912
3   111155
4   111125
5   111084
6   111328
7   110873
8   111532
9   110953

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

How to add a classname/id to React-Bootstrap Component?

If you look at the code for the component you can see that it uses the className prop passed to it to combine with the row class to get the resulting set of classes (<Row className="aaa bbb"... works).Also, if you provide the id prop like <Row id="444" ... it will actually set the id attribute for the element.

Angular routerLink does not navigate to the corresponding component

The links are wrong, you have to do this:

<ul class="nav navbar-nav item">
    <li>
        <a [routerLink]="['/home']" routerLinkActive="active">Home</a>
    </li>
    <li>
        <a [routerLink]="['/about']" routerLinkActive="active">About this
        </a>
    </li>
</ul>

You can read this tutorial

How do I write to the console from a Laravel Controller?

Aha!

This can be done with the following PHP function:

error_log('Some message here.');

Found the answer here: Print something in PHP built-in web server

How can I expose more than 1 port with Docker?

If you are creating a container from an image and like to expose multiple ports (not publish) you can use the following command:

docker create --name `container name` --expose 7000 --expose 7001 `image name`

Now, when you start this container using the docker start command, the configured ports above will be exposed.

How do I discard unstaged changes in Git?

you have a very simple git command git checkout .

How to disable scrolling the document body?

add this css

body.disable-scroll {
    overflow: hidden;
}

and when to disable run this code

$("body").addClass("disable-scroll");

and when to enabled run this code

$("body").removeClass("disable-scroll")

importing a CSV into phpmyadmin

In phpMyAdmin v.4.6.5.2 there's a checkbox option "The first line of the file contains the table column names...." :

enter image description here

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

As @kosev said in his answer you can use JobIntentService. But I use an alternative solution - I catch IllegalStateException and start the service as foreground. For example, this function starts my service:

@JvmStatic
protected fun startService(intentAction: String, serviceType: Class<*>, intentExtraSetup: (Intent) -> Unit) {
    val context = App.context
    val intent = Intent(context, serviceType)
    intent.action = intentAction
    intentExtraSetup(intent)
    intent.putExtra(NEED_FOREGROUND_KEY, false)

    try {
        context.startService(intent)
    }
    catch (ex: IllegalStateException) {
        intent.putExtra(NEED_FOREGROUND_KEY, true)
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent)
        }
        else {
            context.startService(intent)
        }
    }
}

and when I process Intent I do such thing:

override fun onHandleIntent(intent: Intent?) {
    val needToMoveToForeground = intent?.getBooleanExtra(NEED_FOREGROUND_KEY, false) ?: false
    if(needToMoveToForeground) {
        val notification = notificationService.createSyncServiceNotification()
        startForeground(notification.second, notification.first)

        isInForeground = true
    }

    intent?.let {
        getTask(it)?.process()
    }
}

How can I manually generate a .pyc file from a .py file

You can compile individual files(s) from the command line with:

python -m compileall <file_1>.py <file_n>.py

Difference between "git add -A" and "git add ."

A more distilled quick answer:

Does both below (same as git add --all)

git add -A

Stages new + modified files

git add .

Stages modified + deleted files

git add -u

How to check python anaconda version installed on Windows 10 PC?

The folder containing your Anaconda installation contains a subfolder called conda-meta with json files for all installed packages, including one for Anaconda itself. Look for anaconda-<version>-<build>.json.

My file is called anaconda-5.0.1-py27hdb50712_1.json, and at the bottom is more info about the version:

"installed_by": "Anaconda2-5.0.1-Windows-x86_64.exe", 
"link": { "source": "C:\\ProgramData\\Anaconda2\\pkgs\\anaconda-5.0.1-py27hdb50712_1" }, 
"name": "anaconda", 
"platform": "win", 
"subdir": "win-64", 
"url": "https://repo.continuum.io/pkgs/main/win-64/anaconda-5.0.1-py27hdb50712_1.tar.bz2", 
"version": "5.0.1"

(Slightly edited for brevity.)

The output from conda -V is the conda version.

Return multiple values to a method caller

In C# 4, you will be able to use built-in support for tuples to handle this easily.

In the meantime, there are two options.

First, you can use ref or out parameters to assign values to your parameters, which get passed back to the calling routine.

This looks like:

void myFunction(ref int setMe, out int youMustSetMe);

Second, you can wrap up your return values into a structure or class, and pass them back as members of that structure. KeyValuePair works well for 2 - for more than 2 you would need a custom class or struct.

Run git pull over all subdirectories

You can try this

find . -type d -name .git -exec sh -c "cd \"{}\"/../ && pwd && git pull" \;

Also, you can add your customized output by adding one more && argument like.

find . -type d -name .git -exec sh -c "cd \"{}\"/../ && pwd && git pull && git status" \;

Getting "A potentially dangerous Request.Path value was detected from the client (&)"

If you want to allow Html tags only for few textbox in mvc

You can do one thing

in controller

 [ValidateInput(false)]
public ActionResult CreateNewHtml()  //view
{
    return View();
}
[ValidateInput(false)]
[HttpPost]
public ActionResult CreateNewHtml(cbs obj)//view cbs is database class
{
    repo.AddHtml(obj);
    return View();
}

How to delete zero components in a vector in Matlab?

You could use sparse(a), which would return

(1,2) 1

(1,4) 3

This allows you to keep the information about where your non-zero entries used to be.

trigger body click with jQuery

Interestingly, when I replaced this:

$("body").trigger("click")

With this:

jQuery("body").trigger("click")

It works!

How to join two sets in one line without using "|"

Assuming you also can't use s.union(t), which is equivalent to s | t, you could try

>>> from itertools import chain
>>> set(chain(s,t))
set([1, 2, 3, 4, 5, 6])

Or, if you want a comprehension,

>>> {i for j in (s,t) for i in j}
set([1, 2, 3, 4, 5, 6])

What are ODEX files in Android?

ART

According to the docs: http://web.archive.org/web/20170909233829/https://source.android.com/devices/tech/dalvik/configure an .odex file:

contains AOT compiled code for methods in the APK.

Furthermore, they appear to be regular shared libraries, since if you get any app, and check:

file /data/app/com.android.appname-*/oat/arm64/base.odex

it says:

base.odex: ELF shared object, 64-bit LSB arm64, stripped

and aarch64-linux-gnu-objdump -d base.odex seems to work and give some meaningful disassembly (but also some rubbish sections).

How do I decompile a .NET EXE into readable C# source code?

When Red Gate said there would no longer be a free version of .Net Reflector, I started using ILSpy and Telerik's JustDecompile. I have found ILSpy to decompile more accurately than JustDecompile (which is still in Beta). Red Gate has changed their decision and still have a free version of .Net Reflector, but now I like ILSpy.

From the ILSpy website (https://github.com/icsharpcode/ILSpy/):

ILSpy is the open-source .NET assembly browser and decompiler.

ILSpy Features

  • Assembly browsing
  • IL Disassembly
  • Decompilation to C#
  • Supports lambdas and 'yield return'
  • Shows XML documentation
  • Saving of resources
  • Search for types/methods/properties (substring)
  • Hyperlink-based type/method/property navigation
  • Base/Derived types navigation
  • Navigation history
  • BAML to XAML decompiler
  • Save Assembly as C# Project
  • Find usage of field/method
  • Extensible via plugins (MEF)

Update:

April 15, 2012, ILSpy 2.0 was released. New features compared with version 1.0:

  • Assembly Lists
  • Support for decompiling Expression trees
  • Support for lifted operatores on nullables
  • Decompile to Visual Basic
  • Search for multiple strings separated by space (searching for "Assembly manager" in ILSpy.exe would find AssemblyListManager)
  • Clicking on a local variable will highlight all other occurrences of that variable
  • Ctrl+F can be used to search within the decompiled code view

Update:

  • ILSpy 2.1 supports async/await decompilation

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

The problem is that you are passing a nullable type to a non-nullable type.

You can do any of the following solution:

A. Declare your dt as nullable

DateTime? dt = dateTime;

B. Use Value property of the the DateTime? datetime

DateTime dt = datetime.Value;

C. Cast it

DateTime dt = (DateTime) datetime;

ASP.NET Web Site or ASP.NET Web Application?

It is always depends on the requirement of your client. ASP.NET just includes flexible features that the user needs for security and easy maintenance of your application.

You can think of a Web application as a binary file that runs inside the ASP.NET framework. And Web sites as a static webpage that you can review and easily deploy source code to.

But the advantage and disadvantages of these two ASP.NET technologies come what is good.

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

After a certain amount of time, your access token expires.

To prevent this, you can request the 'offline_access' permission during the authentication, as noted here: Do Facebook Oauth 2.0 Access Tokens Expire?

JQuery addclass to selected div, remove class if another div is selected

**This can be achived easily using two different ways:**

1)We can also do this by using addClass and removeClass of Jquery
2)Toggle class of jQuery

**1)First Way**

$(documnet.ready(function(){
$('#dvId').click(function(){
  $('#dvId').removeClass('active class or your class name which you want to    remove').addClass('active class or your class name which you want to add');     
});
});

**2) Second Way**

i) Here we need to add the class which we want to show while page get loads.
ii)after clicking on div we we will toggle class i.e. the class is added while loading page gets removed and class which we provide in toggleClss gets added :)

<div id="dvId" class="ActiveClassname ">
</div

$(documnet.ready(function(){
$('#dvId').click(function(){
  $('#dvId').toggleClass('ActiveClassname InActiveClassName');     
});
});


Enjoy.....:)

If you any doubt free to ask any time...

Xcode stuck on Indexing

I too was facing the problem. I noticed that I have opened the same project twice.

So QuitXCode > Open your project and make sure only one instance is open > Clean > CleanBuild Folder in some cases > build.

It should work

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

In my case I used Tortoise SVN and made the mistake to also use the Visual Studio GIT functions at the same time. That made Visual Studio lock the HEAD file inside the .git folder so neither VS or Tortoise could access the repo and i got the "fatal: Not a git repo..." error from both applications.

Solution:

  1. Go inside the .git folder and rename "HEAD.lock" to just "HEAD"
  2. Decide for one GIT admin application and don't touch the other one

Insertion sort vs Bubble Sort Algorithms

Though both the sorts are O(N^2).The hidden constants are much smaller in Insertion sort.Hidden constants refer to the actual number of primitive operations carried out.

When insertion sort has better running time?

  1. Array is nearly sorted-notice that insertion sort does fewer operations in this case, than bubble sort.
  2. Array is of relatively small size: insertion sort you move elements around, to put the current element.This is only better than bubble sort if the number of elements is few.

Notice that insertion sort is not always better than bubble sort.To get the best of both worlds, you can use insertion sort if array is of small size, and probably merge sort(or quicksort) for larger arrays.

Unexpected token }

You have endless loop in place:

function save() {
    var filename = id('filename').value;
    var name = id('name').value;
    var text = id('text').value;
    save(filename, name, text);
}

No idea what you're trying to accomplish with that endless loop but first of all get rid of it and see if things are working.

Limit String Length

You can use something similar to the below:

if (strlen($str) > 10)
   $str = substr($str, 0, 7) . '...';

How to Calculate Execution Time of a Code Snippet in C++

I created a lambda that calls you function call N times and returns you the average.

double c = BENCHMARK_CNT(25, fillVectorDeque(variable));

You can find the c++11 header here.

Convert all strings in a list to int

A little bit more expanded than list comprehension but likewise useful:

def str_list_to_int_list(str_list):
    n = 0
    while n < len(str_list):
        str_list[n] = int(str_list[n])
        n += 1
    return(str_list)

e.g.

>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]

Also:

def str_list_to_int_list(str_list):
    int_list = [int(n) for n in str_list]
    return int_list

Rounding to two decimal places in Python 2.7?

When we use the round() function, it will not give correct values.

you can check it using, round (2.735) and round(2.725)

please use

import math
num = input('Enter a number')
print(math.ceil(num*100)/100)

How to call multiple functions with @click in vue?

On Vue 2.3 and above you can do this:

<div v-on:click="firstFunction(); secondFunction();"></div>
// or
<div @click="firstFunction(); secondFunction();"></div>

How do you programmatically set an attribute?

Usually, we define classes for this.

class XClass( object ):
   def __init__( self ):
       self.myAttr= None

x= XClass()
x.myAttr= 'magic'
x.myAttr

However, you can, to an extent, do this with the setattr and getattr built-in functions. However, they don't work on instances of object directly.

>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'

They do, however, work on all kinds of simple classes.

class YClass( object ):
    pass

y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr

Downloading images with node.js

This is an extension to Cezary's answer. If you want to download it to a specific directory, use this. Also, use const instead of var. Its safe this way.

const fs = require('fs');
const request = require('request');
var download = function(uri, filename, callback){
  request.head(uri, function(err, res, body){    
    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};

download('https://www.google.com/images/srpr/logo3w.png', './images/google.png', function(){
  console.log('done');
});

How to include a sub-view in Blade templates?

You can use the blade template engine:

@include('view.name') 

'view.name' would live in your main views folder:

// for laravel 4.X
app/views/view/name.blade.php  

// for laravel 5.X
resources/views/view/name.blade.php

Another example

@include('hello.world');

would display the following view

// for laravel 4.X
app/views/hello/world.blade.php

// for laravel 5.X
resources/views/hello/world.blade.php

Another example

@include('some.directory.structure.foo');

would display the following view

// for Laravel 4.X
app/views/some/directory/structure/foo.blade.php

// for Laravel 5.X
resources/views/some/directory/structure/foo.blade.php

So basically the dot notation defines the directory hierarchy that your view is in, followed by the view name, relative to app/views folder for laravel 4.x or your resources/views folder in laravel 5.x

ADDITIONAL

If you want to pass parameters: @include('view.name', array('paramName' => 'value'))

You can then use the value in your views like so <p>{{$paramName}}</p>

How to randomly select rows in SQL?

Maybe this site will be of assistance.

For those who don't want to click through:

SELECT TOP 1 column FROM table
ORDER BY NEWID()

C non-blocking keyboard input

As already stated, you can use sigaction to trap ctrl-c, or select to trap any standard input.

Note however that with the latter method you also need to set the TTY so that it's in character-at-a-time rather than line-at-a-time mode. The latter is the default - if you type in a line of text it doesn't get sent to the running program's stdin until you press enter.

You'd need to use the tcsetattr() function to turn off ICANON mode, and probably also disable ECHO too. From memory, you also have to set the terminal back into ICANON mode when the program exits!

Just for completeness, here's some code I've just knocked up (nb: no error checking!) which sets up a Unix TTY and emulates the DOS <conio.h> functions kbhit() and getch():

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <termios.h>

struct termios orig_termios;

void reset_terminal_mode()
{
    tcsetattr(0, TCSANOW, &orig_termios);
}

void set_conio_terminal_mode()
{
    struct termios new_termios;

    /* take two copies - one for now, one for later */
    tcgetattr(0, &orig_termios);
    memcpy(&new_termios, &orig_termios, sizeof(new_termios));

    /* register cleanup handler, and set the new terminal mode */
    atexit(reset_terminal_mode);
    cfmakeraw(&new_termios);
    tcsetattr(0, TCSANOW, &new_termios);
}

int kbhit()
{
    struct timeval tv = { 0L, 0L };
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(0, &fds);
    return select(1, &fds, NULL, NULL, &tv);
}

int getch()
{
    int r;
    unsigned char c;
    if ((r = read(0, &c, sizeof(c))) < 0) {
        return r;
    } else {
        return c;
    }
}

int main(int argc, char *argv[])
{
    set_conio_terminal_mode();

    while (!kbhit()) {
        /* do some work */
    }
    (void)getch(); /* consume the character */
}

how to get request path with express req object

For version 4.x you can now use the req.baseUrl in addition to req.path to get the full path. For example, the OP would now do something like:

//auth required or redirect
app.use('/account', function(req, res, next) {
  console.log(req.baseUrl + req.path);  // => /account

  if(!req.session.user) {
    res.redirect('/login?ref=' + encodeURIComponent(req.baseUrl + req.path));  // => /login?ref=%2Faccount
  } else {
    next();
  }
});

How to make a Qt Widget grow with the window size?

I found it was impossible to assign a layout to the centralwidget until I had added at least one child beneath it. Then I could highlight the tiny icon with the red 'disabled' mark and then click on a layout in the Designer toolbar at top.

SQL Server CTE and recursion example

The execution process is really confusing with recursive CTE, I found the best answer at https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx and the abstract of the CTE execution process is as below.

The semantics of the recursive execution is as follows:

  1. Split the CTE expression into anchor and recursive members.
  2. Run the anchor member(s) creating the first invocation or base result set (T0).
  3. Run the recursive member(s) with Ti as an input and Ti+1 as an output.
  4. Repeat step 3 until an empty set is returned.
  5. Return the result set. This is a UNION ALL of T0 to Tn.

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

I also have the same problem, and the solution is I didn't bind the event in my onClick. so when it renders for the first time and the data is more, which ends up calling the state setter again, which triggers React to call your function again and so on.

export default function Component(props) {

function clickEvent (event, variable){
    console.log(variable);
}

return (
    <div>
        <IconButton
            key="close"
            aria-label="Close"
            color="inherit"
            onClick={e => clickEvent(e, 10)} // or you can call like this:onClick={() => clickEvent(10)} 
        >
    </div>
)
}

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

To add a bit to accepted answer ...

If you get an UnfinishedStubbingException, be sure to set the method to be stubbed after the when closure, which is different than when you write Mockito.when

Mockito.doNothing().when(mock).method()    //method is declared after 'when' closes

Mockito.when(mock.method()).thenReturn(something)   //method is declared inside 'when'

How to connect to Oracle 11g database remotely

First, make sure the listener on database server (computer A) that receives client connection requests is running. To do so, run lsnrctl status command.

In case, if you get TNS:no listener message (see below image), it means listener service is not running. To start it, run lsnrctl start command.

enter image description here

Second, for database operations and connectivity from remote clients, the following executables must be added to the Windows Firewall exception list: (see image)

Oracle_home\bin\oracle.exe - Oracle Database executable

Oracle_home\bin\tnslsnr.exe - Oracle Listener

enter image description here

Finally, install oracle instant client on client machine (computer B) and run:

sqlplus user/password@computerA:port/XE

writing a batch file that opens a chrome URL

It's very simple. Just try:

start chrome https://www.google.co.in/

it will open the Google page in the Chrome browser.

If you wish to open the page in Firefox, try:

start firefox https://www.google.co.in/

Have Fun!

Get raw POST body in Python Flask regardless of Content-Type header

request.data will be empty if request.headers["Content-Type"] is recognized as form data, which will be parsed into request.form. To get the raw data regardless of content type, use request.get_data().

request.data calls request.get_data(parse_form_data=True), which results in the different behavior for form data.

Save current directory in variable using Bash?

One more variant:

export PATH=$PATH:\`pwd`:/foo/bar

smtpclient " failure sending mail"

apparently this problem got solved just by increasing queue size on my 3rd party smtp server. but the answer by Nip sounds like it is fairly usefull too

CentOS 7 and Puppet unable to install nc

Nc is a link to nmap-ncat.

It would be nice to use nmap-ncat in your puppet, because NC is a virtual name of nmap-ncat.

Puppet cannot understand the links/virtualnames

your puppet should be:

package {
  'nmap-ncat':
    ensure => installed;
}

Why is Java Vector (and Stack) class considered obsolete or deprecated?

You can use the synchronizedCollection/List method in java.util.Collection to get a thread-safe collection from a non-thread-safe one.

Are static methods inherited in Java?

Static members will not be inherited to subclass because inheritance is only for non-static members.. And static members will be loaded inside static pool by class loader. Inheritance is only for those members which are loaded inside the object

How do I rewrite URLs in a proxy response in NGINX

You can use the following nginx configuration example:

upstream adminhost {
  server adminhostname:8080;
}

server {
  listen 80;

  location ~ ^/admin/(.*)$ {
    proxy_pass http://adminhost/$1$is_args$args;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host $server_name;
  }
}

How to check programmatically if an application is installed or not in Android?

A cool answer to other problems. If you do not want to differentiate "com.myapp.debug" and "com.myapp.release" for example !

public static boolean isAppInstalled(final Context context, final String packageName) {
    final List<ApplicationInfo> appsInfo = context.getPackageManager().getInstalledApplications(0);
    for (final ApplicationInfo appInfo : appsInfo) {
        if (appInfo.packageName.contains(packageName)) return true;
    }
    return false;
}

Combating AngularJS executing controller twice

When using angular-ui-router with Angular 1.3+, there was an issue about Rendering views twice on route transition. This resulted in executing controllers twice, too. None of the proposed solutions worked for me.

However, updating angular-ui-router from 0.2.11 to 0.2.13 solved problem for me.

How to get the background color of an HTML element?

It depends which style from the div you need. Is this a background style which was defined in CSS or background style which was added through javascript(inline) to the current node?

In case of CSS style, you should use computed style. Like you do in getStyle().

With inline style you should use node.style reference: x.style.backgroundColor;

Also notice, that you pick the style by using camelCase/non hyphen reference, so not background-color, but backgroundColor;

Is it possible to add dynamically named properties to JavaScript object?

I know there are several answers to this post already, but I haven't seen one wherein there are multiple properties and they are within an array. And this solution by the way is for ES6.

For illustration, let's say we have an array named person with objects inside:

 let Person = [{id:1, Name: "John"}, {id:2, Name: "Susan"}, {id:3, Name: "Jet"}]

So, you can add a property with corresponding value. Let's say we want to add a Language with a default value of EN.

Person.map((obj)=>({...obj,['Language']:"EN"}))

The Person array now would become like this:

Person = [{id:1, Name: "John", Language:"EN"}, 
{id:2, Name: "Susan", Language:"EN"}, {id:3, Name: "Jet", Language:"EN"}]

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

How do I bind onchange event of a TextBox using JQuery?

You're looking for keydown/press/up

$("#inputID").keydown(function(event) {
    alert(event.keyCode);
});

or using bind $("#inputID").bind('onkeydown', ...

http://docs.jquery.com/Events

Query an XDocument for elements by name at any depth

(Code and Instructions is for C# and may need to be slightly altered for other languages)

This example works perfect if you want to read from a Parent Node that has many children, for example look at the following XML;

<?xml version="1.0" encoding="UTF-8"?> 
<emails>
    <emailAddress>[email protected]</emailAddress>
    <emailAddress>[email protected]</emailAddress>
    <emailAddress>rgreen@set_ig.ca</emailAddress> 
</emails>

Now with this code below (keeping in mind that the XML File is stored in resources (See the links at end of snippet for help on resources) You can obtain each email address within the "emails" tag.

XDocument doc = XDocument.Parse(Properties.Resources.EmailAddresses);

var emailAddresses = (from emails in doc.Descendants("emailAddress")
                      select emails.Value);

foreach (var email in emailAddresses)
{
    //Comment out if using WPF or Windows Form project
    Console.WriteLine(email.ToString());

   //Remove comment if using WPF or Windows Form project
   //MessageBox.Show(email.ToString());
}

Results

  1. [email protected]
  2. [email protected]
  3. rgreen@set_ig.ca

Note: For Console Application and WPF or Windows Forms you must add the "using System.Xml.Linq;" Using directive at the top of your project, for Console you will also need to add a reference to this namespace before adding the Using directive. Also for Console there will be no Resource file by default under the "Properties folder" so you have to manually add the Resource file. The MSDN articles below, explain this in detail.

Adding and Editing Resources

How to: Add or Remove Resources

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

The solution of removing the '-rcX' part works. I wanted to provide some more detail on why the error is happening. The issue is with https://android.googlesource.com/platform/tools/base/+/master/build-system/gradle/src/main/groovy/com/android/build/gradle/BasePlugin.java#230

There is a default 40 days 'retirement age' for plugins that don't have a version or contain 'rc', 'alpha', or 'beta'.

Why am I getting error for apple-touch-icon-precomposed.png

An alternative solution is to simply add a route to your routes.rb

It basically catches the Apple request and renders a 404 back to the client. This way your log files aren't cluttered.

# routes.rb at the near-end
match '/:png', via: :get, controller: 'application', action: 'apple_touch_not_found', png: /apple-touch-icon.*\.png/

then add a method 'apple_touch_not_found' to your application_controller.rb

# application_controller.rb
def apple_touch_not_found
  render  plain: 'apple-touch icons not found', status: 404
end

Eclipse fonts and background color

If you are having trouble with Eclipse 2019 and using a dark theme and setting the background and having it not change: There seems to be a recent Eclipse bug. I suggest you look here or here for workarounds.

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

Short answer: use mongoose.Types.ObjectId.

Mongoose (but not mongo) can accept object Ids as strings and "cast" them properly for you, so just use:

MyClass.findById(req.params.id)

However, the caveat is if req.params.id is not a valid format for a mongo ID string, that will throw an exception which you must catch.

So the main confusing thing to understand is that mongoose.SchemaTypes has stuff you only use when defining mongoose schemas, and mongoose.Types has the stuff you use when creating data objects you want to store in the database or query objects. So mongoose.Types.ObjectId("51bb793aca2ab77a3200000d") works, will give you an object you can store in the database or use in queries, and will throw an exception if given an invalid ID string.

findOne takes a query object and passes a single model instance to the callback. And findById is literally a wrapper of findOne({_id: id}) (see source code here). Just find takes a query object and passes an array of matching model instances to the callback.

Just go slow. It's confusing but I can guarantee you you are getting confused and not hitting bugs in mongoose at this point. It's a pretty mature library, but it takes some time to get the hang of it.

The other suspect thing I see in your snippet is not using new when instantiating ChildClass. Beyond that, you'll need to post your schema code in order for us to help you tract down any CastErrors that remain.

Call javascript from MVC controller action

There are ways you can mimic this by having your controller return a piece of data, which your view can then translate into a JavaScript call.

We do something like this to allow people to use RESTful URLs to share their jquery-rendered workspace view.

In our case we pass a list of components which need to be rendered and use Razor to translate these back into jquery calls.

Playing HTML5 video on fullscreen in android webview

Tested on Android 9.0 version

None of the answers worked for me . This is the final thing worked

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

    WebView mWebView;


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


        mWebView = (WebView) findViewById(R.id.webView);


        mWebView.setWebViewClient(new WebViewClient());
        mWebView.setWebChromeClient(new MyChrome());
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);

       if (savedInstanceState == null) {
          mWebView.loadUrl("https://www.youtube.com/");
       }

    }


    private class MyChrome extends WebChromeClient {

        private View mCustomView;
        private WebChromeClient.CustomViewCallback mCustomViewCallback;
        protected FrameLayout mFullscreenContainer;
        private int mOriginalOrientation;
        private int mOriginalSystemUiVisibility;

        MyChrome() {}

        public Bitmap getDefaultVideoPoster()
        {
            if (mCustomView == null) {
                return null;
            }
            return BitmapFactory.decodeResource(getApplicationContext().getResources(), 2130837573);
        }

        public void onHideCustomView()
        {
            ((FrameLayout)getWindow().getDecorView()).removeView(this.mCustomView);
            this.mCustomView = null;
            getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility);
            setRequestedOrientation(this.mOriginalOrientation);
            this.mCustomViewCallback.onCustomViewHidden();
            this.mCustomViewCallback = null;
        }

        public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback)
        {
            if (this.mCustomView != null)
            {
                onHideCustomView();
                return;
            }
            this.mCustomView = paramView;
            this.mOriginalSystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();
            this.mOriginalOrientation = getRequestedOrientation();
            this.mCustomViewCallback = paramCustomViewCallback;
            ((FrameLayout)getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1));
            getWindow().getDecorView().setSystemUiVisibility(3846 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

 @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mWebView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mWebView.restoreState(savedInstanceState);
    }
}

In AndroidManifest.xml

<activity
  android:name=".MainActivity"
  android:configChanges="orientation|screenSize" />

Source Monster Techno

Spring @Value is not resolving to value from property file

Please note that if you have multiple application.properties files throughout your codebase, then try adding your value to the parent project's property file.

You can check your project's pom.xml file to identify what the parent project of your current project is.

Alternatively, try using environment.getProperty() instead of @Value.

change cursor to finger pointer

_x000D_
_x000D_
div{cursor: pointer; color:blue}_x000D_
_x000D_
p{cursor: text; color:red;}
_x000D_
<div> im Pointer  cursor </div> _x000D_
<p> im Txst cursor </p> 
_x000D_
_x000D_
_x000D_

How to make the tab character 4 spaces instead of 8 spaces in nano?

For anyone who may stumble across this old question ...

There is one thing that I think needs to be addressed.

~/.nanorc is used to apply your user specific settings to nano, so if you are editing files that require the use of sudo nano for permissions then this is not going to work.

When using sudo your custom user configuration files will not be loaded when opening a program, as you are not running the program from your account so none of your configuration changes in ~/.nanorc will be applied.

If this is the situation you find yourself in (wanting to run sudo nano and use your own config settings) then you have three options :

  • using command line flags when running sudo nano
  • editing the /root/.nanorc file
  • editing the /etc/nanorc global config file

Keep in mind that /etc/nanorc is a global configuration file and as such it affects all users, which may or may not be a problem depending on whether you have a multi-user system.

Also, user config files will override the global one, so if you were to edit /etc/nanorc and ~/.nanorc with different settings, when you run nano it will load the settings from ~/.nanorc but if you run sudo nano then it will load the settings from /etc/nanorc.

Same goes for /root/.nanorc this will override /etc/nanorc when running sudo nano

Using flags is probably the best option unless you have a lot of options.

Make REST API call in Swift

Swift 4 - GET request

var request = URLRequest(url: URL(string: "http://example.com/api/v1/example")!)
request.httpMethod = "GET"

URLSession.shared.dataTask(with: request, completionHandler: { data, response, error -> Void in
    do {
        let jsonDecoder = JSONDecoder()
        let responseModel = try jsonDecoder.decode(CustomDtoClass.self, from: data!)
        print(responseModel)
    } catch {
        print("JSON Serialization error")
    }
}).resume()

Don't forget to configure App Transport Security Settings to add your domain to the exceptions and allow insecure http requests if you're hitting endpoints without using HTTPS.

You can use a tool like http://www.json4swift.com/ to autogenerate your Codeable Mappings from your JSON responses.

What is JavaScript's highest integer value that a number can go to without losing precision?

The short answer is “it depends.”

If you’re using bitwise operators anywhere (or if you’re referring to the length of an Array), the ranges are:

Unsigned: 0…(-1>>>0)

Signed: (-(-1>>>1)-1)…(-1>>>1)

(It so happens that the bitwise operators and the maximum length of an array are restricted to 32-bit integers.)

If you’re not using bitwise operators or working with array lengths:

Signed: (-Math.pow(2,53))…(+Math.pow(2,53))

These limitations are imposed by the internal representation of the “Number” type, which generally corresponds to IEEE 754 double-precision floating-point representation. (Note that unlike typical signed integers, the magnitude of the negative limit is the same as the magnitude of the positive limit, due to characteristics of the internal representation, which actually includes a negative 0!)

Are there any naming convention guidelines for REST APIs?

I have a list of guidelines at http://soaprobe.blogspot.co.uk/2012/10/soa-rest-service-naming-guideline.html which we have used in prod. Guidelines are always debatable... I think consistency is sometimes more important than getting things perfect (if there is such a thing).

error LNK2005, already defined?

Presence of int k; in the header file causes symbol k to be defined within each translation unit this header is included to while linker expects it to be defined only once (aka One Definition Rule Violation).

While suggestion involving extern are not wrong, extern is a C-ism and should not be used.

Pre C++17 solution that would allow variable in header file to be defined in multiple translation units without causing ODR violation would be conversion to template:

template<typename x_Dummy = void> class
t_HeaderVariableHolder
{
    public: static int s_k;
};

template<typename x_Dummy> int t_HeaderVariableHolder<x_Dummy>::s_k{};

// Getter is necessary to decouple variable storage implementation details from access to it.
inline int & Get_K() noexcept
{
    return t_HeaderVariableHolder<>::s_k;
}

With C++17 things become much simpler as it allows inline variables:

inline int g_k{};

// Getter is necessary to decouple variable storage implementation details from access to it.
inline int & Get_K() noexcept
{
    return g_k;
}

nodejs mysql Error: Connection lost The server closed the connection

Try to use this code to handle server disconnect:

var db_config = {
  host: 'localhost',
    user: 'root',
    password: '',
    database: 'example'
};

var connection;

function handleDisconnect() {
  connection = mysql.createConnection(db_config); // Recreate the connection, since
                                                  // the old one cannot be reused.

  connection.connect(function(err) {              // The server is either down
    if(err) {                                     // or restarting (takes a while sometimes).
      console.log('error when connecting to db:', err);
      setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
    }                                     // to avoid a hot loop, and to allow our node script to
  });                                     // process asynchronous requests in the meantime.
                                          // If you're also serving http, display a 503 error.
  connection.on('error', function(err) {
    console.log('db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
      handleDisconnect();                         // lost due to either server restart, or a
    } else {                                      // connnection idle timeout (the wait_timeout
      throw err;                                  // server variable configures this)
    }
  });
}

handleDisconnect();

In your code i am missing the parts after connection = mysql.createConnection(db_config);

How to disable all <input > inside a form with jQuery?

you can add

 <fieldset class="fieldset">

and then you can call

 $('.fieldset').prop('disabled', true);