Programs & Examples On #Traveling salesman

The "traveling salesman problem" is a classical computer science problem which involves finding the shortest path which could be taken by a hypothetical salesman to make a single visit to each location on a map (in a graph).

How to list all the available keyspaces in Cassandra?

I suggest a combination of grep and awk:

root@DC1-Node1:/home# nodetool tablestats | grep "Keyspace :" | awk -F ":" '{print $2}'
 system_traces
 system
 system_distributed
 system_schema
 device_tool
 system_tool

How do I show the schema of a table in a MySQL database?

SHOW CREATE TABLE yourTable;

or

SHOW COLUMNS FROM yourTable;

How do I calculate a trendline for a graph?

Here's what I ended up using.

public class DataPoint<T1,T2>
{
    public DataPoint(T1 x, T2 y)
    {
        X = x;
        Y = y;
    }

    [JsonProperty("x")]
    public T1 X { get; }

    [JsonProperty("y")]
    public T2 Y { get; }
}

public class Trendline
{
    public Trendline(IEnumerable<DataPoint<long, decimal>> dataPoints)
    {
        int count = 0;
        long sumX = 0;
        long sumX2 = 0;
        decimal sumY = 0;
        decimal sumXY = 0;

        foreach (var dataPoint in dataPoints)
        {
            count++;
            sumX += dataPoint.X;
            sumX2 += dataPoint.X * dataPoint.X;
            sumY += dataPoint.Y;
            sumXY += dataPoint.X * dataPoint.Y;
        }

        Slope = (sumXY - ((sumX * sumY) / count)) / (sumX2 - ((sumX * sumX) / count));
        Intercept = (sumY / count) - (Slope * (sumX / count));
    }

    public decimal Slope { get; private set; }
    public decimal Intercept { get; private set; }
    public decimal Start { get; private set; }
    public decimal End { get; private set; }

    public decimal GetYValue(decimal xValue)
    {
        return Slope * xValue + Intercept;
    }
}

My data set is using a Unix timestamp for the x-axis and a decimal for the y. Change those datatypes to fit your need. I do all the sum calculations in one iteration for the best possible performance.

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

Just to be complete...

For 32 bit OS you must add a registry entry to:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION

*******OR*******

For 64 bit OS you must add a registry entry to:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION

This entry must be a DWORD, with the name being the name of your executable, that hosts the Webbrowser control; i.e.:

myappname.exe (DON'T USE "Contoso.exe" as in the MSDN web page...it's just a placeholder name)

Then give it a DWORD value, according to the table on:

http://msdn.microsoft.com/en-us/library/ee330730(v=vs.85).aspx#browser_emulation

I changed to 11001 decimal or 0x2AF9 hex --- (IE 11 EMULATION) since that isn't the DEFAULT value (if you have IE 11 installed -- or whatever version).

That MSDN article contains notes on several other Registry changes that affects Internet Explorer web browser behavior.

MSVCP120d.dll missing

I have the same problem with you when I implement OpenCV 2.4.11 on VS 2015. I tried to solve this problem by three methods one by one but they didn't work:

  1. download MSVCP120.DLL online and add it to windows path and OpenCV bin file path
  2. install Visual C++ Redistributable Packages for Visual Studio 2013 both x86 and x86
  3. adjust Debug mode. Go to configuration > C/C++ > Code Generation > Runtime Library and select Multi-threaded Debug (/MTd)

Finally I solved this problem by reinstalling VS2015 with selecting all the options that can be installed, it takes a lot space but it really works.

R legend placement in a plot

?legend will tell you:

Arguments

x, y
the x and y co-ordinates to be used to position the legend. They can be specified by keyword or in any way which is accepted by xy.coords: See ‘Details’.

Details:

Arguments x, y, legend are interpreted in a non-standard way to allow the coordinates to be specified via one or two arguments. If legend is missing and y is not numeric, it is assumed that the second argument is intended to be legend and that the first argument specifies the coordinates.

The coordinates can be specified in any way which is accepted by xy.coords. If this gives the coordinates of one point, it is used as the top-left coordinate of the rectangle containing the legend. If it gives the coordinates of two points, these specify opposite corners of the rectangle (either pair of corners, in any order).

The location may also be specified by setting x to a single keyword from the list bottomright, bottom, bottomleft, left, topleft, top, topright, right and center. This places the legend on the inside of the plot frame at the given location. Partial argument matching is used. The optional inset argument specifies how far the legend is inset from the plot margins. If a single value is given, it is used for both margins; if two values are given, the first is used for x- distance, the second for y-distance.

How to update UI from another thread running in another class

I am going to throw you a curve ball here. If I have said it once I have said it a hundred times. Marshaling operations like Invoke or BeginInvoke are not always the best methods for updating the UI with worker thread progress.

In this case it usually works better to have the worker thread publish its progress information to a shared data structure that the UI thread then polls at regular intervals. This has several advantages.

  • It breaks the tight coupling between the UI and worker thread that Invoke imposes.
  • The UI thread gets to dictate when the UI controls get updated...the way it should be anyway when you really think about it.
  • There is no risk of overrunning the UI message queue as would be the case if BeginInvoke were used from the worker thread.
  • The worker thread does not have to wait for a response from the UI thread as would be the case with Invoke.
  • You get more throughput on both the UI and worker threads.
  • Invoke and BeginInvoke are expensive operations.

So in your calcClass create a data structure that will hold the progress information.

public class calcClass
{
  private double percentComplete = 0;

  public double PercentComplete
  {
    get 
    { 
      // Do a thread-safe read here.
      return Interlocked.CompareExchange(ref percentComplete, 0, 0);
    }
  }

  public testMethod(object input)
  {
    int count = 1000;
    for (int i = 0; i < count; i++)
    {
      Thread.Sleep(10);
      double newvalue = ((double)i + 1) / (double)count;
      Interlocked.Exchange(ref percentComplete, newvalue);
    }
  }
}

Then in your MainWindow class use a DispatcherTimer to periodically poll the progress information. Configure the DispatcherTimer to raise the Tick event on whatever interval is most appropriate for your situation.

public partial class MainWindow : Window
{
  public void YourDispatcherTimer_Tick(object sender, EventArgs args)
  {
    YourProgressBar.Value = calculation.PercentComplete;
  }
}

Make EditText ReadOnly

Try using

editText.setEnabled(false);
editText.setClickable(false);

VBA - If a cell in column A is not blank the column B equals

Another way (Using Formulas in VBA). I guess this is the shortest VBA code as well?

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long

    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        .Range("B1:B" & lRow).Formula = "=If(A1<>"""",""My Text"","""")"
        .Range("B1:B" & lRow).Value = .Range("B1:B" & lRow).Value
    End With
End Sub

There is no argument given that corresponds to the required formal parameter - .NET Error

You have a constructor which takes 2 parameters. You should write something like:

new ErrorEventArg(errorMsv, lastQuery)

It's less code and easier to read.

EDIT

Or, in order for your way to work, you can try writing a default constructor for ErrorEventArg which would have no parameters, like this:

public ErrorEventArg() {}

MySQL root password change

Using the mysqladmin command-line utility to alter the MySQL password:

mysqladmin --user=root --password=oldpassword password "newpassword"

Source

Pass Additional ViewData to a Strongly-Typed Partial View

@Html.Partial("_Header", new ViewDataDictionary { { "HeaderName", "User Management" }, { "TitleName", "List Of Users" } })
or
@{Html.RenderPartial("_Header", new ViewDataDictionary { { "HeaderName", "User Management" }, { "TitleName", "List Of Users" } });}

Partial Page(_Header):

<div class="row titleBlock">
    <h1>@ViewData["HeaderName"].ToString()</h1>
    <h5>@ViewData["TitleName"].ToString()</h5>
</div>

Omitting one Setter/Getter in Lombok

You can pass an access level to the @Getter and @Setter annotations. This is useful to make getters or setters protected or private. It can also be used to override the default.

With @Data, you have public access to the accessors by default. You can now use the special access level NONE to completely omit the accessor, like this:

@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private int mySecret;

PreparedStatement with list of parameters in a IN clause

You need jdbc4 then you can use setArray!

In my case it didn't worked, as the UUID Datatype in postgres seems to still have its weak spots, but for the usual types it works.

ps.setArray(1, connection.createArrayOf("$VALUETYPE",myValuesAsArray));

Of course replace $VALUETYPE and myValuesAsArray with the correct values.

Remark following Marks comment:

Your database and the driver needs to support this! I tried Postgres 9.4 but I think this has been introduced earlier. You need a jdbc 4 driver, otherwise setArray won't be available. I used the postgresql 9.4-1201-jdbc41 driver that ships with spring boot

Resolve Javascript Promise outside function scope

Yes, you can. By using the CustomEvent API for the browser environment. And using an event emitter project in node.js environments. Since the snippet in the question is for the browser environment, here is a working example for the same.

_x000D_
_x000D_
function myPromiseReturningFunction(){_x000D_
  return new Promise(resolve => {_x000D_
    window.addEventListener("myCustomEvent", (event) => {_x000D_
       resolve(event.detail);_x000D_
    }) _x000D_
  })_x000D_
}_x000D_
_x000D_
_x000D_
myPromiseReturningFunction().then(result => {_x000D_
   alert(result)_x000D_
})_x000D_
_x000D_
document.getElementById("p").addEventListener("click", () => {_x000D_
   window.dispatchEvent(new CustomEvent("myCustomEvent", {detail : "It works!"}))_x000D_
})
_x000D_
<p id="p"> Click me </p>
_x000D_
_x000D_
_x000D_

I hope this answer is useful!

Overriding interface property type defined in Typescript d.ts file

If someone else needs a generic utility type to do this, I came up with the following solution:

/**
 * Returns object T, but with T[K] overridden to type U.
 * @example
 * type MyObject = { a: number, b: string }
 * OverrideProperty<MyObject, "a", string> // returns { a: string, b: string }
 */
export type OverrideProperty<T, K extends keyof T, U> = Omit<T, K> & { [P in keyof Pick<T, K>]: U };

I needed this because in my case, the key to override was a generic itself.

If you don't have Omit ready, see Exclude property from type.

how to parse JSONArray in android

getJSONArray(attrname) will get you an array from the object of that given attribute name in your case what is happening is that for

{"abridged_cast":["name": blah...]}
^ its trying to search for a value "characters"

but you need to get into the array and then do a search for "characters"

try this

String json="{'abridged_cast':[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},{'name':'JessicaLange','id':'162653068','characters':['Dwan']},{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";

    JSONObject jsonResponse;
    try {
        ArrayList<String> temp = new ArrayList<String>();
        jsonResponse = new JSONObject(json);
        JSONArray movies = jsonResponse.getJSONArray("abridged_cast");
        for(int i=0;i<movies.length();i++){
            JSONObject movie = movies.getJSONObject(i);
            JSONArray characters = movie.getJSONArray("characters");
            for(int j=0;j<characters.length();j++){
                temp.add(characters.getString(j));
            }
        }
        Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

checked it :)

Rounding a double to turn it into an int (java)

What is the return type of the round() method in the snippet?

If this is the Math.round() method, it returns a Long when the input param is Double.

So, you will have to cast the return value:

int a = (int) Math.round(doubleVar);

Iterating through array - java

You can import the lib org.apache.commons.lang.ArrayUtils

There is a static method where you can pass in an int array and a value to check for.

contains(int[] array, int valueToFind) Checks if the value is in the given array.

ArrayUtils.contains(intArray, valueToFind);

ArrayUtils API

Make TextBox uneditable

If you want your TextBox uneditable you should make it ReadOnly.

Android: How to Programmatically set the size of a Layout

my sample code

wv = (WebView) findViewById(R.id.mywebview);
wv.getLayoutParams().height = LayoutParams.MATCH_PARENT; // LayoutParams: android.view.ViewGroup.LayoutParams
// wv.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
wv.requestLayout();//It is necesary to refresh the screen

Mod of negative number is melting my brain

For the more performance aware devs

uint wrap(int k, int n) ((uint)k)%n

A small performance comparison

Modulo: 00:00:07.2661827 ((n%x)+x)%x)
Cast:   00:00:03.2202334 ((uint)k)%n
If:     00:00:13.5378989 ((k %= n) < 0) ? k+n : k

As for performance cost of cast to uint have a look here

Calling class staticmethod within the class body?

What about this solution? It does not rely on knowledge of @staticmethod decorator implementation. Inner class StaticMethod plays as a container of static initialization functions.

class Klass(object):

    class StaticMethod:
        @staticmethod  # use as decorator
        def _stat_func():
            return 42

    _ANS = StaticMethod._stat_func()  # call the staticmethod

    def method(self):
        ret = self.StaticMethod._stat_func() + Klass._ANS
        return ret

HTML CSS How to stop a table cell from expanding

No javascript, just CSS. Works fine!

   .no-break-out {
      /* These are technically the same, but use both */
      overflow-wrap: break-word;
      word-wrap: break-word;

      -ms-word-break: break-all;
      /* This is the dangerous one in WebKit, as it breaks things wherever */
      word-break: break-all;
      /* Instead use this non-standard one: */
      word-break: break-word;

      /* Adds a hyphen where the word breaks, if supported (No Blink) */
      -ms-hyphens: auto;
      -moz-hyphens: auto;
      -webkit-hyphens: auto;
      hyphens: auto;

    }

TypeError: got multiple values for argument

I had the same problem that is really easy to make, but took me a while to see through.

I had copied the declaration to where I was using it and had left the 'self' argument there, but it took me ages to realise that.

I had

self.myFunction(self, a, b, c='123')

but it should have been

self.myFunction(a, b, c='123')

Dynamically add child components in React

Sharing my solution here, based on Chris' answer. Hope it can help others.

I needed to dynamically append child elements into my JSX, but in a simpler way than conditional checks in my return statement. I want to show a loader in the case that the child elements aren't ready yet. Here it is:

export class Settings extends React.PureComponent {
  render() {
    const loading = (<div>I'm Loading</div>);
    let content = [];
    let pushMessages = null;
    let emailMessages = null;

    if (this.props.pushPreferences) {
       pushMessages = (<div>Push Content Here</div>);
    }
    if (this.props.emailPreferences) {
      emailMessages = (<div>Email Content Here</div>);
    }

    // Push the components in the order I want
    if (emailMessages) content.push(emailMessages);
    if (pushMessages) content.push(pushMessages);

    return (
      <div>
        {content.length ? content : loading}
      </div>
    )
}

Now, I do realize I could also just put {pushMessages} and {emailMessages} directly in my return() below, but assuming I had even more conditional content, my return() would just look cluttered.

Object of class DateTime could not be converted to string

Try this:

$Date = $row['valdate']->format('d/m/Y'); // the result will 01/12/2015

NOTE: $row['valdate'] its a value date in the database

What does body-parser do with express?

Understanding Requests Body

When receiving a POST or PUT request, the request body might be important to your application. Getting at the body data is a little more involved than accessing request headers. The request object that's passed in to a handler implements the ReadableStream interface. This stream can be listened to or piped elsewhere just like any other stream. We can grab the data right out of the stream by listening to the stream's 'data' and 'end' events.

The chunk emitted in each 'data' event is a Buffer. If you know it's going to be string data, the best thing to do is collect the data in an array, then at the 'end', concatenate and stringify it.

let body = [];
request.on('data', (chunk) => {
  body.push(chunk);
}).on('end', () => {
  body = Buffer.concat(body).toString();
  // at this point, `body` has the entire request body stored in it as a string
});

Understanding body-parser

As per its documentation

Parse incoming request bodies in a middleware before your handlers, available under the req.body property.

As you saw in the first example, we had to parse the incoming request stream manually to extract the body. This becomes a tad tedious when there are multiple form data of different types. So we use the body-parser package which does all this task under the hood.

It provides four modules to parse different types of data

After having the raw content body-parser will use one of the above strategies(depending on middleware you decided to use) to parse the data. You can read more about them by reading their documentation.

After setting the req.body to the parsed body, body-parser will invoke next() to call the next middleware down the stack, which can then access the request data without having to think about how to unzip and parse it.

C# RSA encryption/decryption with transmission

well there are really enough examples for this, but anyway, here you go

using System;
using System.Security.Cryptography;

namespace RsaCryptoExample
{
  static class Program
  {
    static void Main()
    {
      //lets take a new CSP with a new 2048 bit rsa key pair
      var csp = new RSACryptoServiceProvider(2048);

      //how to get the private key
      var privKey = csp.ExportParameters(true);

      //and the public key ...
      var pubKey = csp.ExportParameters(false);

      //converting the public key into a string representation
      string pubKeyString;
      {
        //we need some buffer
        var sw = new System.IO.StringWriter();
        //we need a serializer
        var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
        //serialize the key into the stream
        xs.Serialize(sw, pubKey);
        //get the string from the stream
        pubKeyString = sw.ToString();
      }

      //converting it back
      {
        //get a stream from the string
        var sr = new System.IO.StringReader(pubKeyString);
        //we need a deserializer
        var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
        //get the object back from the stream
        pubKey = (RSAParameters)xs.Deserialize(sr);
      }

      //conversion for the private key is no black magic either ... omitted

      //we have a public key ... let's get a new csp and load that key
      csp = new RSACryptoServiceProvider();
      csp.ImportParameters(pubKey);

      //we need some data to encrypt
      var plainTextData = "foobar";

      //for encryption, always handle bytes...
      var bytesPlainTextData = System.Text.Encoding.Unicode.GetBytes(plainTextData);

      //apply pkcs#1.5 padding and encrypt our data 
      var bytesCypherText = csp.Encrypt(bytesPlainTextData, false);

      //we might want a string representation of our cypher text... base64 will do
      var cypherText = Convert.ToBase64String(bytesCypherText);


      /*
       * some transmission / storage / retrieval
       * 
       * and we want to decrypt our cypherText
       */

      //first, get our bytes back from the base64 string ...
      bytesCypherText = Convert.FromBase64String(cypherText);

      //we want to decrypt, therefore we need a csp and load our private key
      csp = new RSACryptoServiceProvider();
      csp.ImportParameters(privKey);

      //decrypt and strip pkcs#1.5 padding
      bytesPlainTextData = csp.Decrypt(bytesCypherText, false);

      //get our original plainText back...
      plainTextData = System.Text.Encoding.Unicode.GetString(bytesPlainTextData);
    }
  }
}

as a side note: the calls to Encrypt() and Decrypt() have a bool parameter that switches between OAEP and PKCS#1.5 padding ... you might want to choose OAEP if it's available in your situation

How do I create an Android Spinner as a popup?

android:spinnerMode="dialog"

// Creating adapter for spinner

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, categories);

// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);

What is the difference between json.load() and json.loads() functions

Just going to add a simple example to what everyone has explained,

json.load()

json.load can deserialize a file itself i.e. it accepts a file object, for example,

# open a json file for reading and print content using json.load
with open("/xyz/json_data.json", "r") as content:
  print(json.load(content))

will output,

{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}

If I use json.loads to open a file instead,

# you cannot use json.loads on file object
with open("json_data.json", "r") as content:
  print(json.loads(content))

I would get this error:

TypeError: expected string or buffer

json.loads()

json.loads() deserialize string.

So in order to use json.loads I will have to pass the content of the file using read() function, for example,

using content.read() with json.loads() return content of the file,

with open("json_data.json", "r") as content:
  print(json.loads(content.read()))

Output,

{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}

That's because type of content.read() is string, i.e. <type 'str'>

If I use json.load() with content.read(), I will get error,

with open("json_data.json", "r") as content:
  print(json.load(content.read()))

Gives,

AttributeError: 'str' object has no attribute 'read'

So, now you know json.load deserialze file and json.loads deserialize a string.

Another example,

sys.stdin return file object, so if i do print(json.load(sys.stdin)), I will get actual json data,

cat json_data.json | ./test.py

{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}

If I want to use json.loads(), I would do print(json.loads(sys.stdin.read())) instead.

Table Height 100% inside Div element

You need to have a height in the div <div style="overflow:hidden"> else it doesnt know what 100% is.

Pass object to javascript function

when you pass an object within curly braces as an argument to a function with one parameter , you're assigning this object to a variable which is the parameter in this case

Syntax for an If statement using a boolean

You can change the value of a bool all you want. As for an if:

if randombool == True:

works, but you can also use:

if randombool:

If you want to test whether something is false you can use:

if randombool == False

but you can also use:

if not randombool:

jQuery change input text value

When set the new value of element, you need call trigger change.

$('element').val(newValue).trigger('change');

Is there any way to install Composer globally on Windows?

An alternative variant (see Lusitanian answer) is to register .phar files as executable on your system, exemplary phar.reg file:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\.phar]
@="phar_auto_file"

[HKEY_CLASSES_ROOT\phar_auto_file\shell\open\command]
@="\"c:\\PROGRA~1\\php\\php.exe\" \"%1\" %*"

Just replace the path to php.exe to your PHP executable. You can then also extend the %PATHEXT% commandline variable with .PHAR which will allow you to type composer instead of composer.phar as long as composer.phar is inside the %Path%.

Change the Textbox height?

So after having the same issue with not being able to adjust height in text box, Width adjustment is fine but height never adjusted with the above suggestions (at least for me), I was finally able to take make it happen. As mentioned above, the issue appeared to be centered around a default font size setting in my text box and the behavior of the text box auto sizing around it. The default font size was tiny. Hence why trying to force the height or even turn off autosizing failed to fix the issue for me.

Set the Font properties to the size of your liking and then height change will kick in around the FONT size, automatically. You can still manually set your text box width. Below is snippet I added that worked for me.

    $textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(60,300)
$textBox.Size = New-Object System.Drawing.Size(600,80)
$textBox.Font = New-Object System.Drawing.Font("Times New Roman",18,[System.Drawing.FontStyle]::Regular)
$textBox.Form.Font = $textbox.Font

Please note the Height value in '$textBox.Size = New-Object System.Drawing.Size(600,80)' is being ignored and the FONT size is actually controlling the height of the text box by autosizing around that font size.

Simplest/cleanest way to implement a singleton in JavaScript

Another way - just insure the class can not new again.

By this, you can use the instanceof op. Also, you can use the prototype chain to inherit the class. It's a regular class, but you can not new it. If you want to get the instance, just use getInstance:

function CA()
{
    if(CA.instance)
    {
        throw new Error('can not new this class');
    }
    else
    {
        CA.instance = this;
    }
}


/**
 * @protected
 * @static
 * @type {CA}
 */
CA.instance = null;

/* @static */
CA.getInstance = function()
{
    return CA.instance;
}


CA.prototype =
/** @lends CA# */
{
    func: function(){console.log('the func');}
}

// Initialise the instance
new CA();

// Test here
var c = CA.getInstance()
c.func();
console.assert(c instanceof CA)

// This will fail
var b = new CA();

If you don't want to expose the instance member, just put it into a closure.

MySQL - UPDATE query based on SELECT Query

UPDATE
    `table1` AS `dest`,
    (
        SELECT
            *
        FROM
            `table2`
        WHERE
            `id` = x
    ) AS `src`
SET
    `dest`.`col1` = `src`.`col1`
WHERE
    `dest`.`id` = x
;

Hope this works for you.

UNION with WHERE clause

You need to look at the explain plans, but unless there is an INDEX or PARTITION on COL_A, you are looking at a FULL TABLE SCAN on both tables.

With that in mind, your first example is throwing out some of the data as it does the FULL TABLE SCAN. That result is being sorted by the UNION, then duplicate data is dropped. This gives you your result set.

In the second example, you are pulling the full contents of both tables. That result is likely to be larger. So the UNION is sorting more data, then dropping the duplicate stuff. Then the filter is being applied to give you the result set you are after.

As a general rule, the earlier you filter away data, the smaller the data set, and the faster you will get your results. As always, your milage may vary.

substring of an entire column in pandas dataframe

I needed to convert a single column of strings of form nn.n% to float. I needed to remove the % from the element in each row. The attend data frame has two columns.

attend.iloc[:,1:2]=attend.iloc[:,1:2].applymap(lambda x: float(x[:-1]))

Its an extenstion to the original answer. In my case it takes a dataframe and applies a function to each value in a specific column. The function removes the last character and converts the remaining string to float.

Saving a text file on server using JavaScript

It's not possible to save content to the website using only client-side scripting such as JavaScript and jQuery, but by submitting the data in an AJAX POST request you could perform the other half very easily on the server-side.

However, I would not recommend having raw content such as scripts so easily writeable to your hosting as this could easily be exploited. If you want to learn more about AJAX POST requests, you can read the jQuery API page:

http://api.jquery.com/jQuery.post/

And here are some things you ought to be aware of if you still want to save raw script files on your hosting. You have to be very careful with security if you are handling files like this!

File uploading (most of this applies if sending plain text too if javascript can choose the name of the file) http://www.developershome.com/wap/wapUpload/wap_upload.asp?page=security https://www.owasp.org/index.php/Unrestricted_File_Upload

Is bool a native C type?

No such thing, probably just a macro for int

Hide/Show Column in an HTML Table

I would like to do this without attaching a class to every td

Personally, I would go with the the class-on-each-td/th/col approach. Then you can switch columns on and off using a single write to className on the container, assuming style rules like:

table.hide1 .col1 { display: none; }
table.hide2 .col2 { display: none; }
...

This is going to be faster than any JS loop approach; for really long tables it can make a significant difference to responsiveness.

If you can get away with not supporting IE6, you could use adjacency selectors to avoid having to add the class attributes to tds. Or alternatively, if your concern is making the markup cleaner, you could add them from JavaScript automatically in an initialisation step.

Converting a sentence string to a string array of words in Java

You can use simple following code

String str= "This is a sample sentence.";
String[] words = str.split("[[ ]*|[//.]]");
for(int i=0;i<words.length;i++)
System.out.print(words[i]+" ");

Using Switch Statement to Handle Button Clicks

Just change the class (I suppose it's the main Activity) to implement View.OnClickListener and on the onClick method put the general onClick actions you want to put:

public class MediaPlayer extends Activity implements OnClickListener {

@Override
public void onCreate(Bundle savedInstanceState) {
    Button b1 = (Button) findViewById(R.id.buttonplay);       
    b1.setOnClickListener(this);
    //{YOUR APP}
}


@Override
public void onClick(View v) {
    // Perform action on click
    switch(v.getId()) {
    case R.id.buttonplay:
        //Play voicefile
        MediaPlayer.create(getBaseContext(), R.raw.voicefile).start();
        break;
    case R.id.buttonstop:
        //Stop MediaPlayer
        MediaPlayer.create(getBaseContext(), R.raw.voicefile).stop();
        break;
    }

}}

I took it from this video: http://www.youtube.com/watch?v=rm-hNlTD1H0 . It's good for starters.

Git says local branch is behind remote branch, but it's not

To diagnose it, follow this answer.

But to fix it, knowing you are the only one changing it, do:
1 - backup your project (I did only the files on git, ./src folder)
2 - git pull
3 - restore you backup over the many "messed" files (with merge indicators)

I tried git pull -s recursive -X ours but didnt work the way I wanted, it could be an option tho, but backup first!!!

Make sure the differences/changes (at git gui) are none. This is my case, there is nothing to merge at all, but github keeps saying I should merge...

Manually map column names with class properties

I know this is a relatively old thread, but I thought I'd throw what I did out there.

I wanted attribute-mapping to work globally. Either you match the property name (aka default) or you match a column attribute on the class property. I also didn't want to have to set this up for every single class I was mapping to. As such, I created a DapperStart class that I invoke on app start:

public static class DapperStart
{
    public static void Bootstrap()
    {
        Dapper.SqlMapper.TypeMapProvider = type =>
        {
            return new CustomPropertyTypeMap(typeof(CreateChatRequestResponse),
                (t, columnName) => t.GetProperties().FirstOrDefault(prop =>
                    {
                        return prop.Name == columnName || prop.GetCustomAttributes(false).OfType<ColumnAttribute>()
                                   .Any(attr => attr.Name == columnName);
                    }
                ));
        };
    }
}

Pretty simple. Not sure what issues I'll run into yet as I just wrote this, but it works.

Setting Timeout Value For .NET Web Service

Try setting the timeout value in your web service proxy class:

WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds

Adding an arbitrary line to a matplotlib plot in ipython notebook

Rather than abusing plot or annotate, which will be inefficient for many lines, you can use matplotlib.collections.LineCollection:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")

# Takes list of lines, where each line is a sequence of coordinates
l1 = [(70, 100), (70, 250)]
l2 = [(70, 90), (90, 200)]
lc = LineCollection([l1, l2], color=["k","blue"], lw=2)

plt.gca().add_collection(lc)

plt.show()

Figure with two lines plotted via LineCollection

It takes a list of lines [l1, l2, ...], where each line is a sequence of N coordinates (N can be more than two).

The standard formatting keywords are available, accepting either a single value, in which case the value applies to every line, or a sequence of M values, in which case the value for the ith line is values[i % M].

Laravel Eloquent Join vs Inner Join?

Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.

You could build it like this:

<?php

Schema::create('feeds', function($table) {
    $table->increments('id');
    $table->timestamps();
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->morphs('target'); 
});

Build the feed model like so:

<?php

class Feed extends Eloquent
{
    protected $fillable = ['user_id', 'target_type', 'target_id'];

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function target()
    {
        return $this->morphTo();
    }
}

Then keep it up to date with something like:

<?php

Vote::created(function(Vote $vote) {
    $target_type = 'Vote';
    $target_id   = $vote->id;
    $user_id     = $vote->user_id;

    Feed::create(compact('target_type', 'target_id', 'user_id'));
});

You could make the above much more generic/robust—this is just for demonstration purposes.

At this point, your feed items are really easy to retrieve all at once:

<?php

Feed::whereIn('user_id', $my_friend_ids)
    ->with('user', 'target')
    ->orderBy('created_at', 'desc')
    ->get();

What is the purpose of using WHERE 1=1 in SQL statements?

As you said:

if you are adding conditions dynamically you don't have to worry about stripping the initial AND that's the only reason could be, you are right.

How to enable file sharing for my app?

You just have to set UIFileSharingEnabled (Application Supports iTunes file sharing) key in the info plist of your app. Here's a link for the documentation. Scroll down to the file sharing support part.

In the past, it was also necessary to define CFBundleDisplayName (Bundle Display Name), if it wasn't already there. More details here.

What are C++ functors and their uses?

Functors are used in gtkmm to connect some GUI button to an actual C++ function or method.


If you use the pthread library to make your app multithreaded, Functors can help you.
To start a thread, one of the arguments of the pthread_create(..) is the function pointer to be executed on his own thread.
But there's one inconvenience. This pointer can't be a pointer to a method, unless it's a static method, or unless you specify it's class, like class::method. And another thing, the interface of your method can only be:

void* method(void* something)

So you can't run (in a simple obvious way), methods from your class in a thread without doing something extra.

A very good way of dealing with threads in C++, is creating your own Thread class. If you wanted to run methods from MyClass class, what I did was, transform those methods into Functor derived classes.

Also, the Thread class has this method: static void* startThread(void* arg)
A pointer to this method will be used as an argument to call pthread_create(..). And what startThread(..) should receive in arg is a void* casted reference to an instance in heap of any Functor derived class, which will be casted back to Functor* when executed, and then called it's run() method.

On Selenium WebDriver how to get Text from Span Tag

String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span));

kk.getText().toString();

System.out.println(+kk.getText().toString());

how to convert string into time format and add two hours

This will give you the time you want (eg: 21:31 PM)

//Add 2 Hours to just TIME
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss a");
Date date2 = formatter.parse("19:31:51 PM");
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
cal2.add(Calendar.HOUR_OF_DAY, 2);
SimpleDateFormat printTimeFormat = new SimpleDateFormat("HH:mm a");
System.out.println(printTimeFormat.format(cal2.getTime())); 

SQL Server - find nth occurrence in a string

Inspired by Alex K's reply One way (2k8), I have created a script for a Token Function for the SQL Server for returning a specific token from a string. I needed this for refacturing a SSIS-package to T-SQL without having to implement Alex' solution a number of times manually. My function has one disadvantage: It returns the token value as a table (one column, one row) instead of as a varchar value. If anyone has a solution for this, please let me know.

DROP FUNCTION [RDW].[token]
GO

create function [RDW].[token] (@string varchar(8000), @split varchar(50), @returnIndex int) 
returns table  
as 
    return with T(img, starts, pos, [index]) as ( 
        select @string, 1, charindex(@split, @string), 0 
        union all 
        select @string, pos + 1, charindex(@split, @string, pos + 1), [index]+1 
        from t 
        where pos > 0
    )
    select substring(img, starts, case when pos > 0 then pos - starts else len(img) end) token
    from T
    where [index] = @returnIndex 
GO

Update multiple tables in SQL Server using INNER JOIN

You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :

BEGIN TRANSACTION

update A
set A.ORG_NAME =  @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID

update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
    on B.ORG_ID = A.ORG_ID
    and A.ORG_ID = @ORG_ID

COMMIT

Can I edit an iPad's host file?

The easiest way to do this is to run an iPad simulator using XCode and then add an entry in the hosts file (/etc/hosts) on the host system to point to your test site.

python-dev installation error: ImportError: No module named apt_pkg

This error will often occur when a newer version of python has been installed alongside an older version e.g;

  • Ubuntu 18.04.1 ships with python version 3.6.6
  • Installed ppa:deadsnakes/python3.7.1 or alternative
  • Run a command that uses the apt_pkg module and get an error such as;

        from CommandNotFound.db.db import SqliteDatabase
    File "/usr/lib/python3/dist-packages/CommandNotFound/db/db.py", line 5, in <module>
        import apt_pkg
    

When we install a non-distro python3 version with apt it will set a shared module directory to be that of python3 most usually it will be /usr/lib/python3.

Most of the time this will be ok, but under some circumstances the different versions of python rely on different libraries or shared objects/libraries than the other python version does, so as other answers have pointed out we need to link the .SO to the correct python version. So if we have python3.6 installed on a 64bit system then the apt_pkg .SO link would be

sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

But the problem lies in the fact that when we install a newer python version the link will update to point to the newest python version, which leads to the error of apt_pkg module not being found. By checking which version of python ships with your distro you can create the link as shown above. Or we use a method to offer the command a choice of python versions to link the .SO such as;

sudo ln -s apt_pkg.cpython-{36m,35m,34m}-x86_64-linux-gnu.so apt_pkg.so

Because python will create this link to the newest installed python version we give the command the option to choose from 3 python versions, of which it will choose the highest version given.

Chrome extension: accessing localStorage in content script

Sometimes it may be better to use chrome.storage API. It's better then localStorage because you can:

  • store information from your content script without the need for message passing between content script and extension;
  • store your data as JavaScript objects without serializing them to JSON (localStorage only stores strings).

Here's a simple code demonstrating the use of chrome.storage. Content script gets the url of visited page and timestamp and stores it, popup.js gets it from storage area.

content_script.js

(function () {
    var visited = window.location.href;
    var time = +new Date();
    chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
        console.log("Just visited",visited)
    });
})();

popup.js

(function () {
    chrome.storage.onChanged.addListener(function (changes,areaName) {
        console.log("New item in storage",changes.visitedPages.newValue);
    })
})();

"Changes" here is an object that contains old and new value for a given key. "AreaName" argument refers to name of storage area, either 'local', 'sync' or 'managed'.

Remember to declare storage permission in manifest.json.

manifest.json

...
"permissions": [
    "storage"
 ],
...

Focusable EditText inside ListView

My task was to implement ListView which expands when clicked. The additional space shows EditText where you can input some text. App should be functional on 2.2+ (up to 4.2.2 at time of writing this)

I tried numerous solutions from this post and others I could find; tested them on 2.2 up to 4.2.2 devices. None of solutions was satisfactionary on all devices 2.2+, each solution presented with different problems.

I wanted to share my final solution :

  1. set listview to android:descendantFocusability="afterDescendants"
  2. set listview to setItemsCanFocus(true);
  3. set your activity to android:windowSoftInputMode="adjustResize" Many people suggest adjustPan but adjustResize gives much better ux imho, just test this in your case. With adjustPan you will get bottom listitems obscured for instance. Docs suggest that ("This is generally less desirable than resizing"). Also on 4.0.4 after user starts typing on soft keyboard the screen pans to the top.
  4. on 4.2.2 with adjustResize there are some problems with EditText focus. The solution is to apply rjrjr solution from this thread. It looks scarry but it is not. And it works. Just try it.

Additional 5. Due to adapter being refreshed (because of view resize) when EditText gains focus on pre HoneyComb versions I found an issue with reversed views: getting View for ListView item / reverse order on 2.2; works on 4.0.3

If you are doing some animations you might want to change behaviour to adjustPan for pre-honeycomb versions so that resize doesnt fire and adapter doesn't refresh the views. You just need to add something like this

if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

All this gives acceptable ux on 2.2 - 4.2.2 devices. Hope it will save people some time as it took me at least several hours to come to this conclusion.

Telling gcc directly to link a library statically

It is possible of course, use -l: instead of -l. For example -l:libXYZ.a to link with libXYZ.a. Notice the lib written out, as opposed to -lXYZ which would auto expand to libXYZ.

CodeIgniter activerecord, retrieve last insert id?

$this->db->insert_id()  

//please try this

Batch Script to Run as Administrator

You could put it as a startup item... Startup items don't show off a prompt to run as an administrator at all.

Check this article Elevated Program Shortcut Without UAC rompt

How to clear the logs properly for a Docker container?

You can also supply the log-opts parameters on the docker run command line, like this:

docker run --log-opt max-size=10m --log-opt max-file=5 my-app:latest

or in a docker-compose.yml like this

my-app:
image: my-app:latest
logging:
    driver: "json-file"
    options:
        max-file: "5"
        max-size: 10m

Credits: https://medium.com/@Quigley_Ja/rotating-docker-logs-keeping-your-overlay-folder-small-40cfa2155412 (James Quigley)

Trying to include a library, but keep getting 'undefined reference to' messages

If the .c source files are converted .cpp (like as in parsec), then the extern needs to be followed by "C" as in

extern "C" void foo();

Can you display HTML5 <video> as a full screen background?

I might be a bit late to answer this but this will be useful for new people looking for this answer.

The answers above are good, but to have a perfect video background you have to check at the aspect ratio as the video might cut or the canvas around get deformed when resizing the screen or using it on different screen sizes.

I got into this issue not long ago and I found the solution using media queries.

Here is a tutorial that I wrote on how to create a Fullscreen Video Background with only CSS

I will add the code here as well:

HTML:

<div class="videoBgWrapper">
    <video loop muted autoplay poster="img/videoframe.jpg" class="videoBg">
        <source src="videosfolder/video.webm" type="video/webm">
        <source src="videosfolder/video.mp4" type="video/mp4">
        <source src="videosfolder/video.ogv" type="video/ogg">
    </video>
</div>

CSS:

.videoBgWrapper {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: hidden;
    z-index: -100;
}
.videoBg{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

@media (min-aspect-ratio: 16/9) {
  .videoBg{
    width: 100%;
    height: auto;
  }
}
@media (max-aspect-ratio: 16/9) {
  .videoBg {
    width: auto;
    height: 100%;
  }
}

I hope you find it useful.

bootstrap 3 navbar collapse button not working

I had a similar problem. Looked over the html several times and was sure it was correct. Then I started playing around with the order of jquery and bootstrap javascript.

Originally I had bootstrap.min.js loading BEFORE jquery.min.js. In this state, the menu would not expand when clicking on the menu icon.

Then I changed the order so that bootstrap.min.js came after jquery.min.js, and this solved the problem. I don't know enough about javascript to explain why this caused the problem (or fixed it), but that is what worked for me.

Additional info:

Both scripts are located at the bottom of the page, just before the tag. Both scripts are hosted on CDNs, not locally hosted.

If you're pretty sure your code is correct, give this a try.

animating addClass/removeClass with jQuery

You could use jquery ui's switchClass, Heres an example:

$( "selector" ).switchClass( "oldClass", "newClass", 1000, "easeInOutQuad" );

Or see this jsfiddle.

Check file size before upload

Client side Upload Canceling

On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE, can be tampered with so always use server side validation.

<form method="post" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('file').files[0];

    if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
        //Submit form        
    } else {
        //Prevent default and display error
        evt.preventDefault();
    }
}, false);
</script>

Server Side Upload Canceling

On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZE has been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.

PHP Validation

On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILES array to find out the upload size. (Docs on the contents of $_FILES can be found below the MAX_FILE_SIZE docs)

upload.php

<?php
if(isset($_FILES['file'])) {
    if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
        // File too big
    } else {
        // File within size restrictions
    }
}

Android: Quit application when press back button

This one work for me.I found it myself by combining other answers

private Boolean exit = false;
@override
public void onBackPressed(){ 
    if (exit) {
        finish(); // finish activity
    } 
    else {
        Toast.makeText(this, "Press Back again to Exit.",
            Toast.LENGTH_SHORT).show();
         exit = true;
         new Handler().postDelayed(new Runnable() {

         @Override
         public void run() {
             // TODO Auto-generated method stub
             Intent a = new Intent(Intent.ACTION_MAIN);
             a.addCategory(Intent.CATEGORY_HOME);
             a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
             startActivity(a);
        }
    }, 1000);
}

Can't concatenate 2 arrays in PHP

IMO some of the previous answers are incorrect! (It's possible to sort the answers to start from oldest to newest).

array_merge() actually merges the arrays, meaning, if the arrays have a common item one of the copies will be omitted. Same goes for + (union).

I didn't find a "work-around" for this issue, but to do it manually...

Here it goes:

<?php
$part1 = array(1,2,3);
echo "array 1 = \n";
print_r($part1);
$part2 = array(4,5,6);
echo "array 2 = \n";
print_r($part2);
$ans = NULL;
for ($i = 0; $i < count($part1); $i++) {
    $ans[] = $part1[$i];
}
for ($i = 0; $i < count($part2); $i++) {
    $ans[] = $part2[$i];
}
echo "after arrays concatenation:\n";
print_r($ans);
?>

mongodb how to get max value from collections

The performance of the suggested answer is fine. According to the MongoDB documentation:

When a $sort immediately precedes a $limit, the optimizer can coalesce the $limit into the $sort. This allows the sort operation to only maintain the top n results as it progresses, where n is the specified limit, and MongoDB only needs to store n items in memory.

Changed in version 4.0.

So in the case of

db.collection.find().sort({age:-1}).limit(1)

we get only the highest element WITHOUT sorting the collection because of the mentioned optimization.

Create an ISO date object in javascript

In node, the Mongo driver will give you an ISO string, not the object. (ex: Mon Nov 24 2014 01:30:34 GMT-0800 (PST)) So, simply convert it to a js Date by: new Date(ISOString);

Find TODO tags in Eclipse

Go TO Window>Show View >Markers

than you will get java task .

java task have all TODOs of your project

Add quotation at the start and end of each line in Notepad++

  1. Put your cursor at the begining of line 1.
  2. click Edit>ColumnEditor. Put " in the text and hit enter.
  3. Repeat 2 but put the cursor at the end of line1 and put ", and hit enter.

python: iterate a specific range in a list

A more memory efficient way to iterate over a slice of a list would be to use islice() from the itertools module:

from itertools import islice

listOfStuff = (['a','b'], ['c','d'], ['e','f'], ['g','h'])

for item in islice(listOfStuff, 1, 3):
    print item

# ['c', 'd']
# ['e', 'f']

However, this can be relatively inefficient in terms of performance if the start value of the range is a large value sinceislicewould have to iterate over the first start value-1 items before returning items.

What's the difference between Invoke() and BeginInvoke()

Delegate.BeginInvoke() asynchronously queues the call of a delegate and returns control immediately. When using Delegate.BeginInvoke(), you should call Delegate.EndInvoke() in the callback method to get the results.

Delegate.Invoke() synchronously calls the delegate in the same thread.

MSDN Article

How to refer to Excel objects in Access VBA?

Inside a module

Option Explicit
dim objExcelApp as Excel.Application
dim wb as Excel.Workbook

sub Initialize()
   set objExcelApp = new Excel.Application
end sub

sub ProcessDataWorkbook()
    dim ws as Worksheet
    set wb = objExcelApp.Workbooks.Open("path to my workbook")
    set ws = wb.Sheets(1)

    ws.Cells(1,1).Value = "Hello"
    ws.Cells(1,2).Value = "World"

    'Close the workbook
    wb.Close
    set wb = Nothing
end sub

sub Release()
   set objExcelApp = Nothing
end sub

How to find all trigger associated with a table with SQL Server?

You can do this simply with SSMS. Just go to your table name and expand the Triggers node to view a list of triggers associated with that table. Right click to modify your trigger. enter image description here

SQL Order By Count

You need to aggregate the data first, this can be done using the GROUP BY clause:

SELECT Group, COUNT(*)
FROM table
GROUP BY Group
ORDER BY COUNT(*) DESC

The DESC keyword allows you to show the highest count first, ORDER BY by default orders in ascending order which would show the lowest count first.

Read a XML (from a string) and get some fields - Problems reading XML

The other answers are several years old (and do not work for Windows Phone 8.1) so I figured I'd drop in another option. I used this to parse an RSS response for a Windows Phone app:

XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(xml_string);

Matplotlib discrete colorbar

To set a values above or below the range of the colormap, you'll want to use the set_over and set_under methods of the colormap. If you want to flag a particular value, mask it (i.e. create a masked array), and use the set_bad method. (Have a look at the documentation for the base colormap class: http://matplotlib.org/api/colors_api.html#matplotlib.colors.Colormap )

It sounds like you want something like this:

import matplotlib.pyplot as plt
import numpy as np

# Generate some data
x, y, z = np.random.random((3, 30))
z = z * 20 + 0.1

# Set some values in z to 0...
z[:5] = 0

cmap = plt.get_cmap('jet', 20)
cmap.set_under('gray')

fig, ax = plt.subplots()
cax = ax.scatter(x, y, c=z, s=100, cmap=cmap, vmin=0.1, vmax=z.max())
fig.colorbar(cax, extend='min')

plt.show()

enter image description here

Which port we can use to run IIS other than 80?

Also remember, when running on alternate ports, you need to specify the port on the URL:

http://www.example.com:8080

There may be firewalls or proxy servers to consider depending on your environment.

Inserting the iframe into react component

You can use property dangerouslySetInnerHTML, like this

_x000D_
_x000D_
const Component = React.createClass({_x000D_
  iframe: function () {_x000D_
    return {_x000D_
      __html: this.props.iframe_x000D_
    }_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe> tag and pass it to new <iframe> tag, like that

_x000D_
_x000D_
/**_x000D_
 * getAttrs_x000D_
 * returns all attributes from TAG string_x000D_
 * @return Object_x000D_
 */_x000D_
const getAttrs = (iframeTag) => {_x000D_
  var doc = document.createElement('div');_x000D_
  doc.innerHTML = iframeTag;_x000D_
_x000D_
  const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
  return [].slice_x000D_
    .call(iframe.attributes)_x000D_
    .reduce((attrs, element) => {_x000D_
      attrs[element.name] = element.value;_x000D_
      return attrs;_x000D_
    }, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <iframe {...getAttrs(this.props.iframe) } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
_x000D_
_x000D_

Why doesn't catching Exception catch RuntimeException?

Catching Exception will catch a RuntimeException

Global variables in R

As Christian's answer with assign() shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<- operator, ie

    a <<- "new" 

inside the function.

Selecting/excluding sets of columns in pandas

Here's how to create a copy of a DataFrame excluding a list of columns:

df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
df2 = df.drop(['B', 'D'], axis=1)

But be careful! You mention views in your question, suggesting that if you changed df, you'd want df2 to change too. (Like a view would in a database.)

This method doesn't achieve that:

>>> df.loc[0, 'A'] = 999 # Change the first value in df
>>> df.head(1)
     A         B         C         D
0  999 -0.742688 -1.980673 -0.920133
>>> df2.head(1) # df2 is unchanged. It's not a view, it's a copy!
          A         C
0  0.251262 -1.980673

Note also that this is also true of @piggybox's method. (Although that method is nice and slick and Pythonic. I'm not doing it down!!)

For more on views vs. copies see this SO answer and this part of the Pandas docs which that answer refers to.

Convert from DateTime to INT

Or, once it's already in SSIS, you could create a derived column (as part of some data flow task) with:

(DT_I8)FLOOR((DT_R8)systemDateTime)

But you'd have to test to doublecheck.

How to open CSV file in R when R says "no such file or directory"?

Try

f <- file.choose()

to choose the file interactively and save the name in f.

Then run read.csv on the saved filename

d <- read.csv(f)

How to show uncommitted changes in Git and some Git diffs in detail

For me, the only thing which worked is

git diff HEAD

including the staged files, git diff --cached only shows staged files.

What are Runtime.getRuntime().totalMemory() and freeMemory()?

To understand it better, run this following program (in jdk1.7.x) :

$ java -Xms1025k -Xmx1025k -XshowSettings:vm  MemoryTest

This will print jvm options and the used, free, total and maximum memory available in jvm.

public class MemoryTest {    
    public static void main(String args[]) {
                System.out.println("Used Memory   :  " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + " bytes");
                System.out.println("Free Memory   : " + Runtime.getRuntime().freeMemory() + " bytes");
                System.out.println("Total Memory  : " + Runtime.getRuntime().totalMemory() + " bytes");
                System.out.println("Max Memory    : " + Runtime.getRuntime().maxMemory() + " bytes");            
        }
}

Counting the number of elements in array

This expands on the answer by Denis Bubnov.

I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.

{% set count = 0 %}
{% for anchor in items %}
    {% if anchor.content['#paragraph'].field_anchor_link.0.value %}
        {% set count = count + 1 %}
    {% endif %}
{% endfor %}

{% if count > 0 %}
 ---  build the toc here --
{% endif %}

How do you calculate program run time in python?

@JoshAdel covered a lot of it, but if you just want to time the execution of an entire script, you can run it under time on a unix-like system.

kotai:~ chmullig$ cat sleep.py 
import time

print "presleep"
time.sleep(10)
print "post sleep"
kotai:~ chmullig$ python sleep.py 
presleep
post sleep
kotai:~ chmullig$ time python sleep.py 
presleep
post sleep

real    0m10.035s
user    0m0.017s
sys 0m0.016s
kotai:~ chmullig$ 

java.io.IOException: Server returned HTTP response code: 500

I have encountered the same problem and found out the solution.

You may look within the first server response and see if the server sent you a cookie.

To check if the server sent you a cookie, you can use HttpURLConnection#getHeaderFields() and look for headers named "Set-Cookie".

If existing, here's the solution for your problem. 100% Working for this case!

+1 if it worked for you.

Sending email from Azure

I know this is an old post but I've just signed up for Azure and I get 25,000 emails a month for free via SendGrid. These instructions are excellent, I was up and running in minutes:

How to Send Email Using SendGrid with Azure

Azure customers can unlock 25,000 free emails each month.

How to use not contains() in xpath?

XPath queries are case sensitive. Having looked at your example (which, by the way, is awesome, nobody seems to provide examples anymore!), I can get the result you want just by changing "business", to "Business"

//production[not(contains(category,'Business'))]

I have tested this by opening the XML file in Chrome, and using the Developer tools to execute that XPath queries, and it gave me just the Film category back.

How can I make Jenkins CI with Git trigger on pushes to master?

For GitLab, use these steps:

  1. Go to your project's settings ? Web hooks
  2. Enter the "Build Now" URL from your Jenkins project as a Push Event URL:

    http://server.com/jenkins/job/project_name/build?delay=0sec for example

  3. Click Add Web Hook and then test hook

Then any time you commit to the repository, the web hook is triggered and a build is created. Be sure to set your Jenkins workspace to delete workspace before each build so you get a fresh copy of the new code.

How to use auto-layout to move other views when a view is hidden?

Instead of hiding view, create the width constrain and change it to 0 in code when you want to hide the UIView.

It may be the simplest way to do so. Also, it will preserve the view and you don't need to recreate it if you want to show it again (ideal to use inside table cells). To change the constant value you need to create a constant reference outlet (the same way as you do outlets for the view).

Shared-memory objects in multiprocessing

This is the intended use case for Ray, which is a library for parallel and distributed Python. Under the hood, it serializes objects using the Apache Arrow data layout (which is a zero-copy format) and stores them in a shared-memory object store so they can be accessed by multiple processes without creating copies.

The code would look like the following.

import numpy as np
import ray

ray.init()

@ray.remote
def func(array, param):
    # Do stuff.
    return 1

array = np.ones(10**6)
# Store the array in the shared memory object store once
# so it is not copied multiple times.
array_id = ray.put(array)

result_ids = [func.remote(array_id, i) for i in range(4)]
output = ray.get(result_ids)

If you don't call ray.put then the array will still be stored in shared memory, but that will be done once per invocation of func, which is not what you want.

Note that this will work not only for arrays but also for objects that contain arrays, e.g., dictionaries mapping ints to arrays as below.

You can compare the performance of serialization in Ray versus pickle by running the following in IPython.

import numpy as np
import pickle
import ray

ray.init()

x = {i: np.ones(10**7) for i in range(20)}

# Time Ray.
%time x_id = ray.put(x)  # 2.4s
%time new_x = ray.get(x_id)  # 0.00073s

# Time pickle.
%time serialized = pickle.dumps(x)  # 2.6s
%time deserialized = pickle.loads(serialized)  # 1.9s

Serialization with Ray is only slightly faster than pickle, but deserialization is 1000x faster because of the use of shared memory (this number will of course depend on the object).

See the Ray documentation. You can read more about fast serialization using Ray and Arrow. Note I'm one of the Ray developers.

I am getting Failed to load resource: net::ERR_BLOCKED_BY_CLIENT with Google chrome

My advice is to avoid any image names; class names or ID's with the words:

  • Advert
  • Advertise

in their name!

I ran some tests and Ad blockers regularly block any direct content with these names either within the CSS file, Div or Span Layers.

So an image name loaded via CSS such as advertise-with-us.png gets blocked on any machine running such software for example.

EDIT: I've Traced a list of web page elements in Chrome which AdBlock Plus sets the CSS value to "display:none". They probably apply to other browsers too:

::content #ads > .dose > .dosesingle, 
::content #content > #center > .dose > .dosesingle,
::content #content > #right > .dose > .dosesingle, 
::content #header + #content > #left > #rlblock_left, 
::content .trc_rbox_border_elm .syndicatedItem, 
::content .trc_rbox_div .syndicatedItem, 
::content div[id^="mainads"], ::content #ad-banner-980, 
::content #adbox300600, ::content #chartAdWrap, 
::content #in-content-ad, ::content #main-right-ad-tray, 
::content #second-right-ad-tray, ::content #sponsored-message, 
::content #tr-adv-banner, ::content #votvAds_inner, 
::content #welcome_ad, ::content #wp_ad_marker, 
::content .PremiumObitAdBar, ::content .ad-active

Find row where values for column is maximal in a pandas DataFrame

mx.iloc[0].idxmax()

This one line of code will give you how to find the maximum value from a row in dataframe, here mx is the dataframe and iloc[0] indicates the 0th index.

How to return multiple values in one column (T-SQL)?

DECLARE @Str varchar(500)

SELECT @Str=COALESCE(@Str,'') + CAST(ID as varchar(10)) + ','
FROM dbo.fcUser

SELECT @Str

Nested JSON: How to add (push) new items to an object?

If your JSON is without key you can do it like this:

library[library.length] = {"foregrounds" : foregrounds,"backgrounds" : backgrounds};

So, try this:

var library = {[{
    "title"       : "Gold Rush",
        "foregrounds" : ["Slide 1","Slide 2","Slide 3"],
        "backgrounds" : ["1.jpg","","2.jpg"]
    }, {
    "title"       : California",
        "foregrounds" : ["Slide 1","Slide 2","Slide 3"],
        "backgrounds" : ["3.jpg","4.jpg","5.jpg"]
    }]
}

Then:

library[library.length] = {"title" : "Gold Rush", "foregrounds" : ["Howdy","Slide 2"], "backgrounds" : ["1.jpg",""]};

Call PHP function from jQuery?

Thanks all. I took bits of each of your solutions and made my own.

The final working solution is:

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            url: '<?php bloginfo('template_url'); ?>/functions/twitter.php',
            data: "tweets=<?php echo $ct_tweets; ?>&account=<?php echo $ct_twitter; ?>",
            success: function(data) {
                $('#twitter-loader').remove();
                $('#twitter-container').html(data);
            }
        });
   });
</script>

selected value get from db into dropdown select box option using php mysql error

for example ..and please use mysqli() next time because mysql() is deprecated.

<?php
$select="select * from tbl_assign where id='".$_GET['uid']."'"; 
$q=mysql_query($select) or die($select);
$row=mysql_fetch_array($q);
?>

<select name="sclient" id="sclient" class="reginput"/>
<option value="">Select Client</option>
<?php $s="select * from tbl_new_user where type='client'";
$q=mysql_query($s) or die($s);
while($rw=mysql_fetch_array($q))
{ ?>
<option value="<?php echo $rw['login_name']; ?>"<?php if($row['clientname']==$rw['login_name']) echo 'selected="selected"'; ?>><?php echo $rw['login_name']; ?></option>
<?php } ?>
</select>

UTF-8 encoding in JSP page

Page encoding or anything else do not matter a lot. ISO-8859-1 is a subset of UTF-8, therefore you never have to convert ISO-8859-1 to UTF-8 because ISO-8859-1 is already UTF-8,a subset of UTF-8 but still UTF-8. Plus, all that do not mean a thing if You have a double encoding somewhere. This is my "cure all" recipe for all things encoding and charset related:

        String myString = "heartbroken ð";

//String is double encoded, fix that first.

                myString = new String(myString.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                String cleanedText = StringEscapeUtils.unescapeJava(myString);
                byte[] bytes = cleanedText.getBytes(StandardCharsets.UTF_8);
                String text = new String(bytes, StandardCharsets.UTF_8);
                Charset charset = Charset.forName("UTF-8");
                CharsetDecoder decoder = charset.newDecoder();
                decoder.onMalformedInput(CodingErrorAction.IGNORE);
                decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
                CharsetEncoder encoder = charset.newEncoder();
                encoder.onMalformedInput(CodingErrorAction.IGNORE);
                encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
                try {
                    // The new ByteBuffer is ready to be read.
                    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(text));
                    // The new ByteBuffer is ready to be read.
                    CharBuffer cbuf = decoder.decode(bbuf);
                    String str = cbuf.toString();
                } catch (CharacterCodingException e) {
                    logger.error("Error Message if you want to");

                } 

HttpServletRequest to complete URL

In a Spring project you can use

UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request)).build().toUriString()

SELECT from nothing?

It's not consistent across vendors - Oracle, MySQL, and DB2 support dual:

SELECT 'Hello world'
  FROM DUAL

...while SQL Server, PostgreSQL, and SQLite don't require the FROM DUAL:

SELECT 'Hello world'

MySQL does support both ways.

How can I verify if a Windows Service is running

I guess something like this would work:

Add System.ServiceProcess to your project references (It's on the .NET tab).

using System.ServiceProcess;

ServiceController sc = new ServiceController(SERVICENAME);

switch (sc.Status)
{
    case ServiceControllerStatus.Running:
        return "Running";
    case ServiceControllerStatus.Stopped:
        return "Stopped";
    case ServiceControllerStatus.Paused:
        return "Paused";
    case ServiceControllerStatus.StopPending:
        return "Stopping";
    case ServiceControllerStatus.StartPending:
        return "Starting";
    default:
        return "Status Changing";
}

Edit: There is also a method sc.WaitforStatus() that takes a desired status and a timeout, never used it but it may suit your needs.

Edit: Once you get the status, to get the status again you will need to call sc.Refresh() first.

Reference: ServiceController object in .NET.

How to create streams from string in Node.Js?

From node 10.17, stream.Readable have a from method to easily create streams from any iterable (which includes array literals):

const { Readable } = require("stream")

const readable = Readable.from(["input string"])

readable.on("data", (chunk) => {
  console.log(chunk) // will be called once with `"input string"`
})

Note that at least between 10.17 and 12.3, a string is itself a iterable, so Readable.from("input string") will work, but emit one event per character. Readable.from(["input string"]) will emit one event per item in the array (in this case, one item).

Also note that in later nodes (probably 12.3, since the documentation says the function was changed then), it is no longer necessary to wrap the string in an array.

https://nodejs.org/api/stream.html#stream_stream_readable_from_iterable_options

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

Most probably the answer is to install MySQL Developer Build and selecting "C headers\libs" option during configuration. (as reported in this entry: Building MySQLdb for Python on Windows on rationalpie.wordpress.com)

Maybe even better solution is to install a precompiled build: http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe

Looking for simple Java in-memory cache

If you're needing something simple, would this fit the bill?

Map<K, V> myCache = Collections.synchronizedMap(new WeakHashMap<K, V>());

It wont save to disk, but you said you wanted simple...

Links:

(As Adam commented, synchronising a map has a performance hit. Not saying the idea doesn't have hairs on it, but would suffice as a quick and dirty solution.)

How do I check if a column is empty or null in MySQL?

You can test whether a column is null or is not null using WHERE col IS NULL or WHERE col IS NOT NULL e.g.

SELECT myCol 
FROM MyTable 
WHERE MyCol IS NULL 

In your example you have various permutations of white space. You can strip white space using TRIM and you can use COALESCE to default a NULL value (COALESCE will return the first non-null value from the values you suppy.

e.g.

SELECT myCol
FROM MyTable
WHERE TRIM(COALESCE(MyCol, '')) = '' 

This final query will return rows where MyCol is null or is any length of whitespace.

If you can avoid it, it's better not to have a function on a column in the WHERE clause as it makes it difficult to use an index. If you simply want to check if a column is null or empty, you may be better off doing this:

SELECT myCol
FROM MyTable
WHERE MyCol IS NULL OR MyCol =  '' 

See TRIM COALESCE and IS NULL for more info.

Also Working with null values from the MySQL docs

Access to file download dialog in Firefox

I was stuck with the same problem, but I found a solution. I did it the same way as this blog did.

Of course this was Java, I've translated it to Python:

fp = webdriver.FirefoxProfile()

fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir",getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","text/csv")

browser = webdriver.Firefox(firefox_profile=fp)

In my example it was a CSV file. But when you need more, there are stored in the ~/.mozilla/$USER_PROFILE/mimeTypes.rdf

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

C:\xampp>mysql -u root -p mydatabase < C:\DB_Backups\stage-new.sql
Enter password:
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the ma
nual that corresponds to your MySQL server version for the right syntax to use n
ear 'stage-new.sql

----lot of space----

' at line 1

The reason was when I dumped the DB I used following command :

mysqldump -h <host> -u <username> -p <database> > dumpfile.sql
dumpfile.sql

By mistaken dumpfile.sql added twice in the syntax.

Solution : I removed the dumpfile.sql text added to first line of the exported dumpfile.

What is the difference between a URI, a URL and a URN?

URI => http://en.wikipedia.org/wiki/Uniform_Resource_Identifier

URL's are a subset of URI's (which also contain URNs).

Basically, a URI is a general identifier, where a URL specifies a location and a URN specifies a name.

Angular 2.0 and Modal Dialog

try to use ng-window, it's allow developer to open and full control multiple windows in single page applications in simple way, No Jquery, No Bootstrap.

enter image description here

Avilable Configration

  • Maxmize window
  • Minimize window
  • Custom size,
  • Custom posation
  • the window is dragable
  • Block parent window or not
  • Center the window or not
  • Pass values to chield window
  • Pass values from chield window to parent window
  • Listening to closing chield window in parent window
  • Listen to resize event with your custom listener
  • Open with maximum size or not
  • Enable and disable window resizing
  • Enable and disable maximization
  • Enable and disable minimization

How do I make an HTML button not reload the page

I can't comment yet, so I'm posting this as an answer. Best way to avoid reload is how @user2868288 said: using the onsubmit on the form tag.

From all the other possibilities mentioned here, it's the only way which allows the new HTML5 browser data input validation to be triggered (<button> won't do it nor the jQuery/JS handlers) and allows your jQuery/AJAX dynamic info to be appended on the page. For example:

<form id="frmData" onsubmit="return false">
 <input type="email" id="txtEmail" name="input_email" required="" placeholder="Enter a valid e-mail" spellcheck="false"/>
 <input type="tel" id="txtTel" name="input_tel" required="" placeholder="Enter your telephone number" spellcheck="false"/>
 <input type="submit" id="btnSubmit" value="Send Info"/>
</form>
<script type="text/javascript">
  $(document).ready(function(){
    $('#btnSubmit').click(function() {
        var tel = $("#txtTel").val();
        var email = $("#txtEmail").val();
        $.post("scripts/contact.php", {
            tel1: tel,
            email1: email
        })
        .done(function(data) {
            $('#lblEstatus').append(data); // Appends status
            if (data == "Received") {
                $("#btnSubmit").attr('disabled', 'disabled'); // Disable doubleclickers.
            }
        })
        .fail(function(xhr, textStatus, errorThrown) { 
            $('#lblEstatus').append("Error. Try later."); 
        });
     });
   }); 
</script>

Simple DateTime sql query

Others have already said that date literals in SQL Server require being surrounded with single quotes, but I wanted to add that you can solve your month/day mixup problem two ways (that is, the problem where 25 is seen as the month and 5 the day) :

  1. Use an explicit Convert(datetime, 'datevalue', style) where style is one of the numeric style codes, see Cast and Convert. The style parameter isn't just for converting dates to strings but also for determining how strings are parsed to dates.

  2. Use a region-independent format for dates stored as strings. The one I use is 'yyyymmdd hh:mm:ss', or consider ISO format, yyyy-mm-ddThh:mi:ss.mmm. Based on experimentation, there are NO other language-invariant format string. (Though I think you can include time zone at the end, see the above link).

What is an NP-complete in computer science?

The definitions for NP complete problems above is correct, but I thought I might wax lyrical about their philosophical importance as nobody has addressed that issue yet.

Almost all complex problems you'll come up against will be NP Complete. There's something very fundamental about this class, and which just seems to be computationally different from easily solvable problems. They sort of have their own flavour, and it's not so hard to recognise them. This basically means that any moderately complex algorithm is impossible for you to solve exactly -- scheduling, optimising, packing, covering etc.

But not all is lost if a problem you'll encounter is NP Complete. There is a vast and very technical field where people study approximation algorithms, which will give you guarantees for being close to the solution of an NP complete problem. Some of these are incredibly strong guarantees -- for example, for 3sat, you can get a 7/8 guarantee through a really obvious algorithm. Even better, in reality, there are some very strong heuristics, which excel at giving great answers (but no guarantees!) for these problems.

Note that two very famous problems -- graph isomorphism and factoring -- are not known to be P or NP.

How/when to generate Gradle wrapper files?

If you want to download gradle with source and docs, the default distribution url configured in gradle-wrapper.properites will not satisfy your need.It is https://services.gradle.org/distributions/gradle-2.10-bin.zip, not https://services.gradle.org/distributions/gradle-2.10-all.zip.This full url is suggested by IDE such as Android Studio.If you want to download the full gradle,You can configure the wrapper task like this:

task wrapper(type: Wrapper) {
    gradleVersion = '2.13'
    distributionUrl = distributionUrl.replace("bin", "all")
}

How can I get the values of data attributes in JavaScript code?

Circa 2019, using jquery, this can be accessed using $('#DOMId').data('typeId') where $('#DOMId') is the jquery selector for your span element.

How do I download a tarball from GitHub using cURL?

All the other solutions require specifying a release/version number which obviously breaks automation.

This solution- currently tested and known to work with Github API v3- however can be used programmatically to grab the LATEST release without specifying any tag or release number and un-TARs the binary to an arbitrary name you specify in switch --one-top-level="pi-ap". Just swap-out user f1linux and repo pi-ap in below example with your own details and Bob's your uncle:

curl -L https://api.github.com/repos/f1linux/pi-ap/tarball | tar xzvf - --one-top-level="pi-ap" --strip-components 1

HTTP Basic Authentication credentials passed in URL and encryption

Not necessarily true. It will be encrypted on the wire however it still lands in the logs plain text

How to do while loops with multiple conditions

use an infinity loop like what you have originally done. Its cleanest and you can incorporate many conditions as you wish

while 1:
  if condition1 and condition2:
      break
  ...
  ...
  if condition3: break
  ...
  ...

Java: how do I initialize an array size if it's unknown?

int i,largest = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of numbers in the list");
i = scan.nextInt();
int arr[] = new int[i];
System.out.println("Enter the list of numbers:");
for(int j=0;j<i;j++){
    arr[j] = scan.nextInt();
}

The above code works well. I have taken the input of the number of elements in the list and initialized the array accordingly.

TypeError: 'list' object cannot be interpreted as an integer

You should do this instead:

for i in myList:
    # etc.

That is, remove the range() part. The range() function is used to generate a sequence of numbers, and it receives as parameters the limits to generate the range, it won't work to pass a list as parameter. For iterating over the list, just write the loop as shown above.

How to increase icons size on Android Home Screen?

If you want to change settings in the launcher, change icon size, or grid size just hold down on an empty part of your home screen. Tap the three Dots and there you go.

From https://forums.oneplus.net/threads/how-to-change-icon-and-grid-size-trebuchet-settings.84820/

When configuring the phone for first time I saw something about a grid somewhere, but couldn't find it again. Luckily I found the answer on the link above.

Replace only text inside a div using jquery

You need to set the text to something other than an empty string. In addition, the .html() function should do it while preserving the HTML structure of the div.

$('#one').html($('#one').html().replace('text','replace'));

How to convert UTC timestamp to device local time in android

Converting a date String of the format "2011-06-23T15:11:32" to our time zone.

private String getDate(String ourDate)
{
    try
    {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date value = formatter.parse(ourDate);

        SimpleDateFormat dateFormatter = new SimpleDateFormat("MM-dd-yyyy HH:mm"); //this format changeable
        dateFormatter.setTimeZone(TimeZone.getDefault());
        ourDate = dateFormatter.format(value);

        //Log.d("ourDate", ourDate);
    }
    catch (Exception e)
    {
        ourDate = "00-00-0000 00:00";
    }
  return ourDate;
}

Swift days between two NSDates

There's hardly any Swift-specific standard library yet; just the lean basic numeric, string, and collection types.

It's perfectly possible to define such shorthands using extensions, but as far as the actual out-of-the-box APIs goes, there is no "new" Cocoa; Swift just maps directly to the same old verbose Cocoa APIs as they already exist.

No visible cause for "Unexpected token ILLEGAL"

I got this error in chrome when I had an unterminated string after the line that the error pointed to. After closing the string the error went away.

Example with error:

var file = files[i]; // SyntaxError: Unexpected token ILLEGAL

jQuery('#someDiv').innerHTML = file.name + " (" + formatSize(file.size) + ") "
    + "<a href=\"javascript: something('"+file.id+');\">Error is here</a>";

Example without error:

var file = files[i]; // No error

jQuery('#someDiv').innerHTML = file.name + " (" + formatSize(file.size) + ") "
    + "<a href=\"javascript: something('"+file.id+"');\">Error was here</a>";

Route.get() requires callback functions but got a "object Undefined"

My suggestion, if you are still using const XXX = require('library or path./') when using module.exports to export multiple functions use an ES6 arrow function

for example:

module.exports = () => {

const  getPosts = (req, res ) =>{
    res.send('THIS WORKS!');
}

const getPost = async (req, res) => { 
    const { id } = req.params;

    try {
        const post = await PostMessage.findById(id);
        
        res.status(200).json(post);
    } catch (error) {
        res.status(404).json({ message: error.message });
    }
}

}

then Import: const getPosts = require('../controllers/posts.js');

Hope this helps... Cheers! www.miyamotto.net

How to call a MySQL stored procedure from within PHP code?

I now found solution by using mysqli instead of mysql.

<?php 

// enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//connect to database
$connection = mysqli_connect("hostname", "user", "password", "db", "port");

//run the store proc
$result = mysqli_query($connection, "CALL StoreProcName");

//loop the result set
while ($row = mysqli_fetch_array($result)){     
  echo $row[0] . " - " . + $row[1]; 
}

I found that many people seem to have a problem with using mysql_connect, mysql_query and mysql_fetch_array.

How to get the last row of an Oracle a table

The last row according to a strict total order over composite key K(k1, ..., kn):

SELECT  *
FROM    TableX AS o
WHERE   NOT EXISTS (
            SELECT  *
            FROM    TableX AS i
            WHERE   i.k1 > o.k1
                OR  (i.k1 = o.k1 AND i.k2 > o.k2)
                ...
                OR  (i.k1 = o.k1 AND i.k2 = o.k2 AND i.k3 = o.k3 AND ... AND i.kn > o.kn)
        )
;

Given the special case where K is simple (i.e. not composite), the above is shortened to:

SELECT  *
FROM    TableX AS o
WHERE   NOT EXISTS (
            SELECT  *
            FROM    TableX AS i
            WHERE   i.k1 > o.k1
        )
;

Note that for this query to return just one row the key must order without ties. If ties are allowed, this query will return all the rows tied with the greatest key.

DateTime vs DateTimeOffset

The only negative side of DateTimeOffset I see is that Microsoft "forgot" (by design) to support it in their XmlSerializer class. But it has since been added to the XmlConvert utility class.

XmlConvert.ToDateTimeOffset

XmlConvert.ToString

I say go ahead and use DateTimeOffset and TimeZoneInfo because of all the benefits, just beware when creating entities which will or may be serialized to or from XML (all business objects then).

Format an Integer using Java String Format

Use %03d in the format specifier for the integer. The 0 means that the number will be zero-filled if it is less than three (in this case) digits.

See the Formatter docs for other modifiers.

Can I define a class name on paragraph using Markdown?

It should also be mentioned that <span> tags allow inside them -- block-level items negate MD natively inside them unless you configure them not to do so, but in-line styles natively allow MD within them. As such, I often do something akin to...

This is a superfluous paragraph thing.

<span class="class-red">And thus I delve into my topic, Lorem ipsum lollipop bubblegum.</span>

And thus with that I conclude.

I am not 100% sure if this is universal but seems to be the case in all MD editors I've used.

How to call a View Controller programmatically?

You can call ViewController this way, If you want with NavigationController

enter image description here

1.In current Screen : Load new screen

VerifyExpViewController *addProjectViewController = [[VerifyExpViewController alloc] init];
[self.navigationController pushViewController:addProjectViewController animated:YES];

2.1 In Loaded View : add below in .h file

@interface VerifyExpViewController : UIViewController <UINavigationControllerDelegate>

2.2 In Loaded View : add below in .m file

  @implementation VerifyExpViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationController.delegate = self;
    [self setNavigationBar];
}
-(void)setNavigationBar
{
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"B_topbar.png"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Btn_topback.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onBackButtonTap:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor lightGrayColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Save.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onSaveButtonTap:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor lightGrayColor];
}

-(void)onBackButtonTap:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(IBAction)onSaveButtonTap:(id)sender
{
    //todo for save button
}

@end

Hope this will be useful for someone there :)

Optimum way to compare strings in JavaScript?

You can use the comparison operators to compare strings. A strcmp function could be defined like this:

function strcmp(a, b) {
    if (a.toString() < b.toString()) return -1;
    if (a.toString() > b.toString()) return 1;
    return 0;
}

Edit    Here’s a string comparison function that takes at most min { length(a), length(b) } comparisons to tell how two strings relate to each other:

function strcmp(a, b) {
    a = a.toString(), b = b.toString();
    for (var i=0,n=Math.max(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
    if (i === n) return 0;
    return a.charAt(i) > b.charAt(i) ? -1 : 1;
}

how to change the dist-folder path in angular-cli after 'ng build'

Caution: Angular 6 and above!


For readers with an angular.json (not angular-cli.json) the key correct key is outputPath. I guess the angular configuration changed to angular.json in Angular 6, so if you are using version 6 or above you most likely have a angular.json file.

To change the output path you have to change outputPath und the build options.

example angular.json

{
    "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
    "version": 1,
    "projects": {
        "angular-app": {
            "projectType": "application",
            [...]
            "architect": {
                "build": {
                    "builder": "@angular-devkit/build-angular:browser",
                    "options": {
                        "outputPath": "dist/angular-app",
                        "index": "src/index.html",
                        "main": "src/main.ts",
                        [...]

I could not find any official docs on this (not included in https://angular.io/guide/workspace-config as I would have expected), maybe someone can link an official resource on this.

favicon not working in IE

THE SOLUTION :

  • I created an icon from existing png file by simply changing the extension of the image from png to ico. I use drupal 7 bartik theme, so I uploaded the shortcut icon to the server and it WORKED for Chrome and Firefox but not IE. Also, the image icon was white-blank on the desktop.

  • Then I took the advice of some guys here and reduced the size of the image to 32x32 pixels using an image editor (gimp 2<<

  • I uploaded the icon in the same way as earlier, and it worked fine for all browsers.

I love you guys on stackoverflow, you helped me solve LOTS of problems. THANK YOU!

Access to Image from origin 'null' has been blocked by CORS policy

To solve your error I propose this solution: to work on Visual studio code editor and install live server extension in the editor, which allows you to connect to your local server, for me I put the picture in my workspace 127.0.0.1:5500/workspace/data/pict.png and it works!

Why doesn't java.io.File have a close method?

java.io.File doesn't represent an open file, it represents a path in the filesystem. Therefore having close method on it doesn't make sense.

Actually, this class was misnamed by the library authors, it should be called something like Path.

How to validate a date?

One simple way to validate a date string is to convert to a date object and test that, e.g.

_x000D_
_x000D_
// Expect input as d/m/y_x000D_
function isValidDate(s) {_x000D_
  var bits = s.split('/');_x000D_
  var d = new Date(bits[2], bits[1] - 1, bits[0]);_x000D_
  return d && (d.getMonth() + 1) == bits[1];_x000D_
}_x000D_
_x000D_
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {_x000D_
  console.log(s + ' : ' + isValidDate(s))_x000D_
})
_x000D_
_x000D_
_x000D_

When testing a Date this way, only the month needs to be tested since if the date is out of range, the month will change. Same if the month is out of range. Any year is valid.

You can also test the bits of the date string:

_x000D_
_x000D_
function isValidDate2(s) {_x000D_
  var bits = s.split('/');_x000D_
  var y = bits[2],_x000D_
    m = bits[1],_x000D_
    d = bits[0];_x000D_
  // Assume not leap year by default (note zero index for Jan)_x000D_
  var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];_x000D_
_x000D_
  // If evenly divisible by 4 and not evenly divisible by 100,_x000D_
  // or is evenly divisible by 400, then a leap year_x000D_
  if ((!(y % 4) && y % 100) || !(y % 400)) {_x000D_
    daysInMonth[1] = 29;_x000D_
  }_x000D_
  return !(/\D/.test(String(d))) && d > 0 && d <= daysInMonth[--m]_x000D_
}_x000D_
_x000D_
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {_x000D_
  console.log(s + ' : ' + isValidDate2(s))_x000D_
})
_x000D_
_x000D_
_x000D_

Append data to a POST NSURLRequest

All the changes to the NSMutableURLRequest must be made before calling NSURLConnection.

I see this problem as I copy and paste the code above and run TCPMon and see the request is GET instead of the expected POST.

NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                     cachePolicy:NSURLRequestUseProtocolCachePolicy
                                 timeoutInterval:60.0];


[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 
                                                         delegate:self];

How to implement authenticated routes in React Router 4?

I was also looking for some answer. Here all answers are quite good, but none of them give answers how we can use it if user starts application after opening it back. (I meant to say using cookie together).

No need to create even different privateRoute Component. Below is my code

    import React, { Component }  from 'react';
    import { Route, Switch, BrowserRouter, Redirect } from 'react-router-dom';
    import { Provider } from 'react-redux';
    import store from './stores';
    import requireAuth from './components/authentication/authComponent'
    import SearchComponent from './components/search/searchComponent'
    import LoginComponent from './components/login/loginComponent'
    import ExampleContainer from './containers/ExampleContainer'
    class App extends Component {
    state = {
     auth: true
    }


   componentDidMount() {
     if ( ! Cookies.get('auth')) {
       this.setState({auth:false });
     }
    }
    render() {
     return (
      <Provider store={store}>
       <BrowserRouter>
        <Switch>
         <Route exact path="/searchComponent" component={requireAuth(SearchComponent)} />
         <Route exact path="/login" component={LoginComponent} />
         <Route exact path="/" component={requireAuth(ExampleContainer)} />
         {!this.state.auth &&  <Redirect push to="/login"/> }
        </Switch>
       </BrowserRouter>
      </Provider>);
      }
     }
    }
    export default App;

And here is authComponent

import React  from 'react';
import { withRouter } from 'react-router';
import * as Cookie from "js-cookie";
export default function requireAuth(Component) {
class AuthenticatedComponent extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
   auth: Cookie.get('auth')
  }
 }
 componentDidMount() {
  this.checkAuth();
 }
 checkAuth() {
  const location = this.props.location;
  const redirect = location.pathname + location.search;
  if ( ! Cookie.get('auth')) {
   this.props.history.push(`/login?redirect=${redirect}`);
  }
 }
render() {
  return Cookie.get('auth')
   ? <Component { ...this.props } />
   : null;
  }
 }
 return  withRouter(AuthenticatedComponent)
}

Below I have written blog, you can get more depth explanation there as well.

Create Protected routes in ReactJS

Swift programmatically navigate to another view controller/scene

You should push the new viewcontroller by using current navigation controller, not present.

self.navigationController.pushViewController(nextViewController, animated: true)

What causing this "Invalid length for a Base-64 char array"

This is because of a huge view state, In my case I got lucky since I was not using the viewstate. I just added enableviewstate="false" on the form tag and view state went from 35k to 100 chars

Optimal way to Read an Excel file (.xls/.xlsx)

Using OLE Query, it's quite simple (e.g. sheetName is Sheet1):

DataTable LoadWorksheetInDataTable(string fileName, string sheetName)
{           
    DataTable sheetData = new DataTable();
    using (OleDbConnection conn = this.returnConnection(fileName))
    {
       conn.Open();
       // retrieve the data using data adapter
       OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "$]", conn);
       sheetAdapter.Fill(sheetData);
       conn.Close();
    }                        
    return sheetData;
}

private OleDbConnection returnConnection(string fileName)
{
    return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");
}

For newer Excel versions:

return new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;");

You can also use Excel Data Reader an open source project on CodePlex. Its works really well to export data from Excel sheets.

The sample code given on the link specified:

FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);

//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//...
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//...
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//...
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();

//5. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}

//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();

Reference: How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

angular 2 ngIf and CSS transition/animation

CSS only solution for modern browsers

@keyframes slidein {
    0%   {margin-left:1500px;}
    100% {margin-left:0px;}
}
.note {
    animation-name: slidein;
    animation-duration: .9s;
    display: block;
}

WARNING: sanitizing unsafe style value url

There is an open issue to only print this warning if there was actually something sanitized: https://github.com/angular/angular/pull/10272

I didn't read in detail when this warning is printed when nothing was sanitized.

Appending a list to a list of lists in R

There are two other solutions which involve assigning to an index one past the end of the list. Here is a solution that does use append.

resultsa <- list(1,2,3,4,5)
resultsb <- list(6,7,8,9,10)
resultsc <- list(11,12,13,14,15)

outlist <- list(resultsa)
outlist <- append(outlist, list(resultsb))
outlist <- append(outlist, list(resultsc))

which gives your requested format

> str(outlist)
List of 3
 $ :List of 5
  ..$ : num 1
  ..$ : num 2
  ..$ : num 3
  ..$ : num 4
  ..$ : num 5
 $ :List of 5
  ..$ : num 6
  ..$ : num 7
  ..$ : num 8
  ..$ : num 9
  ..$ : num 10
 $ :List of 5
  ..$ : num 11
  ..$ : num 12
  ..$ : num 13
  ..$ : num 14
  ..$ : num 15

Singleton: How should it be used

Answer:

Use a Singleton if:

  • You need to have one and only one object of a type in system

Do not use a Singleton if:

  • You want to save memory
  • You want to try something new
  • You want to show off how much you know
  • Because everyone else is doing it (See cargo cult programmer in wikipedia)
  • In user interface widgets
  • It is supposed to be a cache
  • In strings
  • In Sessions
  • I can go all day long

How to create the best singleton:

  • The smaller, the better. I am a minimalist
  • Make sure it is thread safe
  • Make sure it is never null
  • Make sure it is created only once
  • Lazy or system initialization? Up to your requirements
  • Sometimes the OS or the JVM creates singletons for you (e.g. in Java every class definition is a singleton)
  • Provide a destructor or somehow figure out how to dispose resources
  • Use little memory

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

Had the same issue with VirtualBox 5.0.16/rXXX

Installed latest VirtualBox 5.0.18 and installed latest Vagrant 1.9.3, issue went toodles.

Create listview in fragment android

The inflate() method takes three parameters:

  1. The id of a layout XML file (inside R.layout),
  2. A parent ViewGroup into which the fragment's View is to be inserted,

  3. A third boolean telling whether the fragment's View as inflated from the layout XML file should be inserted into the parent ViewGroup.

In this case we pass false because the View will be attached to the parent ViewGroup elsewhere, by some of the Android code we call (in other words, behind our backs). When you pass false as last parameter to inflate(), the parent ViewGroup is still used for layout calculations of the inflated View, so you cannot pass null as parent ViewGroup .

 View rootView = inflater.inflate(R.layout.fragment_photos, container, false);

So, You need to call rootView in here

ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);

jQuery Ajax Request inside Ajax Request

$.ajax({
    url: "<?php echo site_url('upToWeb/ajax_edit/')?>/" + id,
    type: "GET",
    dataType: "JSON",
    success: function (data) {
        if (data.web == 0) {
            if (confirm('Data product upToWeb ?')) {
                $.ajax({
                    url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
                    type: "post",
                    dataType: "json",
                    data: {web: 1},
                    success: function (respons) {
                        location.href = location.pathname;
                    },
                    error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
                        alert(xhr.responseText); // munculkan alert
                    }
                });
            }
        }
        else {
            if (confirm('Data product DownFromWeb ?')) {
                $.ajax({
                    url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
                    type: "post",
                    dataType: "json",
                    data: {web: 0},
                    success: function (respons) {
                        location.href = location.pathname;
                    },
                    error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
                        alert(xhr.responseText); // munculkan alert
                    }
                });
            }
        }
    },

    error: function (jqXHR, textStatus, errorThrown) {
        alert('Error get data from ajax');
    }

});

Change button text from Xcode?

If you've got a button that's hooked up to an action in your code, you can change the title without an instance variable.

For example, if the button is set to this action:

-(IBAction)startSomething:(id)sender;

You can simply do this in the method:

-(IBAction)startSomething:(id)sender {
    [sender setTitle:@"Hello" forState:UIControlStateNormal];
}

Or if you're wanting to toggle the name of the button, you can create a BOOL named "buttonToggled" (for example), and toggle the name this way:

-(IBAction)toggleButton:(id)sender {
    if (!buttonToggled) {
        [sender setTitle:@"Something" forState:UIControlStateNormal];
        buttonToggled = YES;
    }
    else {
        [sender setTitle:@"Different" forState:UIControlStateNormal];
        buttonToggled = NO;
    }
}

Html: Difference between cell spacing and cell padding

Cellpadding is the amount of space between the outer edges of the table cell and the content of the cell.

Cellspacing is the amount of space in between the individual table cells.

More Details *Link 1*

Link 2

Link 3

password-check directive in angularjs

I was dealing with the same issue and found a good blog post about it written by Piotr Buda. It's a good read and it explains the process very well. The code is as follows:

directives.directive("repeatPassword", function() {
    return {
        require: "ngModel",
        link: function(scope, elem, attrs, ctrl) {
            var otherInput = elem.inheritedData("$formController")[attrs.repeatPassword];

            ctrl.$parsers.push(function(value) {
                if(value === otherInput.$viewValue) {
                    ctrl.$setValidity("repeat", true);
                    return value;
                }
                ctrl.$setValidity("repeat", false);
            });

            otherInput.$parsers.push(function(value) {
                ctrl.$setValidity("repeat", value === ctrl.$viewValue);
                return value;
            });
        }
    };
});

So you could do something like:

<input type="password" name="repeatPassword" id="repeatPassword" placeholder="repeat password" ng-model="user.repeatPassword" repeat-password="password" required>

Credit goes to the author

Android EditText for password with android:hint

Just stumbled on the answer. android:inputType="textPassword" does work with android:hint, same as android:password. The only difference is when I use android:gravity="center", the hint will not show if I'm using android:inputType. Case closed!

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

Abort trap 6 error in C

Try this:

void drawInitialNim(int num1, int num2, int num3){
    int board[3][50] = {0}; // This is a local variable. It is not possible to use it after returning from this function. 

    int i, j, k;

    for(i=0; i<num1; i++)
        board[0][i] = 'O';
    for(i=0; i<num2; i++)
        board[1][i] = 'O';
    for(i=0; i<num3; i++)
        board[2][i] = 'O';

    for (j=0; j<3;j++) {
        for (k=0; k<50; k++) {
            if(board[j][k] != 0)
                printf("%c", board[j][k]);
        }
        printf("\n");
    }
}

How can I align text directly beneath an image?

In order to be able to justify the text, you need to know the width of the image. You can just use the normal width of the image, or use a different width, but IE 6 might get cranky at you and not scale.

Here's what you need:

<style type="text/css">
#container { width: 100px; //whatever width you want }

#image {width: 100%; //fill up whole div }

#text { text-align: justify; }    
</style>

 <div id="container"> 
     <img src="" id="image" /> 
     <p id="text">oooh look! text!</p> 
 </div>

PHP/MySQL Insert null values

This is one example where using prepared statements really saves you some trouble.

In MySQL, in order to insert a null value, you must specify it at INSERT time or leave the field out which requires additional branching:

INSERT INTO table2 (f1, f2)
  VALUES ('String Value', NULL);

However, if you want to insert a value in that field, you must now branch your code to add the single quotes:

INSERT INTO table2 (f1, f2)
  VALUES ('String Value', 'String Value');

Prepared statements automatically do that for you. They know the difference between string(0) "" and null and write your query appropriately:

$stmt = $mysqli->prepare("INSERT INTO table2 (f1, f2) VALUES (?, ?)");
$stmt->bind_param('ss', $field1, $field2);

$field1 = "String Value";
$field2 = null;

$stmt->execute();

It escapes your fields for you, makes sure that you don't forget to bind a parameter. There is no reason to stay with the mysql extension. Use mysqli and it's prepared statements instead. You'll save yourself a world of pain.

Java - sending HTTP parameters via POST method easily

Try this pattern:

public static PricesResponse getResponse(EventRequestRaw request) {

    // String urlParameters  = "param1=a&param2=b&param3=c";
    String urlParameters = Piping.serialize(request);

    HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters);

    PricesResponse response = null;

    try {
        // POST
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(urlParameters);
        writer.flush();

        // RESPONSE
        BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8));
        String json = Buffering.getString(reader);
        response = (PricesResponse) Piping.deserialize(json, PricesResponse.class);

        writer.close();
        reader.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    conn.disconnect();

    System.out.println("PricesClient: " + response.toString());

    return response;
}

public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters) {

    return RestClient.getConnection(endPoint, "POST", urlParameters);

}


public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters) {

    System.out.println("ENDPOINT " + endPoint + " METHOD " + method);
    HttpURLConnection conn = null;

    try {
        URL url = new URL(endPoint);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "text/plain");

    } catch (IOException e) {
        e.printStackTrace();
    }

    return conn;
}

Accept function as parameter in PHP

PHP VERSION >= 5.3.0

Example 1: basic

function test($test_param, $my_function) {
    return $my_function($test_param);
}

test("param", function($param) {
    echo $param;
}); //will echo "param"

Example 2: std object

$obj = new stdClass();
$obj->test = function ($test_param, $my_function) {
    return $my_function($test_param);
};

$test = $obj->test;
$test("param", function($param) {
    echo $param;
});

Example 3: non static class call

class obj{
    public function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

$obj = new obj();
$obj->test("param", function($param) {
    echo $param;
});

Example 4: static class call

class obj {
    public static function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

obj::test("param", function($param) {
    echo $param;
});

Error:java: invalid source release: 8 in Intellij. What does it mean?

As Andreas mentioned all about:

Error:java: invalid source release: 8 in IntelliJ
Error:java: invalid source release: 13 in IntelliJ
Error:java: invalid source release: 14 in IntelliJ...

OR whatever version you are using in Java...

The problem will exist if you do not have it matching inside the below code:

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

This 1.8 in my case, must be matching on your device through MAVEN project library, settings, preferences, project setting and SDK.

Use jQuery to change value of a label

Validation (HTML5): Attribute 'name' is not a valid attribute of element 'label'.

Node.js + Nginx - What now?

answering your question 2:

I would use option b simply because it consumes much less resources. with option 'a', every client will cause the server to consume a lot of memory, loading all the files you need (even though i like php, this is one of the problems with it). With option 'b' you can load your libraries (reusable code) and share them among all client requests.

But be ware that if you have multiple cores you should tweak node.js to use all of them.

Serialize Class containing Dictionary member

You can't serialize a class that implements IDictionary. Check out this link.

Q: Why can't I serialize hashtables?

A: The XmlSerializer cannot process classes implementing the IDictionary interface. This was partly due to schedule constraints and partly due to the fact that a hashtable does not have a counterpart in the XSD type system. The only solution is to implement a custom hashtable that does not implement the IDictionary interface.

So I think you need to create your own version of the Dictionary for this. Check this other question.

How do I programmatically change file permissions?

Full control over file attributes is available in Java 7, as part of the "new" New IO facility (NIO.2). For example, POSIX permissions can be set on an existing file with setPosixFilePermissions(), or atomically at file creation with methods like createFile() or newByteChannel().

You can create a set of permissions using EnumSet.of(), but the helper method PosixFilePermissions.fromString() will uses a conventional format that will be more readable to many developers. For APIs that accept a FileAttribute, you can wrap the set of permissions with with PosixFilePermissions.asFileAttribute().

Set<PosixFilePermission> ownerWritable = PosixFilePermissions.fromString("rw-r--r--");
FileAttribute<?> permissions = PosixFilePermissions.asFileAttribute(ownerWritable);
Files.createFile(path, permissions);

In earlier versions of Java, using native code of your own, or exec-ing command-line utilities are common approaches.

Add a dependency in Maven

You'll have to do this in two steps:

1. Give your JAR a groupId, artifactId and version and add it to your repository.

If you don't have an internal repository, and you're just trying to add your JAR to your local repository, you can install it as follows, using any arbitrary groupId/artifactIds:

mvn install:install-file -DgroupId=com.stackoverflow... -DartifactId=yourartifactid... -Dversion=1.0 -Dpackaging=jar -Dfile=/path/to/jarfile

You can also deploy it to your internal repository if you have one, and want to make this available to other developers in your organization. I just use my repository's web based interface to add artifacts, but you should be able to accomplish the same thing using mvn deploy:deploy-file ....

2. Update dependent projects to reference this JAR.

Then update the dependency in the pom.xml of the projects that use the JAR by adding the following to the element:

<dependencies>
    ...
    <dependency>
        <groupId>com.stackoverflow...</groupId>
        <artifactId>artifactId...</artifactId>
        <version>1.0</version>
    </dependency>
    ...
</dependencies>

SqlException: DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null

To get the definition of the SQL codes, the easiest way is to use db2 cli!

at the unix or dos command prompt, just type

db2 "? SQL302"

this will give you the required explanation of the particular SQL code that you normally see in the java exception or your db2 sql output :)

hope this helped.

How to add image for button in android?

Rather humorously, considering your tags, just use the ImageButton widget.

Can't bind to 'formGroup' since it isn't a known property of 'form'

Angular 4 in combination with feature modules (if you are for instance using a shared-module) requires you to also export the ReactiveFormsModule to work.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports:      [
    CommonModule,
    ReactiveFormsModule
  ],
  declarations: [],
  exports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ]
})
export class SharedModule { } 

How to uninstall Jenkins?

Keep in mind, that in Terminal you need to add backslash before space, so the proper copy/paste will be

/Library/Application\ Support/Jenkins/Uninstall.command

p.s. sorry for the late answer :)

Load and execution sequence of a web page?

If you're asking this because you want to speed up your web site, check out Yahoo's page on Best Practices for Speeding Up Your Web Site. It has a lot of best practices for speeding up your web site.

Display Last Saved Date on worksheet

You can also simple add the following into the Header or Footer of the Worksheet

Last Saved: &[Date] &[Time]

How to use comparison and ' if not' in python?

Operator precedence in python
You can see that not X has higher precedence than and. Which means that the not only apply to the first part (u0 <= u). Write:

if not (u0 <= u and u < u0+step):  

or even

if not (u0 <= u < u0+step):  

What does "for" attribute do in HTML <label> tag?

Using label for= in html form

This could permit to visualy dissociate label(s) and object while keeping them linked.

Sample: there is a checkbox and two labels. You could check/uncheck the box by clicking indifferently on any label or on box, but not on text nor on input content...

_x000D_
_x000D_
<label for="demo1"> There is a label </label>
<br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis sem velit, ultrices et, fermentum auctor, rhoncus ut, ligula. Phasellus at purus sed purus cursus iaculis. Suspendisse fermentum. Pellentesque et arcu. Maecenas viverra. In consectetuer, lorem eu lobortis egestas, velit odio imperdiet eros, sit amet sagittis nunc mi ac neque. Sed non ipsum. Nullam venenatis gravida orci.
<br />
<label for="demo1"> There is a 2nd label </label>
<input id="demo1" type="checkbox">Demo 1</input>
_x000D_
_x000D_
_x000D_

Some useful tricks

By use stylesheet CSS power, you could do a lot of interresting things...

_x000D_
_x000D_
#demo2:checked ~ .but2:before { content: 'Des'; }
#demo2:checked ~ .box2:before { content: '?'; }
.but2:before { content: 'S'; }
.box2:before { content: '?'; }
#demo1:checked ~ .but1:before { content: 'Des'; }
#demo1:checked ~ .box1:before { content: '?'; }
.but1:before { content: 'S'; }
.box1:before { content: '?'; }
_x000D_
<input id="demo1" type="checkbox">Demo 1</input>
<input id="demo2" type="checkbox">Demo 2</input>
<br />
<label for="demo1" class="but1">elect 2</label> - 
<label for="demo2" class="but2">elect 1</label>
<br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis sem velit, ultrices et, fermentum auctor, rhoncus ut, ligula. Phasellus at purus sed purus cursus iaculis. Suspendisse fermentum. Pellentesque et arcu. Maecenas viverra. In consectetuer, lorem eu lobortis egestas, velit odio imperdiet eros, sit amet sagittis nunc mi ac neque. Sed non ipsum. Nullam venenatis gravida orci.
<br />
<label for="demo1" class="but1">elect this 2nd label </label> - 
<label class="but2" for="demo2">elect this another 2nd label </label>
<br />
<label for="demo1" class="box1"> check 1</label>
<label for="demo2" class="box2"> check 2</label> 
_x000D_
_x000D_
_x000D_

Finding all cycles in a directed graph

In the case of undirected graph, a paper recently published (Optimal listing of cycles and st-paths in undirected graphs) offers an asymptotically optimal solution. You can read it here http://arxiv.org/abs/1205.2766 or here http://dl.acm.org/citation.cfm?id=2627951 I know it doesn't answer your question, but since the title of your question doesn't mention direction, it might still be useful for Google search

SecurityError: The operation is insecure - window.history.pushState()

I had this problem on ReactJS history push, turned out i was trying to open //link (with double slashes)

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

How to achieve ripple animation using support library?

sometimes will b usable this line on any layout or components.

 android:background="?attr/selectableItemBackground"

Like as.

 <RelativeLayout
                android:id="@+id/relative_ticket_checkin"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="?attr/selectableItemBackground">

increase the java heap size permanently?

what platform are you running?..
if its unix, maybe adding

alias java='java -Xmx1g'  

to .bashrc (or similar) work

edit: Changing XmX to Xmx

How to enable PHP short tags?

For Wamp Server users there is easier way: You may enable that setting simply (left) click once on the WampServer icon, choose PHP -> PHP settings -> short open tag. Wait for a second, then WampServer will automatically restart your PHP and also its web service.

originally from: http://osticket.com/forums/showthread.php?t=3149

TreeMap sort by value

A lot of people hear adviced to use List and i prefer to use it as well

here are two methods you need to sort the entries of the Map according to their values.

    static final Comparator<Entry<?, Double>> DOUBLE_VALUE_COMPARATOR = 
        new Comparator<Entry<?, Double>>() {
            @Override
            public int compare(Entry<?, Double> o1, Entry<?, Double> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        };

        static final List<Entry<?, Double>> sortHashMapByDoubleValue(HashMap temp)
        {
            Set<Entry<?, Double>> entryOfMap = temp.entrySet();

            List<Entry<?, Double>> entries = new ArrayList<Entry<?, Double>>(entryOfMap);
            Collections.sort(entries, DOUBLE_VALUE_COMPARATOR);
            return entries;
        }

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

In some cases, DateTime.MinValue (or equivalenly, default(DateTime)) is used to indicate an unknown value.

This simple extension method can help handle such situations:

public static class DbDateHelper
{
    /// <summary>
    /// Replaces any date before 01.01.1753 with a Nullable of 
    /// DateTime with a value of null.
    /// </summary>
    /// <param name="date">Date to check</param>
    /// <returns>Input date if valid in the DB, or Null if date is 
    /// too early to be DB compatible.</returns>
    public static DateTime? ToNullIfTooEarlyForDb(this DateTime date)
    {
        return (date >= (DateTime) SqlDateTime.MinValue) ? date : (DateTime?)null;
    }
}

Usage:

 DateTime? dateToPassOnToDb = tooEarlyDate.ToNullIfTooEarlyForDb();

How to set margin with jquery?

Set it with a px value. Changing the code like below should work

el.css('marginLeft', mrg + 'px');

Are HTTP cookies port specific?

This is a big gray area in cookie SOP (Same Origin Policy).

Theoretically, you can specify port number in the domain and the cookie will not be shared. In practice, this doesn't work with several browsers and you will run into other issues. So this is only feasible if your sites are not for general public and you can control what browsers to use.

The better approach is to get 2 domain names for the same IP and not relying on port numbers for cookies.

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

The entity which has the table with foreign key in the database is the owning entity and the other table, being pointed at, is the inverse entity.

Difference between Divide and Conquer Algo and Dynamic Programming

Divide and Conquer

  • In this problem is solved in following three steps: 1. Divide - Dividing into number of sub-problems 2. Conquer - Conquering by solving sub-problems recursively 3. Combine - Combining sub-problem solutions to get original problem's solution
  • Recursive approach
  • Top Down technique
  • Example: Merge Sort

Dynamic Programming

  • In this the problem is solved in following steps: 1. Defining structure of optimal solution 2. Defines value of optimal solutions repeatedly. 3. Obtaining values of optimal solution in bottom-up fashion 4. Getting final optimal solution from obtained values
  • Non-Recursive
  • Bottom Up Technique
  • Example: Strassen's Matrix Multiplication

How to print a groupby object

Call list() on the GroupBy object

print(list(df.groupby('A')))

gives you:

[('one',      A  B
0  one  0
1  one  1
5  one  5), ('three',        A  B
3  three  3
4  three  4), ('two',      A  B
2  two  2)]

How do you post to the wall on a facebook page (not profile)

If your blog outputs an RSS feed you can use Facebook's "RSS Graffiti" application to post that feed to your wall in Facebook. There are other RSS Facebook apps as well; just search "Facebook for RSS apps"...

What is trunk, branch and tag in Subversion?

The "trunk", "branches", and "tags" directories are conventions in Subversion. Subversion does not require you to have these directories nor assign special meaning to them. However, this convention is very common and, unless you have a really good reason, you should follow the convention. The book links that other readers have given describe the convention and how to use it.