Programs & Examples On #Bios

The BIOS software is built into the PC, and is the first code run by a PC when powered on ('boot firmware'). The primary function of the BIOS is to load and start an operating system.

What "wmic bios get serialnumber" actually retrieves?

wmic bios get serialnumber     

if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)

I had to do exactly that.:):)

How can I force gradle to redownload dependencies?

You can tell Gradle to re-download some dependencies in the build script by flagging the dependency as 'changing'. Gradle will then check for updates every 24 hours, but this can be configured using the resolutionStrategy DSL. I find it useful to use this for for SNAPSHOT or NIGHTLY builds.

configurations.all {
    // Check for updates every build
    resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}

Expanded:

dependencies {
    implementation group: "group", name: "projectA", version: "1.1-SNAPSHOT", changing: true
}

Condensed:

implementation('group:projectA:1.1-SNAPSHOT') { changing = true }

I found this solution at this forum thread.

Is it possible to see more than 65536 rows in Excel 2007?

Excel 2003, doesn't included 1M row features, Introduced in 2007 onwards.

In Excel2007, save as "normal" Excel file, not a backwards compatible one.

You may have to close and re-open Excel to get the full 1M rows

Thilip

How do I list one filename per output line in Linux?

you can use ls -1

ls -l will also do the work

foreach vs someList.ForEach(){}

You could name the anonymous delegate :-)

And you can write the second as:

someList.ForEach(s => s.ToUpper())

Which I prefer, and saves a lot of typing.

As Joachim says, parallelism is easier to apply to the second form.

Auto submit form on page load

You can submit any form automatically on page load simply by adding a snippet of javascript code to your body tag referencing the form name like this....

<body onload="document.form1.submit()">

Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers

this is backend problem. if use sails api on backend change cors.js and add your filed here

module.exports.cors = {
  allRoutes: true,
  origin: '*',
  credentials: true,
  methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
  headers: 'Origin, X-Requested-With, Content-Type, Accept, Engaged-Auth-Token'
};

What is the purpose of willSet and didSet in Swift?

The many well-written existing answers cover the question well, but I'll mention, in some detail, an addition that I believe is worth covering.


The willSet and didSet property observers can be used to call delegates, e.g., for class properties that are only ever updated by user interaction, but where you want to avoid calling the delegate at object initialization.

I'll cite Klaas up-voted comment to the accepted answer:

willSet and didSet observers are not called when a property is first initialized. They are only called when the property’s value is set outside of an initialization context.

This is a quite neat as it means e.g. the didSet property is a good choice of launch point for delegate callbacks & functions, for your own custom classes.

As an example, consider some custom user control object, with some key property value (e.g. position in rating control), implemented as a subclass of UIView:

// CustomUserControl.swift
protocol CustomUserControlDelegate {
    func didChangeValue(value: Int)
    // func didChangeValue(newValue: Int, oldValue: Int)
    // func didChangeValue(customUserControl: CustomUserControl)
    // ... other more sophisticated delegate functions
}

class CustomUserControl: UIView {

    // Properties
    // ...
    private var value = 0 {
        didSet {
            // Possibly do something ...

            // Call delegate.
            delegate?.didChangeValue(value)
            // delegate?.didChangeValue(value, oldValue: oldValue)
            // delegate?.didChangeValue(self)
        }
    }

    var delegate: CustomUserControlDelegate?

    // Initialization
    required init?(...) { 
        // Initialise something ...

        // E.g. 'value = 1' would not call didSet at this point
    }

    // ... some methods/actions associated with your user control.
}

After which your delegate functions can be used in, say, some view controller to observe key changes in the model for CustomViewController, much like you'd use the inherent delegate functions of the UITextFieldDelegate for UITextField objects (e.g. textFieldDidEndEditing(...)).

For this simple example, use a delegate callback from the didSet of the class property value to tell a view controller that one of it's outlets have had associated model update:

// ViewController.swift
Import UIKit
// ...

class ViewController: UIViewController, CustomUserControlDelegate {

    // Properties
    // ...
    @IBOutlet weak var customUserControl: CustomUserControl!

    override func viewDidLoad() {
        super.viewDidLoad()
        // ...

        // Custom user control, handle through delegate callbacks.
        customUserControl = self
    }

    // ...

    // CustomUserControlDelegate
    func didChangeValue(value: Int) {
        // do some stuff with 'value' ...
    }

    // func didChangeValue(newValue: Int, oldValue: Int) {
        // do some stuff with new as well as old 'value' ...
        // custom transitions? :)
    //}

    //func didChangeValue(customUserControl: CustomUserControl) {
    //    // Do more advanced stuff ...
    //}
}

Here, the value property has been encapsulated, but generally: in situations like these, be careful not to update the value property of the customUserControl object in the scope of the associated delegate function (here: didChangeValue()) in the view controller, or you'll end up with infinite recursion.

How to read GET data from a URL using JavaScript?

The currently selected answer did not work well at all in my case, which I feel is a fairly typical one. I found the below function here and it works great!

function getAllUrlParams(url) {

  // get query string from url (optional) or window
  var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

  // we'll store the parameters here
  var obj = {};

  // if query string exists
  if (queryString) {

    // stuff after # is not part of query string, so get rid of it
    queryString = queryString.split('#')[0];

    // split our query string into its component parts
    var arr = queryString.split('&');

    for (var i=0; i<arr.length; i++) {
      // separate the keys and the values
      var a = arr[i].split('=');

      // in case params look like: list[]=thing1&list[]=thing2
      var paramNum = undefined;
      var paramName = a[0].replace(/\[\d*\]/, function(v) {
        paramNum = v.slice(1,-1);
        return '';
      });

      // set parameter value (use 'true' if empty)
      var paramValue = typeof(a[1])==='undefined' ? true : a[1];

      // (optional) keep case consistent
      paramName = paramName.toLowerCase();
      paramValue = paramValue.toLowerCase();

      // if parameter name already exists
      if (obj[paramName]) {
        // convert value to array (if still string)
        if (typeof obj[paramName] === 'string') {
          obj[paramName] = [obj[paramName]];
        }
        // if no array index number specified...
        if (typeof paramNum === 'undefined') {
          // put the value on the end of the array
          obj[paramName].push(paramValue);
        }
        // if array index number specified...
        else {
          // put the value at that index number
          obj[paramName][paramNum] = paramValue;
        }
      }
      // if param name doesn't exist yet, set it
      else {
        obj[paramName] = paramValue;
      }
    }
  }

  return obj;
}

How to format html table with inline styles to look like a rendered Excel table?

Add cellpadding and cellspacing to solve it. Edit: Also removed double pixel border.

<style>
td
{border-left:1px solid black;
border-top:1px solid black;}
table
{border-right:1px solid black;
border-bottom:1px solid black;}
</style>
<html>
    <body>
        <table cellpadding="0" cellspacing="0">
            <tr>
                <td width="350" >
                    Foo
                </td>
                <td width="80" >
                    Foo1
                </td>
                <td width="65" >
                    Foo2
                </td>
            </tr>
            <tr>
                <td>
                    Bar1
                </td>
                <td>
                    Bar2
                </td>
                <td>
                    Bar3
                </td>
            </tr>
            <tr >
                <td>
                    Bar1
                </td>
                <td>
                    Bar2
                </td>
                <td>
                    Bar3
                </td>
            </tr>
        </table>
    </body>
</html>

HTML form with side by side input fields

I would go with Larry K's solution, but you can also set the display to inline-block if you want the benefits of both block and inline elements.

You can do this in the div tag by inserting:

style="display:inline-block;"

Or in a CSS stylesheet with this method:

div { display:inline-block; }

Hope it helps, but as earlier mentioned, I would personally go for Larry K's solution ;-)

Reading/writing an INI file

Here is my class, works like a charm :

public static class IniFileManager
{


    [DllImport("kernel32")]
    private static extern long WritePrivateProfileString(string section,
        string key, string val, string filePath);
    [DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section,
             string key, string def, StringBuilder retVal,
        int size, string filePath);
    [DllImport("kernel32.dll")]
    private static extern int GetPrivateProfileSection(string lpAppName,
             byte[] lpszReturnBuffer, int nSize, string lpFileName);


    /// <summary>
    /// Write Data to the INI File
    /// </summary>
    /// <PARAM name="Section"></PARAM>
    /// Section name
    /// <PARAM name="Key"></PARAM>
    /// Key Name
    /// <PARAM name="Value"></PARAM>
    /// Value Name
    public static void IniWriteValue(string sPath,string Section, string Key, string Value)
    {
        WritePrivateProfileString(Section, Key, Value, sPath);
    }

    /// <summary>
    /// Read Data Value From the Ini File
    /// </summary>
    /// <PARAM name="Section"></PARAM>
    /// <PARAM name="Key"></PARAM>
    /// <PARAM name="Path"></PARAM>
    /// <returns></returns>
    public static string IniReadValue(string sPath,string Section, string Key)
    {
        StringBuilder temp = new StringBuilder(255);
        int i = GetPrivateProfileString(Section, Key, "", temp,
                                        255, sPath);
        return temp.ToString();

    }

}

The use is obviouse since its a static class, just call IniFileManager.IniWriteValue for readsing a section or IniFileManager.IniReadValue for reading a section.

jQuery: how to scroll to certain anchor/div on page load?

Have a look at this

Appending the #value into the address is default behaviour that browsers such as IE use to identify named anchor positions on the page, seeing this comes from Netscape.

You can intercept it and remove it, read this article.

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

SecurityException: Permission denied (missing INTERNET permission?)

Add to manifest file the line:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

It fixed it for me.

error::make_unique is not a member of ‘std’

1.gcc version >= 5
2.CXXFLAGS += -std=c++14
3. #include <memory>

Create Local SQL Server database

Your best bet over here to install XAMPP..Follow the link download it , it has an instruction file as well. You can setup your own MY SQL database and then connect to on your local machine.

https://www.apachefriends.org/download.html

Apache shutdown unexpectedly

Stop the IIS service. It should work then

Need to install urllib2 for Python 3.5.1

Acording to the docs:

Note The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

So it appears that it is impossible to do what you want but you can use appropriate python3 functions from urllib.request.

Check if a Class Object is subclass of another Class Object in Java

//Inheritance

    class A {
      int i = 10;
      public String getVal() {
        return "I'm 'A'";
      }
    }

    class B extends A {
      int j = 20;
      public String getVal() {
        return "I'm 'B'";
      }
    }

    class C extends B {
        int k = 30;
        public String getVal() {
          return "I'm 'C'";
        }
    }

//Methods

    public static boolean isInheritedClass(Object parent, Object child) {
      if (parent == null || child == null) {
        return false;
      } else {
        return isInheritedClass(parent.getClass(), child.getClass());
      }
    }

    public static boolean isInheritedClass(Class<?> parent, Class<?> child) {
      if (parent == null || child == null) {
        return false;
      } else {
        if (parent.isAssignableFrom(child)) {
          // is child or same class
          return parent.isAssignableFrom(child.getSuperclass());
        } else {
          return false;
        }
      }
    }

// Test the code

    System.out.println("isInheritedClass(new A(), new B()):" + isInheritedClass(new A(), new B()));
    System.out.println("isInheritedClass(new A(), new C()):" + isInheritedClass(new A(), new C()));
    System.out.println("isInheritedClass(new A(), new A()):" + isInheritedClass(new A(), new A()));
    System.out.println("isInheritedClass(new B(), new A()):" + isInheritedClass(new B(), new A()));


    System.out.println("isInheritedClass(A.class, B.class):" + isInheritedClass(A.class, B.class));
    System.out.println("isInheritedClass(A.class, C.class):" + isInheritedClass(A.class, C.class));
    System.out.println("isInheritedClass(A.class, A.class):" + isInheritedClass(A.class, A.class));
    System.out.println("isInheritedClass(B.class, A.class):" + isInheritedClass(B.class, A.class));

//Result

    isInheritedClass(new A(), new B()):true
    isInheritedClass(new A(), new C()):true
    isInheritedClass(new A(), new A()):false
    isInheritedClass(new B(), new A()):false
    isInheritedClass(A.class, B.class):true
    isInheritedClass(A.class, C.class):true
    isInheritedClass(A.class, A.class):false
    isInheritedClass(B.class, A.class):false

'POCO' definition

In Java land typically "PO" means "plain old". The rest can be tricky, so I'm guessing that your example (in the context of Java) is "plain old class object".

some other examples

  • POJO (plain old java object)
  • POJI (plain old java interface)

RSpec: how to test if a method was called?

In the new rspec expect syntax this would be:

expect(subject).to receive(:bar).with("an argument I want")

How do I display the value of a Django form field in a template?

If you've populated the form with an instance and not with POST data (as the suggested answer requires), you can access the data using {{ form.instance.my_field_name }}.

Using Selenium Web Driver to retrieve value of a HTML input

Following @ragzzy 's answer I use

 public static string Value(this IWebElement element, IJavaScriptExecutor javaScriptExecutor)
    {

        try
        {
            string value = javaScriptExecutor.ExecuteScript("return arguments[0].value", element) as string;
            return value;
        }
        catch (Exception)
        {
            return null;
        }
    }

It works quite well and does not alter the DOM

JavaScript associative array to JSON

Agreed that it is probably best practice to keep Objects as objects and Arrays as arrays. However, if you have an Object with named properties that you are treating as an array, here is how it can be done:

let tempArr = [];
Object.keys(objectArr).forEach( (element) => {
    tempArr.push(objectArr[element]);
});

let json = JSON.stringify(tempArr);

iPhone SDK on Windows (alternative solutions)

This really comes down to how much you value your time. As the other posters have mentioned, there are a couple of ways you can build iPhone apps without a Mac. However, you are jumping through serious hoops, and it'll be much more difficult and take longer than it would with the proper development chain.

You can buy a second-hand Mac Mini for a couple of hundred bucks on eBay. If you're serious about doing iPhone development you'll make this back in saved time very quickly.

ORA-01008: not all variables bound. They are bound

Came here looking for help as got same error running a statement listed below while going through a Udemy course:

INSERT INTO departments (department_id, department_name)
                  values( &dpet_id, '&dname');  

I'd been able to run statements with substitution variables before. Comment by Charles Burns about possibility of server reaching some threshold while recreating the variables prompted me to log out and restart the SQL Developer. The statement ran fine after logging back in.

Thought I'd share for anyone else venturing here with a limited scope issue as mine.

Convert bytes to a string

You can just do:

print(command_stdout.decode('utf-8'))

Cross-platform way of getting temp directory in Python

The simplest way, based on @nosklo's comment and answer:

import tempfile
tmp = tempfile.mkdtemp()

But if you want to manually control the creation of the directories:

import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)

That way you can easily clean up after yourself when you are done (for privacy, resources, security, whatever) with:

from shutil import rmtree
rmtree(tmp, ignore_errors=True)

This is similar to what applications like Google Chrome and Linux systemd do. They just use a shorter hex hash and an app-specific prefix to "advertise" their presence.

Java 8: merge lists with stream API

In Java 8 we can use stream List1.stream().collect(Collectors.toList()).addAll(List2); Another option List1.addAll(List2)

Calling a JavaScript function named in a variable

I'd avoid eval.

To solve this problem, you should know these things about JavaScript.

  1. Functions are first-class objects, so they can be properties of an object (in which case they are called methods) or even elements of arrays.
  2. If you aren't choosing the object a function belongs to, it belongs to the global scope. In the browser, that means you're hanging it on the object named "window," which is where globals live.
  3. Arrays and objects are intimately related. (Rumor is they might even be the result of incest!) You can often substitute using a dot . rather than square brackets [], or vice versa.

Your problem is a result of considering the dot manner of reference rather than the square bracket manner.

So, why not something like,

window["functionName"]();

That's assuming your function lives in the global space. If you've namespaced, then:

myNameSpace["functionName"]();

Avoid eval, and avoid passing a string in to setTimeout and setInterval. I write a lot of JS, and I NEVER need eval. "Needing" eval comes from not knowing the language deeply enough. You need to learn about scoping, context, and syntax. If you're ever stuck with an eval, just ask--you'll learn quickly.

WinError 2 The system cannot find the file specified (Python)

Popen expect a list of strings for non-shell calls and a string for shell calls.

Call subprocess.Popen with shell=True:

process = subprocess.Popen(command, stdout=tempFile, shell=True)

Hopefully this solves your issue.

This issue is listed here: https://bugs.python.org/issue17023

Stopping fixed position scrolling at a certain point?

I loved @james answer but I was looking for its inverse i.e. stop fixed position right before footer, here is what I came up with

var $fixed_element = $(".some_element")
if($fixed_element.length){
        var $offset = $(".footer").position().top,
            $wh = $(window).innerHeight(),
            $diff = $offset - $wh,
            $scrolled = $(window).scrollTop();
        $fixed_element.css("bottom", Math.max(0, $scrolled-$diff));
    }

So now the fixed element would stop right before footer. and will not overlap with it.

Hash Table/Associative Array in VBA

I think you are looking for the Dictionary object, found in the Microsoft Scripting Runtime library. (Add a reference to your project from the Tools...References menu in the VBE.)

It pretty much works with any simple value that can fit in a variant (Keys can't be arrays, and trying to make them objects doesn't make much sense. See comment from @Nile below.):

Dim d As dictionary
Set d = New dictionary

d("x") = 42
d(42) = "forty-two"
d(CVErr(xlErrValue)) = "Excel #VALUE!"
Set d(101) = New Collection

You can also use the VBA Collection object if your needs are simpler and you just want string keys.

I don't know if either actually hashes on anything, so you might want to dig further if you need hashtable-like performance. (EDIT: Scripting.Dictionary does use a hash table internally.)

MongoDB Show all contents from all collections

Step 1: See all your databases:

show dbs

Step 2: Select the database

use your_database_name

Step 3: Show the collections

show collections

This will list all the collections in your selected database.

Step 4: See all the data

db.collection_name.find() 

or

db.collection_name.find().pretty()

Retina displays, high-res background images

Do I need to double the size of the .box div to 400px by 400px to match the new high res background image

No, but you do need to set the background-size property to match the original dimensions:

@media (-webkit-min-device-pixel-ratio: 2), 
(min-resolution: 192dpi) { 

    .box{
        background:url('images/[email protected]') no-repeat top left;
        background-size: 200px 200px;
    }
}

EDIT

To add a little more to this answer, here is the retina detection query I tend to use:

@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (   min--moz-device-pixel-ratio: 2),
only screen and (     -o-min-device-pixel-ratio: 2/1),
only screen and (        min-device-pixel-ratio: 2),
only screen and (                min-resolution: 192dpi),
only screen and (                min-resolution: 2dppx) { 

}

- Source

NB. This min--moz-device-pixel-ratio: is not a typo. It is a well documented bug in certain versions of Firefox and should be written like this in order to support older versions (prior to Firefox 16). - Source


As @LiamNewmarch mentioned in the comments below, you can include the background-size in your shorthand background declaration like so:

.box{
    background:url('images/[email protected]') no-repeat top left / 200px 200px;
}

However, I personally would not advise using the shorthand form as it is not supported in iOS <= 6 or Android making it unreliable in most situations.

Asynchronous Process inside a javascript for loop

async await is here (ES7), so you can do this kind of things very easily now.

  var i;
  var j = 10;
  for (i = 0; i < j; i++) {
    await asycronouseProcess();
    alert(i);
  }

Remember, this works only if asycronouseProcess is returning a Promise

If asycronouseProcess is not in your control then you can make it return a Promise by yourself like this

function asyncProcess() {
  return new Promise((resolve, reject) => {
    asycronouseProcess(()=>{
      resolve();
    })
  })
}

Then replace this line await asycronouseProcess(); by await asyncProcess();

Understanding Promises before even looking into async await is must (Also read about support for async await)

Filter array to have unique values

You could use a hash table for look up and filter all not included values.

_x000D_
_x000D_
var data = ["X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11"],_x000D_
    unique = data.filter(function (a) {_x000D_
        return !this[a] && (this[a] = true);_x000D_
    }, Object.create(null));_x000D_
_x000D_
console.log(unique);
_x000D_
_x000D_
_x000D_

Python Turtle, draw text with on screen with larger font

Use the optional font argument to turtle.write(), from the docs:

turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))
 Parameters:

  • arg – object to be written to the TurtleScreen
  • move – True/False
  • align – one of the strings “left”, “center” or right”
  • font – a triple (fontname, fontsize, fonttype)

So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal")) to change the font size to 16 (default is 8).

Calling onclick on a radiobutton list using javascript

How are you generating the radio button list? If you're just using HTML:

<input type="radio" onclick="alert('hello');"/>

If you're generating these via something like ASP.NET, you can add that as an attribute to each element in the list. You can run this after you populate your list, or inline it if you build up your list one-by-one:

foreach(ListItem RadioButton in RadioButtons){
    RadioButton.Attributes.Add("onclick", "alert('hello');");
}

More info: http://www.w3schools.com/jsref/event_onclick.asp

Node.js global proxy setting

Unfortunately, it seems that proxy information must be set on each call to http.request. Node does not include a mechanism for global proxy settings.

The global-tunnel-ng module on NPM appears to handle this, however:

var globalTunnel = require('global-tunnel-ng');

globalTunnel.initialize({
  host: '10.0.0.10',
  port: 8080,
  proxyAuth: 'userId:password', // optional authentication
  sockets: 50 // optional pool size for each http and https
});

After the global settings are establish with a call to initialize, both http.request and the request library will use the proxy information.

The module can also use the http_proxy environment variable:

process.env.http_proxy = 'http://proxy.example.com:3129';
globalTunnel.initialize();

XAMPP installation on Win 8.1 with UAC Warning

I don't know if you are still having this problem, but I had the same problem and had a different fix than what was listed in the other answer. I did install XAMPP under C:\xampp\, and my user is an admin, but there was also something else.

I had to manually go give my user full access to the C:\Users\XAMPP\ directory. By default (at least on my machine) Windows did not give my admin user rights to this new user's directory, but this is where XAMPP stores all of it's config files. Once I gave myself full access to this, everything worked perfectly.

Hope this helps!

UPDATE!

In retrospect, I think that I must have accidentally typed in "C:\Users\XAMPP\" as the install folder during the installation process. So I think the most important thing is to make sure that the user you are actually signed into Windows as when you start XAMPP has full access to the folder that it was actually installed to.

How to resolve conflicts in EGit

As it's an issue we face more than often, below are the steps to resolve it.

  1. Open the Git perspective. In the Git Repository view, go to on Branches ? Local ? master and right click ? Merge...

  2. It should auto select Remote Tracking ? *origin/master. Press Merge.

  3. Launch stage view in Eclipse.

  4. Double click the files which initially showed conflict

  5. In the conflict merge view, by selecting the left arrow for all the non-conflict + conflict changes from left to right, you can resolve all the conflicts.

  6. Save the merged file.

  7. Do a Team ? pull from Eclipse again.

You are all set :)

How to install packages offline?

Let me go through the process step by step:

  1. On a computer connected to the internet, create a folder.
   $ mkdir packages
   $ cd packages
  1. open up a command prompt or shell and execute the following command:

    Suppose the package you want is tensorflow

    $ pip download tensorflow

  2. Now, on the target computer, copy the packages folder and apply the following command

  $ cd packages
  $ pip install 'tensorflow-xyz.whl' --no-index --find-links '.'

Note that the tensorflow-xyz.whl must be replaced by the original name of the required package.

What does it mean when an HTTP request returns status code 0?

An HTTP response code of 0 indicates that the AJAX request was cancelled.

This can happen either from a timeout, XHR abortion or a firewall stomping on the request. A timeout is common, it means the request failed to execute within a specified time. An XHR Abortion is very simple to do... you can actually call .abort() on an XMLHttpRequest object to cancel the AJAX call. (This is good practice for a single page application if you don't want AJAX calls returning and attempting to reference objects that have been destroyed.) As mentioned in the marked answer, a firewall would also be capable of cancelling the request and trigger this 0 response.

XHR Abort: Abort Ajax requests using jQuery

var xhr = $.ajax({
    type: "POST",
    url: "some.php",
    data: "name=John&location=Boston",
    success: function(msg){
       alert( "Data Saved: " + msg );
    }
});

//kill the request
xhr.abort()

It's worth noting that running the .abort() method on an XHR object will also fire the error callback. If you're doing any kind of error handling that parses these objects, you'll quickly notice that an aborted XHR and a timeout XHR are identical, but with jQuery the textStatus that is passed to the error callback will be "abort" when aborted and "timeout" with a timeout occurs. If you're using Zepto (very very similar to jQuery) the errorType will be "error" when aborted and "timeout" when a timeout occurs.

jQuery: error(jqXHR, textStatus, errorThrown);
Zepto:  error(xhr, errorType, error);

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

A few comments:

import sun.misc.*; Don't do this. It is non-standard and not guaranteed to be the same between implementations. There are other libraries with Base64 conversion available.

byte[] encVal = c.doFinal(Data.getBytes()); You are relying on the default character encoding here. Always specify what character encoding you are using: byte[] encVal = c.doFinal(Data.getBytes("UTF-8")); Defaults might be different in different places.

As @thegrinner pointed out, you need to explicitly check the length of your byte arrays. If there is a discrepancy, then compare them byte by byte to see where the difference is creeping in.

Random integer in VB.NET

All the answers so far have problems or bugs (plural, not just one). I will explain. But first I want to compliment Dan Tao's insight to use a static variable to remember the Generator variable so calling it multiple times will not repeat the same # over and over, plus he gave a very nice explanation. But his code suffered the same flaw that most others have, as i explain now.

MS made their Next() method rather odd. the Min parameter is the inclusive minimum as one would expect, but the Max parameter is the exclusive maximum as one would NOT expect. in other words, if you pass min=1 and max=5 then your random numbers would be any of 1, 2, 3, or 4, but it would never include 5. This is the first of two potential bugs in all code that uses Microsoft's Random.Next() method.

For a simple answer (but still with other possible but rare problems) then you'd need to use:

Private Function GenRandomInt(min As Int32, max As Int32) As Int32
    Static staticRandomGenerator As New System.Random
    Return staticRandomGenerator.Next(min, max + 1)
End Function

(I like to use Int32 rather than Integer because it makes it more clear how big the int is, plus it is shorter to type, but suit yourself.)

I see two potential problems with this method, but it will be suitable (and correct) for most uses. So if you want a simple solution, i believe this is correct.

The only 2 problems i see with this function is: 1: when Max = Int32.MaxValue so adding 1 creates a numeric overflow. altho, this would be rare, it is still a possibility. 2: when min > max + 1. when min = 10 and max = 5 then the Next function throws an error. this may be what you want. but it may not be either. or consider when min = 5 and max = 4. by adding 1, 5 is passed to the Next method, but it does not throw an error, when it really is an error, but Microsoft .NET code that i tested returns 5. so it really is not an 'exclusive' max when the max = the min. but when max < min for the Random.Next() function, then it throws an ArgumentOutOfRangeException. so Microsoft's implementation is really inconsistent and buggy too in this regard.

you may want to simply swap the numbers when min > max so no error is thrown, but it totally depends on what is desired. if you want an error on invalid values, then it is probably better to also throw the error when Microsoft's exclusive maximum (max + 1) in our code equals minimum, where MS fails to error in this case.

handling a work-around for when max = Int32.MaxValue is a little inconvenient, but i expect to post a thorough function which handles both these situations. and if you want different behavior than how i coded it, suit yourself. but be aware of these 2 issues.

Happy coding!

Edit: So i needed a random integer generator, and i decided to code it 'right'. So if anyone wants the full functionality, here's one that actually works. (But it doesn't win the simplest prize with only 2 lines of code. But it's not really complex either.)

''' <summary>
''' Generates a random Integer with any (inclusive) minimum or (inclusive) maximum values, with full range of Int32 values.
''' </summary>
''' <param name="inMin">Inclusive Minimum value. Lowest possible return value.</param>
''' <param name="inMax">Inclusive Maximum value. Highest possible return value.</param>
''' <returns></returns>
''' <remarks></remarks>
Private Function GenRandomInt(inMin As Int32, inMax As Int32) As Int32
    Static staticRandomGenerator As New System.Random
    If inMin > inMax Then Dim t = inMin : inMin = inMax : inMax = t
    If inMax < Int32.MaxValue Then Return staticRandomGenerator.Next(inMin, inMax + 1)
    ' now max = Int32.MaxValue, so we need to work around Microsoft's quirk of an exclusive max parameter.
    If inMin > Int32.MinValue Then Return staticRandomGenerator.Next(inMin - 1, inMax) + 1 ' okay, this was the easy one.
    ' now min and max give full range of integer, but Random.Next() does not give us an option for the full range of integer.
    ' so we need to use Random.NextBytes() to give us 4 random bytes, then convert that to our random int.
    Dim bytes(3) As Byte ' 4 bytes, 0 to 3
    staticRandomGenerator.NextBytes(bytes) ' 4 random bytes
    Return BitConverter.ToInt32(bytes, 0) ' return bytes converted to a random Int32
End Function

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

openpyxl - adjust column width size

Even more pythonic way to set the width of all columns that works at least in openpyxl version 2.4.0:

for column_cells in worksheet.columns:
    length = max(len(as_text(cell.value)) for cell in column_cells)
    worksheet.column_dimensions[column_cells[0].column].width = length

The as_text function should be something that converts the value to a proper length string, like for Python 3:

def as_text(value):
    if value is None:
        return ""
    return str(value)

Bootstrap footer at the bottom of the page

In my case for Bootstrap4:

<body class="d-flex flex-column min-vh-100">
    <div class="wrapper flex-grow-1"></div>
    <footer></footer>
</body>

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

The big thing to get your head around is that the File class tries to represent a view of what Sun like to call "hierarchical pathnames" (basically a path like c:/foo.txt or /usr/muggins). This is why you create files in terms of paths. The operations you are describing are all operations upon this "pathname".

  • getPath() fetches the path that the File was created with (../foo.txt)
  • getAbsolutePath() fetches the path that the File was created with, but includes information about the current directory if the path is relative (/usr/bobstuff/../foo.txt)
  • getCanonicalPath() attempts to fetch a unique representation of the absolute path to the file. This eliminates indirection from ".." and "." references (/usr/foo.txt).

Note I say attempts - in forming a Canonical Path, the VM can throw an IOException. This usually occurs because it is performing some filesystem operations, any one of which could fail.

MYSQL order by both Ascending and Descending sorting

I don't understand what the meaning of ordering with the same column ASC and DESC in the same ORDER BY, but this how you can do it: naam DESC, naam ASC like so:

ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC

How do I group Windows Form radio buttons?

If you cannot put them into one container, then you have to write code to change checked state of each RadioButton:

private void rbDataSourceFile_CheckedChanged(object sender, EventArgs e)
{
    rbDataSourceNet.Checked = !rbDataSourceFile.Checked;
}

private void rbDataSourceNet_CheckedChanged(object sender, EventArgs e)
{
  rbDataSourceFile.Checked = !rbDataSourceNet.Checked;
}

Converting from IEnumerable to List

another way

List<int> list=new List<int>();

IEnumerable<int> enumerable =Enumerable.Range(1, 300);  

foreach (var item in enumerable )  
{     
  list.add(item);  
}

What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?

The key difference(noticed when reading the Spring Docs) between @Autowired and @Inject is that, @Autowired has the 'required' attribute while the @Inject has no 'required' attribute.

cannot open shared object file: No such file or directory

Your LD_LIBRARY_PATH doesn't include the path to libsvmlight.so.

$ export LD_LIBRARY_PATH=/home/tim/program_files/ICMCluster/svm_light/release/lib:$LD_LIBRARY_PATH

How to concatenate strings with padding in sqlite

SQLite has a printf function which does exactly that:

SELECT printf('%s-%.2d-%.4d', col1, col2, col3) FROM mytable

Why is pydot unable to find GraphViz's executables in Windows 8?

On Mac brew install graphviz solved the problem for me.

jQuery Datepicker close datepicker after selected date

This is my edited version : you just need to add an extra argument "autoClose".

example :

 $('input[name="fieldName"]').datepicker({ autoClose: true});

also you can specify a close callback if you want. :)

replace datepicker.js with this:

!function( $ ) {

// Picker object

var Datepicker = function(element, options , closeCallBack){
    this.element = $(element);
    this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'dd/mm/yyyy');
    this.autoClose = options.autoClose||this.element.data('date-autoClose')|| true;
    this.closeCallback = closeCallBack || function(){};
    this.picker = $(DPGlobal.template)
                        .appendTo('body')
                        .on({
                            click: $.proxy(this.click, this)//,
                            //mousedown: $.proxy(this.mousedown, this)
                        });
    this.isInput = this.element.is('input');
    this.component = this.element.is('.date') ? this.element.find('.add-on') : false;

    if (this.isInput) {
        this.element.on({
            focus: $.proxy(this.show, this),
            //blur: $.proxy(this.hide, this),
            keyup: $.proxy(this.update, this)
        });
    } else {
        if (this.component){
            this.component.on('click', $.proxy(this.show, this));
        } else {
            this.element.on('click', $.proxy(this.show, this));
        }
    }

    this.minViewMode = options.minViewMode||this.element.data('date-minviewmode')||0;
    if (typeof this.minViewMode === 'string') {
        switch (this.minViewMode) {
            case 'months':
                this.minViewMode = 1;
                break;
            case 'years':
                this.minViewMode = 2;
                break;
            default:
                this.minViewMode = 0;
                break;
        }
    }
    this.viewMode = options.viewMode||this.element.data('date-viewmode')||0;
    if (typeof this.viewMode === 'string') {
        switch (this.viewMode) {
            case 'months':
                this.viewMode = 1;
                break;
            case 'years':
                this.viewMode = 2;
                break;
            default:
                this.viewMode = 0;
                break;
        }
    }
    this.startViewMode = this.viewMode;
    this.weekStart = options.weekStart||this.element.data('date-weekstart')||0;
    this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
    this.onRender = options.onRender;
    this.fillDow();
    this.fillMonths();
    this.update();
    this.showMode();
};

Datepicker.prototype = {
    constructor: Datepicker,

    show: function(e) {
        this.picker.show();
        this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
        this.place();
        $(window).on('resize', $.proxy(this.place, this));
        if (e ) {
            e.stopPropagation();
            e.preventDefault();
        }
        if (!this.isInput) {
        }
        var that = this;
        $(document).on('mousedown', function(ev){
            if ($(ev.target).closest('.datepicker').length == 0) {
                that.hide();
            }
        });
        this.element.trigger({
            type: 'show',
            date: this.date
        });
    },

    hide: function(){
        this.picker.hide();
        $(window).off('resize', this.place);
        this.viewMode = this.startViewMode;
        this.showMode();
        if (!this.isInput) {
            $(document).off('mousedown', this.hide);
        }
        //this.set();
        this.element.trigger({
            type: 'hide',
            date: this.date
        });
    },

    set: function() {
        var formated = DPGlobal.formatDate(this.date, this.format);
        if (!this.isInput) {
            if (this.component){
                this.element.find('input').prop('value', formated);
            }
            this.element.data('date', formated);
        } else {
            this.element.prop('value', formated);
        }
    },

    setValue: function(newDate) {
        if (typeof newDate === 'string') {
            this.date = DPGlobal.parseDate(newDate, this.format);
        } else {
            this.date = new Date(newDate);
        }
        this.set();
        this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
        this.fill();
    },

    place: function(){
        var offset = this.component ? this.component.offset() : this.element.offset();
        this.picker.css({
            top: offset.top + this.height,
            left: offset.left
        });
    },

    update: function(newDate){
        this.date = DPGlobal.parseDate(
            typeof newDate === 'string' ? newDate : (this.isInput ? this.element.prop('value') : this.element.data('date')),
            this.format
        );
        this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
        this.fill();
    },

    fillDow: function(){
        var dowCnt = this.weekStart;
        var html = '<tr>';
        while (dowCnt < this.weekStart + 7) {
            html += '<th class="dow">'+DPGlobal.dates.daysMin[(dowCnt++)%7]+'</th>';
        }
        html += '</tr>';
        this.picker.find('.datepicker-days thead').append(html);
    },

    fillMonths: function(){
        var html = '';
        var i = 0
        while (i < 12) {
            html += '<span class="month">'+DPGlobal.dates.monthsShort[i++]+'</span>';
        }
        this.picker.find('.datepicker-months td').append(html);
    },

    fill: function() {
        var d = new Date(this.viewDate),
            year = d.getFullYear(),
            month = d.getMonth(),
            currentDate = this.date.valueOf();
        this.picker.find('.datepicker-days th:eq(1)')
                    .text(DPGlobal.dates.months[month]+' '+year);
        var prevMonth = new Date(year, month-1, 28,0,0,0,0),
            day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
        prevMonth.setDate(day);
        prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7);
        var nextMonth = new Date(prevMonth);
        nextMonth.setDate(nextMonth.getDate() + 42);
        nextMonth = nextMonth.valueOf();
        var html = [];
        var clsName,
            prevY,
            prevM;
        while(prevMonth.valueOf() < nextMonth) {zs
            if (prevMonth.getDay() === this.weekStart) {
                html.push('<tr>');
            }
            clsName = this.onRender(prevMonth);
            prevY = prevMonth.getFullYear();
            prevM = prevMonth.getMonth();
            if ((prevM < month &&  prevY === year) ||  prevY < year) {
                clsName += ' old';
            } else if ((prevM > month && prevY === year) || prevY > year) {
                clsName += ' new';
            }
            if (prevMonth.valueOf() === currentDate) {
                clsName += ' active';
            }
            html.push('<td class="day '+clsName+'">'+prevMonth.getDate() + '</td>');
            if (prevMonth.getDay() === this.weekEnd) {
                html.push('</tr>');
            }
            prevMonth.setDate(prevMonth.getDate()+1);
        }
        this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
        var currentYear = this.date.getFullYear();

        var months = this.picker.find('.datepicker-months')
                    .find('th:eq(1)')
                        .text(year)
                        .end()
                    .find('span').removeClass('active');
        if (currentYear === year) {
            months.eq(this.date.getMonth()).addClass('active');
        }

        html = '';
        year = parseInt(year/10, 10) * 10;
        var yearCont = this.picker.find('.datepicker-years')
                            .find('th:eq(1)')
                                .text(year + '-' + (year + 9))
                                .end()
                            .find('td');
        year -= 1;
        for (var i = -1; i < 11; i++) {
            html += '<span class="year'+(i === -1 || i === 10 ? ' old' : '')+(currentYear === year ? ' active' : '')+'">'+year+'</span>';
            year += 1;
        }
        yearCont.html(html);
    },

    click: function(e) {
        e.stopPropagation();
        e.preventDefault();
        var target = $(e.target).closest('span, td, th');
        if (target.length === 1) {
            switch(target[0].nodeName.toLowerCase()) {
                case 'th':
                    switch(target[0].className) {
                        case 'switch':
                            this.showMode(1);
                            break;
                        case 'prev':
                        case 'next':
                            this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call(
                                this.viewDate,
                                this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) + 
                                DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1)
                            );
                            this.fill();
                            this.set();
                            break;
                    }
                    break;
                case 'span':
                    if (target.is('.month')) {
                        var month = target.parent().find('span').index(target);
                        this.viewDate.setMonth(month);
                    } else {
                        var year = parseInt(target.text(), 10)||0;
                        this.viewDate.setFullYear(year);
                    }
                    if (this.viewMode !== 0) {
                        this.date = new Date(this.viewDate);
                        this.element.trigger({
                            type: 'changeDate',
                            date: this.date,
                            viewMode: DPGlobal.modes[this.viewMode].clsName
                        });
                    }
                    this.showMode(-1);
                    this.fill();
                    this.set();
                    break;
                case 'td':
                    if (target.is('.day') && !target.is('.disabled')){
                        var day = parseInt(target.text(), 10)||1;
                        var month = this.viewDate.getMonth();
                        if (target.is('.old')) {
                            month -= 1;
                        } else if (target.is('.new')) {
                            month += 1;
                        }
                        var year = this.viewDate.getFullYear();
                        this.date = new Date(year, month, day,0,0,0,0);
                        this.viewDate = new Date(year, month, Math.min(28, day),0,0,0,0);
                        this.fill();
                        this.set();
                        this.element.trigger({
                            type: 'changeDate',
                            date: this.date,
                            viewMode: DPGlobal.modes[this.viewMode].clsName
                        });
                        if(this.autoClose === true){
                            this.hide();
                            this.closeCallback();
                        }

                    }
                    break;
            }
        }
    },

    mousedown: function(e){
        e.stopPropagation();
        e.preventDefault();
    },

    showMode: function(dir) {
        if (dir) {
            this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
        }
        this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
    }
};

$.fn.datepicker = function ( option, val ) {
    return this.each(function () {
        var $this = $(this);
        var datePicker = $this.data('datepicker');
        var options = typeof option === 'object' && option;
        if (!datePicker) {
            if (typeof val === 'function')
                $this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options),val)));
            else{
                $this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
            }
        }
        if (typeof option === 'string') datePicker[option](val);

    });
};

$.fn.datepicker.defaults = {
    onRender: function(date) {
        return '';
    }
};
$.fn.datepicker.Constructor = Datepicker;

var DPGlobal = {
    modes: [
        {
            clsName: 'days',
            navFnc: 'Month',
            navStep: 1
        },
        {
            clsName: 'months',
            navFnc: 'FullYear',
            navStep: 1
        },
        {
            clsName: 'years',
            navFnc: 'FullYear',
            navStep: 10
    }],
    dates:{
        days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"],
                    daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"],
                    daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"],
                    months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
                    monthsShort: ["Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Déc"],
                    today: "Aujourd'hui",
                    clear: "Effacer",
                    weekStart: 1,
                    format: "dd/mm/yyyy"
    },
    isLeapYear: function (year) {
        return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
    },
    getDaysInMonth: function (year, month) {
        return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
    },
    parseFormat: function(format){
        var separator = format.match(/[.\/\-\s].*?/),
            parts = format.split(/\W+/);
        if (!separator || !parts || parts.length === 0){
            throw new Error("Invalid date format.");
        }
        return {separator: separator, parts: parts};
    },
    parseDate: function(date, format) {
        var parts = date.split(format.separator),
            date = new Date(),
            val;
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        date.setMilliseconds(0);
        if (parts.length === format.parts.length) {
            var year = date.getFullYear(), day = date.getDate(), month = date.getMonth();
            for (var i=0, cnt = format.parts.length; i < cnt; i++) {
                val = parseInt(parts[i], 10)||1;
                switch(format.parts[i]) {
                    case 'dd':
                    case 'd':
                        day = val;
                        date.setDate(val);
                        break;
                    case 'mm':
                    case 'm':
                        month = val - 1;
                        date.setMonth(val - 1);
                        break;
                    case 'yy':
                        year = 2000 + val;
                        date.setFullYear(2000 + val);
                        break;
                    case 'yyyy':
                        year = val;
                        date.setFullYear(val);
                        break;
                }
            }
            date = new Date(year, month, day, 0 ,0 ,0);
        }
        return date;
    },
    formatDate: function(date, format){
        var val = {
            d: date.getDate(),
            m: date.getMonth() + 1,
            yy: date.getFullYear().toString().substring(2),
            yyyy: date.getFullYear()
        };
        val.dd = (val.d < 10 ? '0' : '') + val.d;
        val.mm = (val.m < 10 ? '0' : '') + val.m;
        var date = [];
        for (var i=0, cnt = format.parts.length; i < cnt; i++) {
            date.push(val[format.parts[i]]);
        }
        return date.join(format.separator);
    },
    headTemplate: '<thead>'+
                        '<tr>'+
                            '<th class="prev">&lsaquo;</th>'+
                            '<th colspan="5" class="switch"></th>'+
                            '<th class="next">&rsaquo;</th>'+
                        '</tr>'+
                    '</thead>',
    contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
};
DPGlobal.template = '<div class="datepicker dropdown-menu">'+
                        '<div class="datepicker-days">'+
                            '<table class=" table-condensed">'+
                                DPGlobal.headTemplate+
                                '<tbody></tbody>'+
                            '</table>'+
                        '</div>'+
                        '<div class="datepicker-months">'+
                            '<table class="table-condensed">'+
                                DPGlobal.headTemplate+
                                DPGlobal.contTemplate+
                            '</table>'+
                        '</div>'+
                        '<div class="datepicker-years">'+
                            '<table class="table-condensed">'+
                                DPGlobal.headTemplate+
                                DPGlobal.contTemplate+
                            '</table>'+
                        '</div>'+
                    '</div>';

}( window.jQuery );

Failed to open/create the internal network Vagrant on Windows10

You can try disabling the "VirtualBox NDIS6 Bridged Networking Driver" on all but your actual physical network adapter(s) before attempting to create the VirtualBox host-only adapter again.

See this answer.

Escaping ampersand character in SQL string

--SUBSTITUTION VARIABLES
-- these variables are used to store values TEMPorarily.
-- The values can be stored temporarily through
-- Single Ampersand (&)
-- Double Ampersand(&&)
-- The single ampersand substitution variable applies for each instance when the
--SQL statement is created or executed.
-- The double ampersand substitution variable is applied for all instances until
--that SQL statement is existing.
INSERT INTO Student (Stud_id, First_Name, Last_Name, Dob, Fees, Gender)
VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &fees, '&Gender');
--Using double ampersand substitution variable
INSERT INTO Student (Stud_id,First_Name, Last_Name,Dob,Fees,Gender)
VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &&fees,'&gender');

AutoComplete TextBox Control

private void textBox1_TextChanged(object sender, EventArgs e)
    {
        try
        {
            textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
            textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
            AutoCompleteStringCollection col = new AutoCompleteStringCollection();
            con.Open();
            sql = "select *from Table_Name;
            cmd = new SqlCommand(sql, con);
            SqlDataReader sdr = null;
            sdr = cmd.ExecuteReader();
            while (sdr.Read())
            {
                col.Add(sdr["Column_Name"].ToString());
            }
            sdr.Close(); 

            textBox1.AutoCompleteCustomSource = col;
            con.Close();
        }
        catch
        {
        }
    }

Calculate distance between two latitude-longitude points? (Haversine formula)

Here is a C# Implementation:

static class DistanceAlgorithm
{
    const double PIx = 3.141592653589793;
    const double RADIUS = 6378.16;

    /// <summary>
    /// Convert degrees to Radians
    /// </summary>
    /// <param name="x">Degrees</param>
    /// <returns>The equivalent in radians</returns>
    public static double Radians(double x)
    {
        return x * PIx / 180;
    }

    /// <summary>
    /// Calculate the distance between two places.
    /// </summary>
    /// <param name="lon1"></param>
    /// <param name="lat1"></param>
    /// <param name="lon2"></param>
    /// <param name="lat2"></param>
    /// <returns></returns>
    public static double DistanceBetweenPlaces(
        double lon1,
        double lat1,
        double lon2,
        double lat2)
    {
        double dlon = Radians(lon2 - lon1);
        double dlat = Radians(lat2 - lat1);

        double a = (Math.Sin(dlat / 2) * Math.Sin(dlat / 2)) + Math.Cos(Radians(lat1)) * Math.Cos(Radians(lat2)) * (Math.Sin(dlon / 2) * Math.Sin(dlon / 2));
        double angle = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
        return angle * RADIUS;
    }

}

ORDER BY using Criteria API

This is what you have to do since sess.createCriteria is deprecated:

CriteriaBuilder builder = getSession().getCriteriaBuilder();
CriteriaQuery<User> q = builder.createQuery(User.class);
Root<User> usr = q.from(User.class);
ParameterExpression<String> p = builder.parameter(String.class);
q.select(usr).where(builder.like(usr.get("name"),p))
  .orderBy(builder.asc(usr.get("name")));
TypedQuery<User> query = getSession().createQuery(q);
query.setParameter(p, "%" + Main.filterName + "%");
List<User> list = query.getResultList();

MySQL "Or" Condition

try this

mysql_query("
SELECT * FROM Drinks WHERE
    email='$Email'
    AND date='$Date_Today'
    OR date='$Date_Yesterday', '$Date_TwoDaysAgo', '$Date_ThreeDaysAgo', '$Date_FourDaysAgo', '$Date_FiveDaysAgo', '$Date_SixDaysAgo', '$Date_SevenDaysAgo'"     
   );

my be like this

 OR date='$Date_Yesterday' oR '$Date_TwoDaysAgo'.........

Add target="_blank" in CSS

There are a few ways CSS can 'target' navigation. This will style internal and external links using attribute styling, which could help signal visitors to what your links will do.

a[href="#"] { color: forestgreen; font-weight: normal; }
a[href="http"] { color: dodgerblue; font-weight: normal; }  

You can also target the traditional inline HTML 'target=_blank'.

a[target=_blank] { font-weight: bold; } 

Also :target selector to style navigation block and element targets.

nav { display: none; }
nav:target { display: block; }  

CSS :target pseudo-class selector is supported - caniuse, w3schools, MDN.

a[href="http"] { target: new; target-name: new; target-new: tab; }

CSS/CSS3 'target-new' property etc, not supported by any major browsers, 2017 August, though it is part of the W3 spec since 2004 February.

W3Schools 'modal' construction, uses ':target' pseudo-class that could contain WP navigation. You can also add HTML rel="noreferrer and noopener beside target="_blank" to improve 'new tab' performance. CSS will not open links in tabs for now, but this page explains how to do that with jQuery (compatibility may depend for WP coders). MDN has a good review at Using the :target pseudo-class in selectors

Possible reason for NGINX 499 error codes

This doesn't answer the OPs question, but since I ended up here after searching furiously for an answer, I wanted to share what we discovered.

In our case, it turns out these 499s are expected. When users use the type-ahead feature in some search boxes, for example, we see something like this in the logs.

GET /api/search?q=h [Status 499] 
GET /api/search?q=he [Status 499]
GET /api/search?q=hel [Status 499]
GET /api/search?q=hell [Status 499]
GET /api/search?q=hello [Status 200]

So in our case I think its safe to use proxy_ignore_client_abort on which was suggested in a previous answer. Thanks for that!

How to check for file lock?

Here's a variation of DixonD's code that adds number of seconds to wait for file to unlock, and try again:

public bool IsFileLocked(string filePath, int secondsToWait)
{
    bool isLocked = true;
    int i = 0;

    while (isLocked &&  ((i < secondsToWait) || (secondsToWait == 0)))
    {
        try
        {
            using (File.Open(filePath, FileMode.Open)) { }
            return false;
        }
        catch (IOException e)
        {
            var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);
            isLocked = errorCode == 32 || errorCode == 33;
            i++;

            if (secondsToWait !=0)
                new System.Threading.ManualResetEvent(false).WaitOne(1000);
        }
    }

    return isLocked;
}


if (!IsFileLocked(file, 10))
{
    ...
}
else
{
    throw new Exception(...);
}

iPhone - Grand Central Dispatch main thread

Dispatching a block to the main queue is usually done from a background queue to signal that some background processing has finished e.g.

- (void)doCalculation
{
    //you can use any string instead "com.mycompany.myqueue"
    dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mycompany.myqueue", 0);

    dispatch_async(backgroundQueue, ^{
        int result = <some really long calculation that takes seconds to complete>;

        dispatch_async(dispatch_get_main_queue(), ^{
            [self updateMyUIWithResult:result];
        });    
    });
}

In this case, we are doing a lengthy calculation on a background queue and need to update our UI when the calculation is complete. Updating UI normally has to be done from the main queue so we 'signal' back to the main queue using a second nested dispatch_async.

There are probably other examples where you might want to dispatch back to the main queue but it is generally done in this way i.e. nested from within a block dispatched to a background queue.

  • background processing finished -> update UI
  • chunk of data processed on background queue -> signal main queue to start next chunk
  • incoming network data on background queue -> signal main queue that message has arrived
  • etc etc

As to why you might want to dispatch to the main queue from the main queue... Well, you generally wouldn't although conceivably you might do it to schedule some work to do the next time around the run loop.

Is there a Java equivalent or methodology for the typedef keyword in C++?

As noted in other answers, you should avoid the pseudo-typedef antipattern. However, typedefs are still useful even if that is not the way to achieve them. You want to distinguish between different abstract types that have the same Java representation. You don't want to mix up strings that are passwords with those that are street addresses, or integers that represent an offset with those with those that represent an absolute value.

The Checker Framework enables you to define a typedef in a backward-compatible way. I works even for primitive classes such as int and final classes such as String. It has no run-time overhead and does not break equality tests.

Section Type aliases and typedefs in the Checker Framework manual describes several ways to create typedefs, depending on your needs.

Add leading zeroes to number in Java?

String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)

In your case it will be:

String formatted = String.format("%03d", num);
  • 0 - to pad with zeros
  • 3 - to set width to 3

"Cloning" row or column vectors

Use numpy.tile:

>>> tile(array([1,2,3]), (3, 1))
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

or for repeating columns:

>>> tile(array([[1,2,3]]).transpose(), (1, 3))
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])

Why does my favicon not show up?

Try adding the profile attribute to your head tag and use "image/x-icon" for the type attribute:

<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="img/favicon.ico">

If the above code doesn't work, try using the full icon path for the href attribute:

<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="http://example.com/img/favicon.ico">

Java Enum return Int

Do you want to this code?

public static enum FieldIndex {
    HDB_TRX_ID,     //TRX ID
    HDB_SYS_ID      //SYSTEM ID
}

public String print(ArrayList<String> itemName){
    return itemName.get(FieldIndex.HDB_TRX_ID.ordinal());
}

Java: String - add character n-times

To have an idea of the speed penalty, I have tested two versions, one with Array.fill and one with StringBuilder.

public static String repeat(char what, int howmany) {
    char[] chars = new char[howmany];
    Arrays.fill(chars, what);
    return new String(chars);
}

and

public static String repeatSB(char what, int howmany) {
    StringBuilder out = new StringBuilder(howmany);
    for (int i = 0; i < howmany; i++)
        out.append(what);
    return out.toString();
}

using

public static void main(String... args) {
    String res;
    long time;

    for (int j = 0; j < 1000; j++) {
        res = repeat(' ', 100000);
        res = repeatSB(' ', 100000);
    }
    time = System.nanoTime();
    res = repeat(' ', 100000);
    time = System.nanoTime() - time;
    System.out.println("elapsed repeat: " + time);

    time = System.nanoTime();
    res = repeatSB(' ', 100000);
    time = System.nanoTime() - time;
    System.out.println("elapsed repeatSB: " + time);
}

(note the loop in main function is to kick in JIT)

The results are as follows:

elapsed repeat: 65899
elapsed repeatSB: 305171

It is a huge difference

identifier "string" undefined?

Perhaps you wanted to #include<string>, not <string.h>. std::string also needs a namespace qualification, or an explicit using directive.

An "and" operator for an "if" statement in Bash

Try this:

if [ ${STATUS} -ne 100 -a "${STRING}" = "${VALUE}" ]

or

if [ ${STATUS} -ne 100 ] && [ "${STRING}" = "${VALUE}" ]

MySQL: selecting rows where a column is null

There's also a <=> operator:

SELECT pid FROM planets WHERE userid <=> NULL

Would work. The nice thing is that <=> can also be used with non-NULL values:

SELECT NULL <=> NULL yields 1.

SELECT 42 <=> 42 yields 1 as well.

See here: https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#operator_equal-to

Optimistic vs. Pessimistic locking

One use case for optimistic locking is to have your application use the database to allow one of your threads / hosts to 'claim' a task. This is a technique that has come in handy for me on a regular basis.

The best example I can think of is for a task queue implemented using a database, with multiple threads claiming tasks concurrently. If a task has status 'Available', 'Claimed', 'Completed', a db query can say something like "Set status='Claimed' where status='Available'. If multiple threads try to change the status in this way, all but the first thread will fail because of dirty data.

Note that this is a use case involving only optimistic locking. So as an alternative to saying "Optimistic locking is used when you don't expect many collisions", it can also be used where you expect collisions but want exactly one transaction to succeed.

Can't push to GitHub because of large file which I already deleted

this worked for me. documentation from github Squashing Git Commits git reset origin/master

git checkout master && git pull;
git merge feature_branch;
git add . --all;
git commit -m "your commit message"

find documentation here

What should I do when 'svn cleanup' fails?

I just had this same problem on Windows 7 64-bit. I ran console as administrator and deleted the .svn directory from the problem directory (got an error about logs or something, but ignored it). Then, in explorer, I deleted the problem directory which was no longer showing as under version control. Then, I ran an update and things proceeded as expected.

Can I apply the required attribute to <select> fields in HTML5?

The <select> element does support the required attribute, as per the spec:

Which browser doesn’t honour this?

(Of course, you have to validate on the server anyway, as you can’t guarantee that users will have JavaScript enabled.)

Extract a substring using PowerShell

The -match operator tests a regex, combine it with the magic variable $matches to get your result

PS C:\> $x = "----start----Hello World----end----"
PS C:\> $x -match "----start----(?<content>.*)----end----"
True
PS C:\> $matches['content']
Hello World

Whenever in doubt about regex-y things, check out this site: http://www.regular-expressions.info

How can I call a WordPress shortcode within a template?

Try this:

<?php 
/*
Template Name: [contact us]

*/
get_header();
echo do_shortcode('[CONTACT-US-FORM]'); 
?>

How do you run a crontab in Cygwin on Windows?

You need to also install cygrunsrv so you can set cron up as a windows service, then run cron-config.

If you want the cron jobs to send email of any output you'll also need to install either exim or ssmtp (before running cron-config.)

See /usr/share/doc/Cygwin/cron-*.README for more details.

Regarding programs without a .exe extension, they are probably shell scripts of some type. If you look at the first line of the file you could see what program you need to use to run them (e.g., "#!/bin/sh"), so you could perhaps execute them from the windows scheduler by calling the shell program (e.g., "C:\cygwin\bin\sh.exe -l /my/cygwin/path/to/prog".)

Android Activity as a dialog

To start activity as dialog I defined it like this in AndroidManifest.xml:

<activity android:theme="@android:style/Theme.Dialog" />

Use this property inside your activity tag to avoid that your Dialog appears in the recently used apps list

android:excludeFromRecents="true"

If you want to stop your dialog / activity from being destroyed when the user clicks outside of the dialog:

After setContentView() in your Activity use:

this.setFinishOnTouchOutside(false);

Now when I call startActivity() it displays as a dialog, with the previous activity shown when the user presses the back button.

Note that if you are using ActionBarActivity (or AppCompat theme), you'll need to use @style/Theme.AppCompat.Dialog instead.

How to override toString() properly in Java?

Well actually you will need to return something like this because toString has to return a string

public String toString() {
 return "Name :" + this.name + "whatever :" + this.whatever + "";
}

and you actually do something wrong in the constructer you set the variable the user set to the name while you need to do the opposite. What you shouldn't do

n = this.name

What you should do

this.name = n

Hopes this helps thanks

Java: Calculating the angle between two points in degrees

I started with johncarls solution, but needed to adjust it to get exactly what I needed. Mainly, I needed it to rotate clockwise when the angle increased. I also needed 0 degrees to point NORTH. His solution got me close, but I decided to post my solution as well in case it helps anyone else.

I've added some additional comments to help explain my understanding of the function in case you need to make simple modifications.

/**
 * Calculates the angle from centerPt to targetPt in degrees.
 * The return should range from [0,360), rotating CLOCKWISE, 
 * 0 and 360 degrees represents NORTH,
 * 90 degrees represents EAST, etc...
 *
 * Assumes all points are in the same coordinate space.  If they are not, 
 * you will need to call SwingUtilities.convertPointToScreen or equivalent 
 * on all arguments before passing them  to this function.
 *
 * @param centerPt   Point we are rotating around.
 * @param targetPt   Point we want to calcuate the angle to.  
 * @return angle in degrees.  This is the angle from centerPt to targetPt.
 */
public static double calcRotationAngleInDegrees(Point centerPt, Point targetPt)
{
    // calculate the angle theta from the deltaY and deltaX values
    // (atan2 returns radians values from [-PI,PI])
    // 0 currently points EAST.  
    // NOTE: By preserving Y and X param order to atan2,  we are expecting 
    // a CLOCKWISE angle direction.  
    double theta = Math.atan2(targetPt.y - centerPt.y, targetPt.x - centerPt.x);

    // rotate the theta angle clockwise by 90 degrees 
    // (this makes 0 point NORTH)
    // NOTE: adding to an angle rotates it clockwise.  
    // subtracting would rotate it counter-clockwise
    theta += Math.PI/2.0;

    // convert from radians to degrees
    // this will give you an angle from [0->270],[-180,0]
    double angle = Math.toDegrees(theta);

    // convert to positive range [0-360)
    // since we want to prevent negative angles, adjust them now.
    // we can assume that atan2 will not return a negative value
    // greater than one partial rotation
    if (angle < 0) {
        angle += 360;
    }

    return angle;
}

Regular expressions inside SQL Server

SQL Wildcards are enough for this purpose. Follow this link: http://www.w3schools.com/SQL/sql_wildcards.asp

you need to use a query like this:

select * from mytable where msisdn like '%7%'

or

select * from mytable where msisdn like '56655%'

Socket transport "ssl" in PHP not enabled

I also ran into this issue just now while messing with laravel.

I am using wampserver for windows and had to copy the /bin/apache/apacheversion/bin/php.ini file to /bin/php/phpversion/php.ini

Reading Excel files from C#

I did a lot of reading from Excel files in C# a while ago, and we used two approaches:

  • The COM API, where you access Excel's objects directly and manipulate them through methods and properties
  • The ODBC driver that allows to use Excel like a database.

The latter approach was much faster: reading a big table with 20 columns and 200 lines would take 30 seconds via COM, and half a second via ODBC. So I would recommend the database approach if all you need is the data.

Cheers,

Carl

How to merge a specific commit in Git

The leading answers describe how to apply the changes from a specific commit to the current branch. If that's what you mean by "how to merge," then just use cherry-pick as they suggest.

But if you actually want a merge, i.e. you want a new commit with two parents -- the existing commit on the current branch, and the commit you wanted to apply changes from -- then a cherry-pick will not accomplish that.

Having true merge history may be desirable, for example, if your build process takes advantage of git ancestry to automatically set version strings based on the latest tag (using git describe).

Instead of cherry-pick, you can do an actual git merge --no-commit, and then manually adjust the index to remove any changes you don't want.

Suppose you're on branch A and you want to merge the commit at the tip of branch B:

git checkout A
git merge --no-commit B

Now you're set up to create a commit with two parents, the current tip commits of A and B. However you may have more changes applied than you want, including changes from earlier commits on the B branch. You need to undo these unwanted changes, then commit.

(There may be an easy way to set the state of the working directory and the index back to way it was before the merge, so that you have a clean slate onto which to cherry-pick the commit you wanted in the first place. But I don't know how to achieve that clean slate. git checkout HEAD and git reset HEAD will both remove the merge state, defeating the purpose of this method.)

So manually undo the unwanted changes. For example, you could

git revert --no-commit 012ea56

for each unwanted commit 012ea56.

When you're finished adjusting things, create your commit:

git commit -m "Merge in commit 823749a from B which tweaked the timeout code"

Now you have only the change you wanted, and the ancestry tree shows that you technically merged from B.

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

How about using Xcode built-in code snippet library?

enter image description here

Update for Swift:

Many up votes inspired me to update this answer.

The build-in Xcode code snippet library has dispatch_after for only objective-c language. People can also create their own Custom Code Snippet for Swift.

Write this in Xcode.

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(<#delayInSeconds#> * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
        <#code to be executed after a specified delay#>
    })

Drag this code and drop it in the code snippet library area. enter image description here

Bottom of the code snippet list, there will be a new entity named My Code Snippet. Edit this for a title. For suggestion as you type in the Xcode fill in the Completion Shortcut.

For more info see CreatingaCustomCodeSnippet.

Update Swift 3

Drag this code and drop it in the code snippet library area.

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(<#delayInSeconds#>)) {
    <#code to be executed after a specified delay#>
}

new DateTime() vs default(DateTime)

The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min

Therefore there is no difference between default(DateTime) and new DateTime() and DateTime.Min

Java Delegates?

It doesn't have an explicit delegate keyword as C#, but you can achieve similar in Java 8 by using a functional interface (i.e. any interface with exactly one method) and lambda:

private interface SingleFunc {
    void printMe();
}

public static void main(String[] args) {
    SingleFunc sf = () -> {
        System.out.println("Hello, I am a simple single func.");
    };
    SingleFunc sfComplex = () -> {
        System.out.println("Hello, I am a COMPLEX single func.");
    };
    delegate(sf);
    delegate(sfComplex);
}

private static void delegate(SingleFunc f) {
    f.printMe();
}

Every new object of type SingleFunc must implement printMe(), so it is safe to pass it to another method (e.g. delegate(SingleFunc)) to call the printMe() method.

How can you strip non-ASCII characters from a string? (in C#)

I found the following slightly altered range useful for parsing comment blocks out of a database, this means that you won't have to contend with tab and escape characters which would cause a CSV field to become upset.

parsememo = Regex.Replace(parsememo, @"[^\u001F-\u007F]", string.Empty);

If you want to avoid other special characters or particular punctuation check the ascii table

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

Breaking Changes to LocalDB: Applies to SQL 2014; take a look over this article and try to use (localdb)\mssqllocaldb as server name to connect to the LocalDB automatic instance, for example:

<connectionStrings>
  <add name="ProductsContext" connectionString="Data Source=(localdb)\mssqllocaldb; 
  ...

The article also mentions the use of 2012 SSMS to connect to the 2014 LocalDB. Which leads me to believe that you might have multiple versions of SQL installed - which leads me to point out this SO answer that suggests changing the default name of your LocalDB "instance" to avoid other version mismatch issues that might arise going forward; mentioned not as source of issue, but to raise awareness of potential clashes that multiple SQL version installed on a single dev machine might lead to ... and something to get in the habit of in order to avoid some.

Another thing worth mentioning - if you've gotten your instance in an unusable state due to tinkering with it to try and fix this problem, then it might be worth starting over - uninstall, reinstall - then try using the mssqllocaldb value instead of v12.0 and see if that corrects your issue.

How to execute two mysql queries as one in PHP/MYSQL?

As others have answered, the mysqli API can execute multi-queries with the msyqli_multi_query() function.

For what it's worth, PDO supports multi-query by default, and you can iterate over the multiple result sets of your multiple queries:

$stmt = $dbh->prepare("
    select sql_calc_found_rows * from foo limit 1 ; 
    select found_rows()");
$stmt->execute();
do {
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
} while ($stmt->nextRowset());

However, multi-query is pretty widely considered a bad idea for security reasons. If you aren't careful about how you construct your query strings, you can actually get the exact type of SQL injection vulnerability shown in the classic "Little Bobby Tables" XKCD cartoon. When using an API that restrict you to single-query, that can't happen.

How do I fix this "TypeError: 'str' object is not callable" error?

this part :

"Your new price is: $"(float(price)

asks python to call this string:

"Your new price is: $"

just like you would a function: function( some_args) which will ALWAYS trigger the error:

TypeError: 'str' object is not callable

Is there Java HashMap equivalent in PHP?

Arrays in PHP can have Key Value structure.

ReactJS: "Uncaught SyntaxError: Unexpected token <"

If you have something like

Uncaught SyntaxError: embedded: Unexpected token

You probably missed a comma in a place like this:

  var CommentForm = React.createClass({
  getInitialState: function() {
      return {author: '', text: ''};

  }, // <---- DON'T FORGET THE COMMA

  render: function() {
      return (
      <form className="commentForm">
          <input type="text" placeholder="Nombre" />
          <input type="text" placeholder="Qué opina" />
          <input type="submit" value="Publicar" />
      </form>
      )
  }
  });

How do I change db schema to dbo

ms-help://MS.SQLCC.v9/MS.SQLSVR.v9.en/tsqlref9/html/0a760138-460e-410a-a3c1-d60af03bf2ed.htm

ALTER SCHEMA schema_name TRANSFER securable_name

How do you use script variables in psql?

I've found this question and the answers extremely useful, but also confusing. I had lots of trouble getting quoted variables to work, so here is the way I got it working:

\set deployment_user username    -- username
\set deployment_pass '\'string_password\''
ALTER USER :deployment_user WITH PASSWORD :deployment_pass;

This way you can define the variable in one statement. When you use it, single quotes will be embedded into the variable.

NOTE! When I put a comment after the quoted variable it got sucked in as part of the variable when I tried some of the methods in other answers. That was really screwing me up for a while. With this method comments appear to be treated as you'd expect.

Mod in Java produces negative numbers

If the modulus is a power of 2 then you can use a bitmask:

int i = -1 & ~-2; // -1 MOD 2 is 1

By comparison the Pascal language provides two operators; REM takes the sign of the numerator (x REM y is x - (x DIV y) * y where x DIV y is TRUNC(x / y)) and MOD requires a positive denominator and returns a positive result.

Git: How to squash all commits on branch

Solution for people who prefer clicking:

  1. Install sourcetree (it is free)

  2. Check how your commits look like. Most likely you have something similar to this enter image description here

  3. Right click on parent commit. In our case it is master branch.

enter image description here

  1. You can squash commit with previous one by clicking a button. In our case we have to click 2 times. You can also change commit message enter image description here

  2. Results are awesome and we are ready to push! enter image description here

Side note: If you were pushing your partial commits to remote you have to use force push after squash

java.io.IOException: Broken pipe

I agree with @arcy, the problem is on client side, on my case it was because of nginx, let me elaborate I am using nginx as the frontend (so I can distribute load, ssl, etc ...) and using proxy_pass http://127.0.0.1:8080 to forward the appropiate requests to tomcat.

There is a default value for the nginx variable proxy_read_timeout of 60s that should be enough, but on some peak moments my setup would error with the java.io.IOException: Broken pipe changing the value will help until the root cause (60s should be enough) can be fixed.

NOTE: I made a new answer so I could expand a bit more with my case (it was the only mention I found about this error on internet after looking quite a lot)

How to run cron job every 2 hours

The line should read either:

0 0-23/2 * * * /home/username/test.sh

or

0 0,2,4,6,8,10,12,14,16,18,20,22 * * * /home/username/test.sh

Mosaic Grid gallery with dynamic sized images

I think you can try "Google Grid Gallery", it based on aforementioned Masonry with some additions, like styles and viewer.

Get JSON object from URL

You could use PHP's json_decode function:

$url = "http://urlToYourJsonFile.com";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "My token: ". $json_data["access_token"];

Converting std::__cxx11::string to std::string

If you can recompile all incompatible libs you use, do it with compiler option

-D_GLIBCXX_USE_CXX11_ABI=1

and then rebuild your project. If you can't do so, add to your project's makefile compiler option

-D_GLIBCXX_USE_CXX11_ABI=0

The define

#define _GLIBCXX_USE_CXX11_ABI 0/1

is also good but you probably need to add it to all your files while compiler option do it for all files at once.

How can I access and process nested objects, arrays or JSON?

You can use the syntax jsonObject.key to access the the value. And if you want access a value from an array, then you can use the syntax jsonObjectArray[index].key.

Here are the code examples to access various values to give you the idea.

_x000D_
_x000D_
        var data = {_x000D_
            code: 42,_x000D_
            items: [{_x000D_
                id: 1,_x000D_
                name: 'foo'_x000D_
            }, {_x000D_
                id: 2,_x000D_
                name: 'bar'_x000D_
            }]_x000D_
        };_x000D_
_x000D_
        // if you want 'bar'_x000D_
        console.log(data.items[1].name);_x000D_
_x000D_
        // if you want array of item names_x000D_
        console.log(data.items.map(x => x.name));_x000D_
_x000D_
        // get the id of the item where name = 'bar'_x000D_
        console.log(data.items.filter(x => (x.name == "bar") ? x.id : null)[0].id);
_x000D_
_x000D_
_x000D_

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

Your Button2Click and Button3Click functions pass klad.xls and smimime.txt. These files most likely aren't actual executables indeed.

In order to open arbitrary files using the application associated with them, use ShellExecute

How to dynamically create CSS class in JavaScript and apply?

function createCSSClass(selector, style, hoverstyle) 
{
    if (!document.styleSheets) 
    {
        return;
    }

    if (document.getElementsByTagName("head").length == 0) 
    {

        return;
    }
    var stylesheet;
    var mediaType;
    if (document.styleSheets.length > 0) 
    {
        for (i = 0; i < document.styleSheets.length; i++) 
        {
            if (document.styleSheets[i].disabled) 
            {
                continue;
            }
            var media = document.styleSheets[i].media;
            mediaType = typeof media;

            if (mediaType == "string") 
            {
                if (media == "" || (media.indexOf("screen") != -1)) 
                {
                    styleSheet = document.styleSheets[i];
                }
            } 
            else if (mediaType == "object") 
            {
                if (media.mediaText == "" || (media.mediaText.indexOf("screen") != -1)) 
                {
                    styleSheet = document.styleSheets[i];
                }
            }

            if (typeof styleSheet != "undefined") 
            {
                break;
            }
        }
    }

    if (typeof styleSheet == "undefined") {
        var styleSheetElement = document.createElement("style");
        styleSheetElement.type = "text/css";
        document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
        for (i = 0; i < document.styleSheets.length; i++) {
            if (document.styleSheets[i].disabled) {
                continue;
            }
            styleSheet = document.styleSheets[i];
        }

        var media = styleSheet.media;
        mediaType = typeof media;
    }

    if (mediaType == "string") {
        for (i = 0; i < styleSheet.rules.length; i++) 
        {
            if (styleSheet.rules[i].selectorText.toLowerCase() == selector.toLowerCase()) 
            {
                styleSheet.rules[i].style.cssText = style;
                return;
            }
        }

        styleSheet.addRule(selector, style);
    }
    else if (mediaType == "object") 
    {
        for (i = 0; i < styleSheet.cssRules.length; i++) 
        {
            if (styleSheet.cssRules[i].selectorText.toLowerCase() == selector.toLowerCase()) 
            {
                styleSheet.cssRules[i].style.cssText = style;
                return;
            }
        }

        if (hoverstyle != null) 
        {
            styleSheet.insertRule(selector + "{" + style + "}", 0);
            styleSheet.insertRule(selector + ":hover{" + hoverstyle + "}", 1);
        }
        else 
        {
            styleSheet.insertRule(selector + "{" + style + "}", 0);
        }
    }
}





createCSSClass(".modalPopup  .header",
                                 " background-color: " + lightest + ";" +
                                  "height: 10%;" +
                                  "color: White;" +
                                  "line-height: 30px;" +
                                  "text-align: center;" +
                                  " width: 100%;" +
                                  "font-weight: bold; ", null);

JS. How to replace html element with another element/text, represented in string?

Because you are talking about your replacement being anything, and also replacing in the middle of an element's children, it becomes more tricky than just inserting a singular element, or directly removing and appending:

function replaceTargetWith( targetID, html ){
  /// find our target
  var i, tmp, elm, last, target = document.getElementById(targetID);
  /// create a temporary div or tr (to support tds)
  tmp = document.createElement(html.indexOf('<td')!=-1?'tr':'div'));
  /// fill that div with our html, this generates our children
  tmp.innerHTML = html;
  /// step through the temporary div's children and insertBefore our target
  i = tmp.childNodes.length;
  /// the insertBefore method was more complicated than I first thought so I 
  /// have improved it. Have to be careful when dealing with child lists as  
  /// they are counted as live lists and so will update as and when you make
  /// changes. This is why it is best to work backwards when moving children 
  /// around, and why I'm assigning the elements I'm working with to `elm` 
  /// and `last`
  last = target;
  while(i--){
    target.parentNode.insertBefore((elm = tmp.childNodes[i]), last);
    last = elm;
  }
  /// remove the target.
  target.parentNode.removeChild(target);
}

example usage:

replaceTargetWith( 'idTABLE', 'I <b>can</b> be <div>anything</div>' );

demo:

By using the .innerHTML of our temporary div this will generate the TextNodes and Elements we need to insert without any hard work. But rather than insert the temporary div itself -- this would give us mark up that we don't want -- we can just scan and insert it's children.

...either that or look to using jQuery and it's replaceWith method.

jQuery('#idTABLE').replaceWith('<blink>Why this tag??</blink>');


update 2012/11/15

As a response to EL 2002's comment above:

It not always possible. For example, when createElement('div') and set its innerHTML as <td>123</td>, this div becomes <div>123</div> (js throws away inappropriate td tag)

The above problem obviously negates my solution as well - I have updated my code above accordingly (at least for the td issue). However for certain HTML this will occur no matter what you do. All user agents interpret HTML via their own parsing rules, but nearly all of them will attempt to auto-correct bad HTML. The only way to achieve exactly what you are talking about (in some of your examples) is to take the HTML out of the DOM entirely, and manipulate it as a string. This will be the only way to achieve a markup string with the following (jQuery will not get around this issue either):

<table><tr>123 text<td>END</td></tr></table>

If you then take this string an inject it into the DOM, depending on the browser you will get the following:

123 text<table><tr><td>END</td></tr></table>

<table><tr><td>END</td></tr></table>

The only question that remains is why you would want to achieve broken HTML in the first place? :)

What is a good regular expression to match a URL?

(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})

Will match the following cases

  • http://www.foufos.gr
  • https://www.foufos.gr
  • http://foufos.gr
  • http://www.foufos.gr/kino
  • http://werer.gr
  • www.foufos.gr
  • www.mp3.com
  • www.t.co
  • http://t.co
  • http://www.t.co
  • https://www.t.co
  • www.aa.com
  • http://aa.com
  • http://www.aa.com
  • https://www.aa.com

Will NOT match the following

  • www.foufos
  • www.foufos-.gr
  • www.-foufos.gr
  • foufos.gr
  • http://www.foufos
  • http://foufos
  • www.mp3#.com

_x000D_
_x000D_
var expression = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi;_x000D_
var regex = new RegExp(expression);_x000D_
_x000D_
var check = [_x000D_
  'http://www.foufos.gr',_x000D_
  'https://www.foufos.gr',_x000D_
  'http://foufos.gr',_x000D_
  'http://www.foufos.gr/kino',_x000D_
  'http://werer.gr',_x000D_
  'www.foufos.gr',_x000D_
  'www.mp3.com',_x000D_
  'www.t.co',_x000D_
  'http://t.co',_x000D_
  'http://www.t.co',_x000D_
  'https://www.t.co',_x000D_
  'www.aa.com',_x000D_
  'http://aa.com',_x000D_
  'http://www.aa.com',_x000D_
  'https://www.aa.com',_x000D_
  'www.foufos',_x000D_
  'www.foufos-.gr',_x000D_
  'www.-foufos.gr',_x000D_
  'foufos.gr',_x000D_
  'http://www.foufos',_x000D_
  'http://foufos',_x000D_
  'www.mp3#.com'_x000D_
];_x000D_
_x000D_
check.forEach(function(entry) {_x000D_
  if (entry.match(regex)) {_x000D_
    $("#output").append( "<div >Success: " + entry + "</div>" );_x000D_
  } else {_x000D_
    $("#output").append( "<div>Fail: " + entry + "</div>" );_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Check it in rubular - NEW version

Check it in rubular - old version

How to display HTML in TextView?

If you are trying to show HTML from a string resource id, the formatting may not show up on screen. If that is happening to you, try using CDATA tags instead:

strings.xml:
<string name="sample_string"><![CDATA[<h2>Title</h2><br><p>Description here</p>]]></string>

...

MainActivity.java:
text.setText(Html.fromHtml(getString(R.string.sample_string));

See this post for further details.

Get file path of image on Android

I am doing this on click of Button.

private static final int CAMERA_PIC_REQUEST = 1;

private View.OnClickListener  OpenCamera=new View.OnClickListener() {

            @Override
            public void onClick(View paramView) {
                // TODO Auto-generated method stub

                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

                NewSelectedImageURL=null;
                //outfile where we are thinking of saving it
                Date date = new Date();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

                String newPicFile = RecipeName+ df.format(date) + ".png";


                String outPath =Environment.getExternalStorageDirectory() + "/myFolderName/"+ newPicFile ;
                File outFile = new File(outPath);               

                CapturedImageURL=outFile.toString();
                Uri outuri = Uri.fromFile(outFile);
                cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, outuri);            
                startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);  

            }
        };

You can get the URL of the recently Captured Image from variable CapturedImageURL

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  


    //////////////////////////////////////
    if (requestCode == CAMERA_PIC_REQUEST) {  
        // do something  

         if (resultCode == RESULT_OK) 
         {
             Uri uri = null;

             if (data != null) 
             {
                 uri = data.getData();
             }
             if (uri == null && CapturedImageURL != null) 
             {
                 uri = Uri.fromFile(new File(CapturedImageURL));
             }
             File file = new File(CapturedImageURL);
             if (!file.exists()) {
                file.mkdir();
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+Environment.getExternalStorageDirectory())));
            }




         }


    }

How to position the Button exactly in CSS

So, the trick here is to use absolute positioning calc like this:

top: calc(50% - XYpx);
left: calc(50% - XYpx);

where XYpx is half the size of your image, in my case, the image was a square. Of course, in this now obsolete case, the image must also change its size proportionally in response to window resize to be able to remain at the center without looking out of proportion.

What are OLTP and OLAP. What is the difference between them?

The difference is quite simple:

OLTP (Online Transaction Processing)

OLTP is a class of information systems that facilitate and manage transaction-oriented applications. OLTP has also been used to refer to processing in which the system responds immediately to user requests. Online transaction processing applications are high throughput and insert or update-intensive in database management. Some examples of OLTP systems include order entry, retail sales, and financial transaction systems.

OLAP (Online Analytical Processing)

OLAP is part of the broader category of business intelligence, which also encompasses relational database, report writing and data mining. Typical applications of OLAP include business reporting for sales, marketing, management reporting, business process management (BPM), budgeting and forecasting, financial reporting and similar areas.

See more details OLTP and OLAP

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

Most certainly, export JAVA_HOME=/usr/bin/java is the culprit. This env var should point to the JDK or JRE installation directory. Googling shows that the best option for MacOS X seems to be export JAVA_HOME=/Library/Java/Home.

How do you read CSS rule values with JavaScript?

SOLUTION 1 (CROSS-BROWSER)

function GetProperty(classOrId,property)
{ 
    var FirstChar = classOrId.charAt(0);  var Remaining= classOrId.substring(1);
    var elem = (FirstChar =='#') ?  document.getElementById(Remaining) : document.getElementsByClassName(Remaining)[0];
    return window.getComputedStyle(elem,null).getPropertyValue(property);
}

alert( GetProperty(".my_site_title","position") ) ;

SOLUTION 2 (CROSS-BROWSER)

function GetStyle(CLASSname) 
{
    var styleSheets = document.styleSheets;
    var styleSheetsLength = styleSheets.length;
    for(var i = 0; i < styleSheetsLength; i++){
        if (styleSheets[i].rules ) { var classes = styleSheets[i].rules; }
        else { 
            try {  if(!styleSheets[i].cssRules) {continue;} } 
            //Note that SecurityError exception is specific to Firefox.
            catch(e) { if(e.name == 'SecurityError') { console.log("SecurityError. Cant readd: "+ styleSheets[i].href);  continue; }}
            var classes = styleSheets[i].cssRules ;
        }
        for (var x = 0; x < classes.length; x++) {
            if (classes[x].selectorText == CLASSname) {
                var ret = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText ;
                if(ret.indexOf(classes[x].selectorText) == -1){ret = classes[x].selectorText + "{" + ret + "}";}
                return ret;
            }
        }
    }
}

alert( GetStyle('.my_site_title') );

auto refresh for every 5 mins

Install an interval:

<script type="text/javascript">    
    setInterval(page_refresh, 5*60000); //NOTE: period is passed in milliseconds
</script>

Functions are not valid as a React child. This may happen if you return a Component instead of from render

it also happens when you call a function from jsx directly rather than in an event. like

it will show the error if you write like

<h1>{this.myFunc}<h2>

it will go if you write:

<h1 onClick={this.myFunc}>Hit Me</h1>

R not finding package even after package installation

Do .libPaths(), close every R runing, check in the first directory, remove the zoo package restart R and install zoo again. Of course you need to have sufficient rights.

Merging Cells in Excel using C#

You can use Microsoft.Office.Interop.Excel:

worksheet.Range[worksheet.Cells[rowNum, columnNum], worksheet.Cells[rowNum, columnNum]].Merge();

You can also use NPOI:

var cellsTomerge = new NPOI.SS.Util.CellRangeAddress(firstrow, lastrow, firstcol, lastcol);
_sheet.AddMergedRegion(cellsTomerge);

How to manually include external aar package using new Gradle Android Build System

I tried all solution here but none is working, then I realise I made a mistake, I put the .aar in wrong folder, as you can see below, I thought I should put in root folder, so I created a libs folder there (1 in picture), but inside the app folder, there is already a libs, you should put in second libs, hope this help those who has same issue as mine:

enter image description here

When can I use a forward declaration?

The main rule is that you can only forward-declare classes whose memory layout (and thus member functions and data members) do not need to be known in the file you forward-declare it.

This would rule out base classes and anything but classes used via references and pointers.

How can I format DateTime to web UTC format?

string foo = yourDateTime.ToUniversalTime()
                         .ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");

How can I capture the right-click event in JavaScript?

Use the oncontextmenu event.

Here's an example:

<div oncontextmenu="javascript:alert('success!');return false;">
    Lorem Ipsum
</div>

And using event listeners (credit to rampion from a comment in 2011):

el.addEventListener('contextmenu', function(ev) {
    ev.preventDefault();
    alert('success!');
    return false;
}, false);

Don't forget to return false, otherwise the standard context menu will still pop up.

If you are going to use a function you've written rather than javascript:alert("Success!"), remember to return false in BOTH the function AND the oncontextmenu attribute.

How to draw an overlay on a SurfaceView used by Camera on Android?

Try calling setWillNotDraw(false) from surfaceCreated:

public void surfaceCreated(SurfaceHolder holder) {
    try {
        setWillNotDraw(false); 
        mycam.setPreviewDisplay(holder);
        mycam.startPreview();
    } catch (Exception e) {
        e.printStackTrace();
        Log.d(TAG,"Surface not created");
    }
}

@Override
protected void onDraw(Canvas canvas) {

    canvas.drawRect(area, rectanglePaint);
    Log.w(this.getClass().getName(), "On Draw Called");
}

and calling invalidate from onTouchEvent:

public boolean onTouch(View v, MotionEvent event) {

    invalidate();
    return true;
}

Reading HTML content from a UIWebView

To read:-

NSString *html = [myWebView stringByEvaluatingJavaScriptFromString: @"document.getElementById('your div id').textContent"];
NSLog(html);    

To modify:-

html = [myWebView stringByEvaluatingJavaScriptFromString: @"document.getElementById('your div id').textContent=''"];

Set a div width, align div center and text align left

Try:

#your_div_id {
  width: 855px;
  margin:0 auto;
  text-align: center;
}

Running AngularJS initialization code when view is loaded

I use the following template in my projects:

angular.module("AppName.moduleName", [])

/**
 * @ngdoc controller
 * @name  AppName.moduleName:ControllerNameController
 * @description Describe what the controller is responsible for.
 **/
    .controller("ControllerNameController", function (dependencies) {

        /* type */ $scope.modelName = null;
        /* type */ $scope.modelName.modelProperty1 = null;
        /* type */ $scope.modelName.modelPropertyX = null;

        /* type */ var privateVariable1 = null;
        /* type */ var privateVariableX = null;

        (function init() {
            // load data, init scope, etc.
        })();

        $scope.modelName.publicFunction1 = function () /* -> type  */ {
            // ...
        };

        $scope.modelName.publicFunctionX = function () /* -> type  */ {
            // ...
        };

        function privateFunction1() /* -> type  */ {
            // ...
        }

        function privateFunctionX() /* -> type  */ {
            // ...
        }

    });

How to set username and password for SmtpClient object in .NET?

The SmtpClient can be used by code:

SmtpClient mailer = new SmtpClient();
mailer.Host = "mail.youroutgoingsmtpserver.com";
mailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");

How to horizontally center an unordered list of unknown width?

Try wrapping the list in a div and give that div the inline property instead of your list.

How do I get the base URL with PHP?

   $base_url="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"].'?').'/';

Usage:

print "<script src='{$base_url}js/jquery.min.js'/>";

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

You can use String.Format:

DateTime d = DateTime.Now;
string str = String.Format("{0:00}/{1:00}/{2:0000} {3:00}:{4:00}:{5:00}.{6:000}", d.Month, d.Day, d.Year, d.Hour, d.Minute, d.Second, d.Millisecond);
// I got this result: "02/23/2015 16:42:38.234"

How to JSON serialize sets?

If you only need to encode sets, not general Python objects, and want to keep it easily human-readable, a simplified version of Raymond Hettinger's answer can be used:

import json
import collections

class JSONSetEncoder(json.JSONEncoder):
    """Use with json.dumps to allow Python sets to be encoded to JSON

    Example
    -------

    import json

    data = dict(aset=set([1,2,3]))

    encoded = json.dumps(data, cls=JSONSetEncoder)
    decoded = json.loads(encoded, object_hook=json_as_python_set)
    assert data == decoded     # Should assert successfully

    Any object that is matched by isinstance(obj, collections.Set) will
    be encoded, but the decoded value will always be a normal Python set.

    """

    def default(self, obj):
        if isinstance(obj, collections.Set):
            return dict(_set_object=list(obj))
        else:
            return json.JSONEncoder.default(self, obj)

def json_as_python_set(dct):
    """Decode json {'_set_object': [1,2,3]} to set([1,2,3])

    Example
    -------
    decoded = json.loads(encoded, object_hook=json_as_python_set)

    Also see :class:`JSONSetEncoder`

    """
    if '_set_object' in dct:
        return set(dct['_set_object'])
    return dct

How to center absolute div horizontally using CSS?

You can't use margin:auto; on position:absolute; elements, just remove it if you don't need it, however, if you do, you could use left:30%; ((100%-40%)/2) and media queries for the max and min values:

.container {
    position: absolute;
    top: 15px;
    left: 30%;
    z-index: 2;
    width:40%;
    height: 60px;
    overflow: hidden;
    background: #fff;
}

@media all and (min-width:960px) {

    .container {
        left: 50%;
        margin-left:-480px;
        width: 960px;
    }

}

@media all and (max-width:600px) {

    .container {
        left: 50%;
        margin-left:-300px;
        width: 600px;
    }

}

Pytorch reshape tensor dimension

import torch
>>>a = torch.Tensor([1,2,3,4,5])
>>>a.size()
torch.Size([5])
#use view to reshape

>>>b = a.view(1,a.shape[0])
>>>b
tensor([[1., 2., 3., 4., 5.]])
>>>b.size()
torch.Size([1, 5])
>>>b.type()
'torch.FloatTensor'

How can I insert into a BLOB column from an insert statement in sqldeveloper?

  1. insert into mytable(id, myblob) values (1,EMPTY_BLOB);
  2. SELECT * FROM mytable mt where mt.id=1 for update
  3. Click on the Lock icon to unlock for editing
  4. Click on the ... next to the BLOB to edit
  5. Select the appropriate tab and click open on the top left.
  6. Click OK and commit the changes.

C compile : collect2: error: ld returned 1 exit status

I got this problem, and tried many ways to solve it. Finally, it turned out that make clean and make again solved it. The reason is: I got the source code together with object files compiled previously with an old gcc version. When my newer gcc version wants to link that old object files, it can't resolve some function in there. It happens to me several times that the source code distributors do not clean up before packing, so a make clean saved the day.

Export DataTable to Excel with Open Xml SDK in c#

I wanted to add this answer because I used the primary answer from this question as my basis for exporting from a datatable to Excel using OpenXML but then transitioned to OpenXMLWriter when I found it to be much faster than the above method.

You can find the full details in my answer in the link below. My code is in VB.NET though, so you'll have to convert it.

How to export DataTable to Excel

Git list of staged files

The best way to do this is by running the command:

git diff --name-only --cached

When you check the manual you will likely find the following:

--name-only
    Show only names of changed files.

And on the example part of the manual:

git diff --cached
    Changes between the index and your current HEAD.

Combined together you get the changes between the index and your current HEAD and Show only names of changed files.

Update: --staged is also available as an alias for --cached above in more recent git versions.

"End of script output before headers" error in Apache

Since no answer is accepted, I would like to provide one possible solution. If your script is written on Windows and uploaded to a Linux server(through FTP), then the problem will raise usually. The reason is that Windows uses CRLF to end each line while Linux uses LF. So you should convert it from CRLF to LF with the help of an editor, such Atom, as following enter image description here

Add new attribute (element) to JSON object using JavaScript

With ECMAScript since 2015 you can use Spread Syntax ( …three dots):

let  people = { id: 4 ,firstName: 'John'};
people = { ...people, secondName: 'Fogerty'};

It's allow you to add sub objects:

people = { ...people, city: { state: 'California' }};

the result would be:

{  
   "id": 4,
   "firstName": "John",
   "secondName": "Forget",
   "city": {  
      "state": "California"
   }
}

You also can merge objects:

var mergedObj = { ...obj1, ...obj2 };

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

Simply adding it to the root folder works after a fashion, but I've found that if I need to change the favicon, it can take days to update... even a cache refresh doesn't do the trick.

How can I create a dropdown menu from a List in Tkinter?

To create a "drop down menu" you can use OptionMenu in tkinter

Example of a basic OptionMenu:

from Tkinter import *

master = Tk()

variable = StringVar(master)
variable.set("one") # default value

w = OptionMenu(master, variable, "one", "two", "three")
w.pack()

mainloop()

More information (including the script above) can be found here.


Creating an OptionMenu of the months from a list would be as simple as:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

mainloop()

In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

def ok():
    print ("value is:" + variable.get())

button = Button(master, text="OK", command=ok)
button.pack()

mainloop()

I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.

What's the difference between django OneToOneField and ForeignKey?

The easiest way to draw a relationship between items is by understanding them in plain languages. Example

A user can have many cars but then a car can have just one owner. After establishing this, the foreign key should be used on the item with the many relationship. In this case the car. Meaning you'll include user as a foreign key in cars

And a one on one relationship is quite simple. Say a man and a heart. A man has only one heart and a heart can belong to just one man

What is a .pid file and what does it contain?

The pid files contains the process id (a number) of a given program. For example, Apache HTTPD may write its main process number to a pid file - which is a regular text file, nothing more than that - and later use the information there contained to stop itself. You can also use that information to kill the process yourself, using cat filename.pid | xargs kill

Read a plain text file with php

You can read a group of txt files in a folder and echo the contents like this.

 <?php
$directory = "folder/";
$dir = opendir($directory);
$filenames = [];
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if($type !== 'file') continue;
$filenames[] = $filename;
}
closedir($dir);
?>

How to make a transparent HTML button?

Setting its background image to none also works:

button {
    background-image: none;
}

How to compare two dates along with time in java

Since Date implements Comparable<Date>, it is as easy as:

date1.compareTo(date2);

As the Comparable contract stipulates, it will return a negative integer/zero/positive integer if date1 is considered less than/the same as/greater than date2 respectively (ie, before/same/after in this case).

Note that Date has also .after() and .before() methods which will return booleans instead.

Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?

The main problem is that the browser won't even send a request with a fragment part. The fragment part is resolved right there in the browser. So it's reachable through JavaScript.

Anyway, you could parse a URL into bits, including the fragment part, using parse_url(), but it's obviously not your case.

How to reset AUTO_INCREMENT in MySQL?

You can also use the syntax TRUNCATE table like this : TRUNCATE TABLE table_name

BEWARE!! TRUNCATE TABLE your_table will delete everything in your your_table!!

CSS list-style-image size

You might would like to try img tag instead of setting 'list-style-image' property. Setting width and height using css will actually crop the image. But if you use img tag, the image will be re-sized to value of width and height.

How to stop java process gracefully?

Thanks for you answers. Shutdown hooks seams like something that would work in my case. But I also bumped into the thing called Monitoring and Management beans:
http://java.sun.com/j2se/1.5.0/docs/guide/management/overview.html
That gives some nice possibilities, for remote monitoring, and manipulation of the java process. (Was introduced in Java 5)

docker container ssl certificates

Mount the certs onto the Docker container using -v:

docker run -v /host/path/to/certs:/container/path/to/certs -d IMAGE_ID "update-ca-certificates"

How to install JRE 1.7 on Mac OS X and use it with Eclipse?

The download from java.com which installs in /Library/Internet Plug-Ins is only the JRE, for development you probably want to download the JDK from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install that instead. This will install the JDK at /Library/Java/JavaVirtualMachines/jdk1.7.0_<something>.jdk/Contents/Home which you can then add to Eclipse via Preferences -> Java -> Installed JREs.

Date Difference in php on days?

strtotime will convert your date string to a unix time stamp. (seconds since the unix epoch.

$ts1 = strtotime($date1);
$ts2 = strtotime($date2);

$seconds_diff = $ts2 - $ts1;

Remove padding from columns in Bootstrap 3

I guess it's easier to just use

margin:-30px;

to override the original value set by bootstrap.

I've tried

margin: 0px -30px 0px -30px;

and it worked for me.

How to retrieve Key Alias and Key Password for signed APK in android studio(migrated from Eclipse)

If looking in the logs doesn't help, you can also try to brute-force the password - check method 3 on this post - Android KeyStore Password Recover.

This SO post has more answers as well.

Split / Explode a column of dictionaries into separate columns with pandas

>>> df

   Station ID                        Pollutants
0        8809  {"a": "46", "b": "3", "c": "12"}
1        8810   {"a": "36", "b": "5", "c": "8"}
2        8811              {"b": "2", "c": "7"}
3        8812                       {"c": "11"}
4        8813            {"a": "82", "c": "15"}

speed comparison for a large dataset of 10 million rows

>>> df = pd.concat([df]*100000).reset_index(drop=True)
>>> df = pd.concat([df]*20).reset_index(drop=True)
>>> print(df.shape)
(10000000, 2)
def apply_drop(df):
    return df.join(df['Pollutants'].apply(pd.Series)).drop('Pollutants', axis=1)  

def json_normalise_drop(df):
    return df.join(pd.json_normalize(df.Pollutants)).drop('Pollutants', axis=1)  

def tolist_drop(df):
    return df.join(pd.DataFrame(df['Pollutants'].tolist())).drop('Pollutants', axis=1)  

def vlues_tolist_drop(df):
    return df.join(pd.DataFrame(df['Pollutants'].values.tolist())).drop('Pollutants', axis=1)  

def pop_tolist(df):
    return df.join(pd.DataFrame(df.pop('Pollutants').tolist()))  

def pop_values_tolist(df):
    return df.join(pd.DataFrame(df.pop('Pollutants').values.tolist()))

>>> %timeit apply_drop(df.copy())
1 loop, best of 3: 53min 20s per loop
>>> %timeit json_normalise_drop(df.copy())
1 loop, best of 3: 54.9 s per loop
>>> %timeit tolist_drop(df.copy())
1 loop, best of 3: 6.62 s per loop
>>> %timeit vlues_tolist_drop(df.copy())
1 loop, best of 3: 6.63 s per loop
>>> %timeit pop_tolist(df.copy())
1 loop, best of 3: 5.99 s per loop
>>> %timeit pop_values_tolist(df.copy())
1 loop, best of 3: 5.94 s per loop
+---------------------+-----------+
| apply_drop          | 53min 20s |
| json_normalise_drop |    54.9 s |
| tolist_drop         |    6.62 s |
| vlues_tolist_drop   |    6.63 s |
| pop_tolist          |    5.99 s |
| pop_values_tolist   |    5.94 s |
+---------------------+-----------+

df.join(pd.DataFrame(df.pop('Pollutants').values.tolist())) is the fastest

Open file by its full path in C++

A different take on this question, which might help someone:

I came here because I was debugging in Visual Studio on Windows, and I got confused about all this / vs \\ discussion (it really should not matter in most cases).

For me, the problem was: the "current directory" was not set to what I wanted in Visual Studio. It defaults to the directory of the executable (depending on how you set up your project).

Change it via: Right-click the solution -> Properties -> Working Directory

I only mention it because the question seems Windows-centric, which generally also means VisualStudio-centric, which tells me this hint might be relevant (:

How to reduce the image file size using PIL

lets say you have a model called Book and on it a field called 'cover_pic', in that case, you can do the following to compress the image:

from PIL import Image
b = Book.objects.get(title='Into the wild')
image = Image.open(b.cover_pic.path)
image.save(b.image.path,quality=20,optimize=True)

hope it helps to anyone stumbling upon it.

Import text file as single character string

I would use the following. It should work just fine, and doesn't seem ugly, at least to me:

singleString <- paste(readLines("foo.txt"), collapse=" ")

How to display a readable array - Laravel

dd() dumps the variable and ends the execution of the script (1), so surrounding it with <pre> tags will leave it broken. Just use good ol' var_dump() (or print_r() if you know it's an array)

Route::get('/', function()
{
    echo '<pre>';
    var_dump(User::all());
    echo '</pre>';
    //exit;  <--if you want
});

Update:

I think you could format down what's shown by having Laravel convert the model object to array:

Route::get('/', function()
{
    echo '<pre>';
    $user = User::where('person_id', '=', 1);
    var_dump($user->toArray()); // <---- or toJson()
    echo '</pre>';
    //exit;  <--if you want
});

(1) For the record, this is the implementation of dd():

function dd()
{
    array_map(function($x) { var_dump($x); }, func_get_args()); die;
}

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

Adding my two cents, based on a performance issue I observed.

If simple queries are getting parellelized unnecessarily, it can bring more problems than solving one. However, before adding MAXDOP into the query as "knee-jerk" fix, there are some server settings to check.

In Jeremiah Peschka - Five SQL Server Settings to Change, MAXDOP and "COST THRESHOLD FOR PARALLELISM" (CTFP) are mentioned as important settings to check.

Note: Paul White mentioned max server memory aslo as a setting to check, in a response to Performance problem after migration from SQL Server 2005 to 2012. A good kb article to read is Using large amounts of memory can result in an inefficient plan in SQL Server

Jonathan Kehayias - Tuning ‘cost threshold for parallelism’ from the Plan Cache helps to find out good value for CTFP.

Why is cost threshold for parallelism ignored?

Aaron Bertrand - Six reasons you should be nervous about parallelism has a discussion about some scenario where MAXDOP is the solution.

Parallelism-Inhibiting Components are mentioned in Paul White - Forcing a Parallel Query Execution Plan

How to check if spark dataframe is empty?

If you do df.count > 0. It takes the counts of all partitions across all executors and add them up at Driver. This take a while when you are dealing with millions of rows.

The best way to do this is to perform df.take(1) and check if its null. This will return java.util.NoSuchElementException so better to put a try around df.take(1).

The dataframe return an error when take(1) is done instead of an empty row. I have highlighted the specific code lines where it throws the error.

enter image description here

Is it possible to use if...else... statement in React render function?

You can render anything using the conditional statement like if, else :

 render() {
    const price = this.state.price;
    let comp;

    if (price) {

      comp = <h1>Block for getting started with {this.state.price}</h1>

    } else {

      comp = <h1>Block for getting started.</h1>

    }

    return (
      <div>
        <div className="gettingStart">
          {comp}
        </div>
      </div>
    );
  }

Iterating over each line of ls -l output

The read(1) utility along with output redirection of the ls(1) command will do what you want.

What is the "right" JSON date format?

"2014-01-01T23:28:56.782Z"

The date is represented in a standard and sortable format that represents a UTC time (indicated by the Z). ISO 8601 also supports time zones by replacing the Z with + or – value for the timezone offset:

"2014-02-01T09:28:56.321-10:00"

There are other variations of the timezone encoding in the ISO 8601 spec, but the –10:00 format is the only TZ format that current JSON parsers support. In general it’s best to use the UTC based format (Z) unless you have a specific need for figuring out the time zone in which the date was produced (possible only in server side generation).

NB:

    var date = new Date();
    console.log(date); // Wed Jan 01 2014 13:28:56 GMT- 
    1000 (Hawaiian Standard Time) 
        
    var json = JSON.stringify(date);
    console.log(json);  // "2014-01-01T23:28:56.782Z"

To tell you that's the preferred way even though JavaScript doesn't have a standard format for it

// JSON encoded date
var json = "\"2014-01-01T23:28:56.782Z\"";

var dateStr = JSON.parse(json);  
console.log(dateStr); // 2014-01-01T23:28:56.782Z

Can we cast a generic object to a custom object type in javascript?

This is not exactly an answer, rather sharing my findings, and hopefully getting some critical argument for/against it, as specifically I am not aware how efficient it is.

I recently had a need to do this for my project. I did this using Object.assign, more precisely it is done something like this:Object.assign(new Person(...), anObjectLikePerson).

Here is link to my JSFiddle, and also the main part of the code:

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;

  this.getFullName = function() {
    return this.lastName + ' ' + this.firstName;
  }
}

var persons = [{
  lastName: "Freeman",
  firstName: "Gordon"
}, {
  lastName: "Smith",
  firstName: "John"
}];

var stronglyTypedPersons = [];
for (var i = 0; i < persons.length; i++) {
  stronglyTypedPersons.push(Object.assign(new Person("", ""), persons[i]));
}

Concatenate two slices in Go

append( ) function and spread operator

Two slices can be concatenated using append method in the standard golang library. Which is similar to the variadic function operation. So we need to use ...

package main

import (
    "fmt"
)

func main() {
    x := []int{1, 2, 3}
    y := []int{4, 5, 6}
    z := append([]int{}, append(x, y...)...)
    fmt.Println(z)
}

output of the above code is: [1 2 3 4 5 6]

How to get tf.exe (TFS command line client)?

You can also try TFS CLI for Node.js which is a cross-platform CLI for Microsoft Team Foundation Server and Visual Studio Team Services.

Redirect HTTP to HTTPS on default virtual host without ServerName

Both works fine. But according to the Apache docs you should avoid using mod_rewrite for simple redirections, and use Redirect instead. So according to them, you should preferably do:

<VirtualHost *:80>
    ServerName www.example.com
    Redirect / https://www.example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.com
    # ... SSL configuration goes here
</VirtualHost>

The first / after Redirect is the url, the second part is where it should be redirected.

You can also use it to redirect URLs to a subdomain: Redirect /one/ http://one.example.com/

excel VBA run macro automatically whenever a cell is changed

Yes, this is possible by using worksheet events:

In the Visual Basic Editor open the worksheet you're interested in (i.e. "BigBoard") by double clicking on the name of the worksheet in the tree at the top left. Place the following code in the module:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Intersect(Target, Me.Range("D2")) Is Nothing Then Exit Sub
        Application.EnableEvents = False 'to prevent endless loop
        On Error Goto Finalize 'to re-enable the events      
        MsgBox "You changed THE CELL!"
    End If
Finalize:        
    Application.EnableEvents = True
End Sub

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

I had a similar error but with different context when I uploaded a *.p file to Google Drive. I tried to use it later in a Google Colab session, and got this error:

    1 with open("/tmp/train.p", mode='rb') as training_data:
----> 2     train = pickle.load(training_data)
UnpicklingError: invalid load key, '<'.

I solved it by compressing the file, upload it and then unzip on the session. It looks like the pickle file is not saved correctly when you upload/download it so it gets corrupted.

How to Import 1GB .sql file to WAMP/phpmyadmin

Before importing just make sure you have max_allowed_pack value set some thing large else you will get an error: Error 2006 MySQL server gone away.

Then try the command: mysql -u root -p database_name < file.sql

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

It appears that my max ports weren't configured correctly. I ran the following code and it worked...

echo fs.inotify.max_user_watches=582222 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

What this command does is to increase the number of watches allowed for a single user. By the default the number can be low (8192 for example). When nodemon tries to watch large numbers of directories for changes it has to create several watches, which can surpass that limit.

You could also solve this problem by:

sudo sysctl fs.inotify.max_user_watches=582222 && sudo sysctl -p

But the way it was written first will make this change permanent.

Javascript/jQuery: Set Values (Selection) in a multiple Select

Just provide the jQuery val function with an array of values:

var values = "Test,Prof,Off";
$('#strings').val(values.split(','));

And to get the selected values in the same format:

values = $('#strings').val();

get an element's id

Super Easy Way is

  $('.CheckBxMSG').each(function () {
            var ChkBxMsgId;
            ChkBxMsgId = $(this).attr('id');
            alert(ChkBxMsgId);
        });

Tell me if this helps

HTML SELECT - Change selected option by VALUE using JavaScript

document.getElementById('drpSelectSourceLibrary').value = 'Seven';

Java: Literal percent sign in printf statement

The percent sign is escaped using a percent sign:

System.out.printf("%s\t%s\t%1.2f%%\t%1.2f%%\n",ID,pattern,support,confidence);

The complete syntax can be accessed in java docs. This particular information is in the section Conversions of the first link.

The reason the compiler is generating an error is that only a limited amount of characters may follow a backslash. % is not a valid character.

Trying to SSH into an Amazon Ec2 instance - permission error

Key file should not be publicly viewable so use permission 400

chmod 400 keyfile.pem

If above command shows permission error use

sudo chmod 400 keyfile.pem

Now ssh into the ec2 machine, if you still face the issue, use ec2-user

ssh -i keyfile.pem [email protected]

jQuery ajax call to REST service

You are running your HTML from a different host than the host you are requesting. Because of this, you are getting blocked by the same origin policy.

One way around this is to use JSONP. This allows cross-site requests.

In JSON, you are returned:

{a: 5, b: 6}

In JSONP, the JSON is wrapped in a function call, so it becomes a script, and not an object.

callback({a: 5, b: 6})

You need to edit your REST service to accept a parameter called callback, and then to use the value of that parameter as the function name. You should also change the content-type to application/javascript.

For example: http://localhost:8080/restws/json/product/get?callback=process should output:

process({a: 5, b: 6})

In your JavaScript, you will need to tell jQuery to use JSONP. To do this, you need to append ?callback=? to the URL.

$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
   function(data) {
     alert(data);         
   });

If you use $.ajax, it will auto append the ?callback=? if you tell it to use jsonp.

$.ajax({ 
   type: "GET",
   dataType: "jsonp",
   url: "http://localhost:8080/restws/json/product/get",
   success: function(data){        
     alert(data);
   }
});

/bin/sh: pushd: not found

pushd is a bash enhancement to the POSIX-specified Bourne Shell. pushd cannot be easily implemented as a command, because the current working directory is a feature of a process that cannot be changed by child processes. (A hypothetical pushd command might do the chdir(2) call and then start a new shell, but ... it wouldn't be very usable.) pushd is a shell builtin, just like cd.

So, either change your script to start with #!/bin/bash or store the current working directory in a variable, do your work, then change back. Depends if you want a shell script that works on very reduced systems (say, a Debian build server) or if you're fine always requiring bash.

Tensorflow import error: No module named 'tensorflow'

I had same issues on Windows 64-bit processor but manage to solve them. Check if your Python is for 32- or 64-bit installation. If it is for 32-bit, then you should download the executable installer (for e.g. you can choose latest Python version - for me is 3.7.3) https://www.python.org/downloads/release/python-373/ -> Scroll to the bottom in Files section and select “Windows x86-64 executable installer”. Download and install it.

The tensorflow installation steps check here : https://www.tensorflow.org/install/pip . I hope this helps somehow ...

How do I get PHP errors to display?

This code on top should work:

error_reporting(E_ALL);

However, try to edit the code on the phone in the file:

error_reporting =on

python pandas: apply a function with arguments to a series

Newer versions of pandas do allow you to pass extra arguments (see the new documentation). So now you can do:

my_series.apply(your_function, args=(2,3,4), extra_kw=1)

The positional arguments are added after the element of the series.


For older version of pandas:

The documentation explains this clearly. The apply method accepts a python function which should have a single parameter. If you want to pass more parameters you should use functools.partial as suggested by Joel Cornett in his comment.

An example:

>>> import functools
>>> import operator
>>> add_3 = functools.partial(operator.add,3)
>>> add_3(2)
5
>>> add_3(7)
10

You can also pass keyword arguments using partial.

Another way would be to create a lambda:

my_series.apply((lambda x: your_func(a,b,c,d,...,x)))

But I think using partial is better.

Check if table exists

    /**
 * Method that checks if all tables exist
 * If a table doesnt exist it creates the table
 */
public void checkTables() {
    try {
        startConn();// method that connects with mysql database
        String useDatabase = "USE " + getDatabase() + ";";
        stmt.executeUpdate(useDatabase);
        String[] tables = {"Patients", "Procedures", "Payments", "Procedurables"};//thats table names that I need to create if not exists
        DatabaseMetaData metadata = conn.getMetaData();

        for(int i=0; i< tables.length; i++) {
            ResultSet rs = metadata.getTables(null, null, tables[i], null);
            if(!rs.next()) {
                createTable(tables[i]);
                System.out.println("Table " + tables[i] + " created");
            }
        }
    } catch(SQLException e) {
        System.out.println("checkTables() " + e.getMessage());
    }
    closeConn();// Close connection with mysql database
}

Composer update memory limit

I am facing problems with composer because it consumes all the available memory, and then, the process get killed ( actualy, the output message is "Killed")

So, I was looking for a solution to limit composer memory usage.

I tried ( from @Sven answers )

$ php -d memory_limit=512M /usr/local/bin/composer update

But it didn't work because

"Composer internally increases the memory_limit to 1.5G."

-> Thats from composer oficial website.

Then I found a command that works :

$ COMPOSER_MEMORY_LIMIT=512M php composer.phar update

Althought, in my case 512mb is not enough !

Source : https://www.agileana.com/blog/composer-memory-limit-troubleshooting/

Spring Boot not serving static content

Did you check the Spring Boot reference docs?

By default Spring Boot will serve static content from a folder called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext.

You can also compare your project with the guide Serving Web Content with Spring MVC, or check out the source code of the spring-boot-sample-web-ui project.

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

HTML forms support GET and POST. (HTML5 at one point added PUT/DELETE, but those were dropped.)

XMLHttpRequest supports every method, including CHICKEN, though some method names are matched against case-insensitively (methods are case-sensitive per HTTP) and some method names are not supported at all for security reasons (e.g. CONNECT).

Browsers are slowly converging on the rules specified by XMLHttpRequest, but as the other comment pointed out there are still some differences.

How to print out the method name and line number and conditionally disable NSLog?

My answer to this question might help, looks like it's similar to the one Diederik cooked up. You may also want to replace the call to NSLog() with a static instance of your own custom logging class, that way you can add a priority flag for debug/warning/error messages, send messages to a file or database as well as the console, or pretty much whatever else you can think of.

#define DEBUG_MODE

#ifdef DEBUG_MODE
    #define DebugLog( s, ... ) NSLog( @"<%p %@:(%d)> %@", self, 
              [[NSString stringWithUTF8String:__FILE__] lastPathComponent], 
              __LINE__, 
              [NSString stringWithFormat:(s), 
              ##__VA_ARGS__] )
#else
    #define DebugLog( s, ... ) 
#endif

How to select rows in a DataFrame between two values, in Python Pandas?

You should use () to group your boolean vector to remove ambiguity.

df = df[(df['closing_price'] >= 99) & (df['closing_price'] <= 101)]

Insert picture/table in R Markdown

In March I made a deck presentation in slidify, Rmarkdown with impress.js which is a cool 3D framework. My index.Rmdheader looks like

---
title       : French TER (regional train) monthly regularity
subtitle    : since January 2013
author      : brigasnuncamais
job         : Business Intelligence / Data Scientist consultant
framework   : impressjs     # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js  # {highlight.js, prettify, highlight}
hitheme     : tomorrow      # 
widgets     : []            # {mathjax, quiz, bootstrap}
mode        : selfcontained # {standalone, draft}
knit        : slidify::knit2slides

subdirs are:

/assets /css    /impress-demo.css
        /fig    /unnamed-chunk-1-1.png (generated by included R code)
        /img    /SS850452.png (my image used as background)
        /js     /impress.js
        /layouts/custbg.html # content:--- layout: slide --- {{{ slide.html }}}
        /libraries  /frameworks /impressjs
                                /io2012
                    /highlighters   /highlight.js
                                    /impress.js
index.Rmd

A slide with image in background code snippet would be in my .Rmd:

<div id="bg">
  <img src="assets/img/SS850452.png" alt="">
</div>  

Some issues appeared since I last worked on it (photos are no more in background, text it too large on my R plot) but it works fine on my local. Troubles come when I run it on RPubs.

How do I create a table based on another table

select * into newtable from oldtable