Programs & Examples On #Build numbers

Using a Glyphicon as an LI bullet point (Bootstrap 3)

If anyone is coming here looking to do this with Font Awesome Icons (like I was) view here: https://fontawesome.com/how-to-use/on-the-web/styling/icons-in-a-list

<ul class="fa-ul">
  <li><i class="fa-li fa fa-check-square"></i>List icons</li>
  <li><i class="fa-li fa fa-check-square"></i>can be used</li>
  <li><i class="fa-li fa fa-spinner fa-spin"></i>as bullets</li>
  <li><i class="fa-li fa fa-square"></i>in lists</li>
</ul>

The fa-ul and fa-li classes easily replace default bullets in unordered lists.

How to debug "ImagePullBackOff"?

Run docker login

Push the image to docker hub

Re-create pod

This solved the problem for me. Hope it helps.

Visibility of global variables in imported modules

A function uses the globals of the module it's defined in. Instead of setting a = 3, for example, you should be setting module1.a = 3. So, if you want cur available as a global in utilities_module, set utilities_module.cur.

A better solution: don't use globals. Pass the variables you need into the functions that need it, or create a class to bundle all the data together, and pass it when initializing the instance.

source command not found in sh shell

/bin/sh is usually some other shell trying to mimic The Shell. Many distributions use /bin/bash for sh, it supports source. On Ubuntu, though, /bin/dash is used which does not support source. Most shells use . instead of source. If you cannot edit the script, try to change the shell which runs it.

XML to CSV Using XSLT

Here is a version with configurable parameters that you can set programmatically:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="utf-8" />

  <xsl:param name="delim" select="','" />
  <xsl:param name="quote" select="'&quot;'" />
  <xsl:param name="break" select="'&#xA;'" />

  <xsl:template match="/">
    <xsl:apply-templates select="projects/project" />
  </xsl:template>

  <xsl:template match="project">
    <xsl:apply-templates />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$break" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="*">
    <!-- remove normalize-space() if you want keep white-space at it is --> 
    <xsl:value-of select="concat($quote, normalize-space(), $quote)" />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$delim" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="text()" />
</xsl:stylesheet>

How does one generate a random number in Apple's Swift language?

You can use GeneratorOf like this:

var fibs = ArraySlice([1, 1])
var fibGenerator = GeneratorOf{
    _ -> Int? in
    fibs.append(fibs.reduce(0, combine:+))
    return fibs.removeAtIndex(0)
}

println(fibGenerator.next())
println(fibGenerator.next())
println(fibGenerator.next())
println(fibGenerator.next())
println(fibGenerator.next())
println(fibGenerator.next())

How to access the ith column of a NumPy multidimensional array?

You could also transpose and return a row:

In [4]: test.T[0]
Out[4]: array([1, 3, 5])

Android failed to load JS bundle

In the app on android I opened Menu (Command + M in Genymotion) -> Dev Settings -> Debug server host & port for device

set the value to: localhost:8081

It worked for me.

How to filter input type="file" dialog by specific file type?

See http://www.w3schools.com/tags/att_input_accept.asp:

The accept attribute is supported in all major browsers, except Internet Explorer and Safari. Definition and Usage

The accept attribute specifies the types of files that the server accepts (that can be submitted through a file upload).

Note: The accept attribute can only be used with <input type="file">.

Tip: Do not use this attribute as a validation tool. File uploads should be validated on the server.

Syntax <input accept="audio/*|video/*|image/*|MIME_type" />

Tip: To specify more than one value, separate the values with a comma (e.g. <input accept="audio/*,video/*,image/*" />.

What does body-parser do with express?

Yes we can work without body-parser. When you don't use that you get the raw request, and your body and headers are not in the root object of request parameter . You will have to individually manipulate all the fields.

Or you can use body-parser, as the express team is maintaining it .

What body-parser can do for you: It simplifies the request.
How to use it: Here is example:

Install npm install body-parser --save

This how to use body-parser in express:

const express = require('express'),
      app = express(),
      bodyParser = require('body-parser');

// support parsing of application/json type post data
app.use(bodyParser.json());

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));

Link.

https://github.com/expressjs/body-parser.

And then you can get body and headers in root request object . Example

app.post("/posturl",function(req,res,next){
    console.log(req.body);
    res.send("response");
})

Convert UTC date time to local date time

Append 'UTC' to the string before converting it to a date in javascript:

var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"

How to get the day name from a selected date?

//default locale
System.DateTime.Now.DayOfWeek.ToString();
//localized version
System.DateTime.Now.ToString("dddd");

To make the answer more complete:

babel-loader jsx SyntaxError: Unexpected token

This works perfect for me

{
    test: /\.(js|jsx)$/,
    loader: 'babel-loader',
    exclude: /node_modules/,
    query: {
        presets: ['es2015','react']
    }
},

How can I print to the same line?

One could simply use \r to keep everything in the same line while erasing what was previously on that line.

Java - Reading XML file

Reading xml the easy way:

http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

} 

.

package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

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

    }
}

Set an empty DateTime variable

This will work for null able dateTime parameter

. .

SearchUsingDate(DateTime? StartDate, DateTime? EndDate){
     DateTime LastDate;
     if (EndDate != null)
       {
          LastDate = (DateTime)EndDate;
          LastDate = LastDate.AddDays(1);
          EndDate = LastDate;
        }
}

Android Studio error: "Environment variable does not point to a valid JVM installation"

all u need to do that is set tJAVA_HOME and JDK_HOME environment variables paths for this go my computer properties set path with name JAVA_HOME and JDK_HOME C:\Program Files\Java\jdk1.8.0_25

enter image description here

Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists

This issue could be related with missing SSH key at Github or any other git server.

In my case I had copied code to another computer and tried to git pull. It failed.

So I had to generate a new SSH key on that machine and update profile on git server with additional SSH key.

How to create a directory if it doesn't exist using Node.js?

Here is a little function to recursivlely create directories:

const createDir = (dir) => {
  // This will create a dir given a path such as './folder/subfolder' 
  const splitPath = dir.split('/');
  splitPath.reduce((path, subPath) => {
    let currentPath;
    if(subPath != '.'){
      currentPath = path + '/' + subPath;
      if (!fs.existsSync(currentPath)){
        fs.mkdirSync(currentPath);
      }
    }
    else{
      currentPath = subPath;
    }
    return currentPath
  }, '')
}

Close Android Application

just call the finish() in the method you would like to end the activity in, for example when you use the onCreate() method, in the end of the method, just add finish() and you will see the activity ends as soon as it is created!

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

As far as I know PKCS#12 is just a certificate/public/private key store. If you extracted a public key from PKCS#12 file, OpenSSH should be able to use it as long as it was extracted in PEM format. You probably already know that you also need a corresponding private key (also in PEM) in order to use it for ssh-public-key authentication.

How to edit hosts file via CMD?

echo 0.0.0.0 websitename.com >> %WINDIR%\System32\Drivers\Etc\Hosts

the >> appends the output of echo to the file.

Note that there are two reasons this might not work like you want it to. You may be aware of these, but I mention them just in case.

First, it won't affect a web browser, for example, that already has the current, "real" IP address resolved. So, it won't always take effect right away.

Second, it requires you to add an entry for every host name on a domain; just adding websitename.com will not block www.websitename.com, for example.

Vue - Deep watching an array of objects and calculating the change?

The component solution and deep-clone solution have their advantages, but also have issues:

  1. Sometimes you want to track changes in abstract data - it doesn't always make sense to build components around that data.

  2. Deep-cloning your entire data structure every time you make a change can be very expensive.

I think there's a better way. If you want to watch all items in a list and know which item in the list changed, you can set up custom watchers on every item separately, like so:

var vm = new Vue({
  data: {
    list: [
      {name: 'obj1 to watch'},
      {name: 'obj2 to watch'},
    ],
  },
  methods: {
    handleChange (newVal) {
      // Handle changes here!
      console.log(newVal);
    },
  },
  created () {
    this.list.forEach((val) => {
      this.$watch(() => val, this.handleChange, {deep: true});
    });
  },
});

With this structure, handleChange() will receive the specific list item that changed - from there you can do any handling you like.

I have also documented a more complex scenario here, in case you are adding/removing items to your list (rather than only manipulating the items already there).

Change a branch name in a Git repo

If you're currently on the branch you want to rename:

git branch -m new_name 

Or else:

git branch -m old_name new_name 

You can check with:

git branch -a

As you can see, only the local name changed Now, to change the name also in the remote you must do:

git push origin :old_name

This removes the branch, then upload it with the new name:

git push origin new_name

Source: https://web.archive.org/web/20150929104013/http://blog.changecong.com:80/2012/10/rename-a-remote-branch-on-github

Google Maps: How to create a custom InfoWindow?

EDIT After some hunting around, this seems to be the best option:

https://github.com/googlemaps/js-info-bubble/blob/gh-pages/examples/example.html

You can see a customised version of this InfoBubble that I used on Dive Seven, a website for online scuba dive logging. It looks like this:


There are some more examples here. They definitely don't look as nice as the example in your screenshot, however.

The thread has exited with code 0 (0x0) with no unhandled exception

Well, an application may have a lot of threads running in parallel. Some are run by you, the coder, some are run by framework classes (espacially if you are in a GUI environnement).

When a thread has finished its task, it exits and stops to exist. There ie nothing alarming in this and you should not care.

Disabling the button after once click

protected void Page_Load(object sender, EventArgs e)
    {
        // prevent user from making operation twice
        btnSave.Attributes.Add("onclick", 
                               "this.disabled=true;" + GetPostBackEventReference(btnSave).ToString() + ";");

        // ... etc. 
    }

Div height 100% and expands to fit content

Set the height to auto and min-height to 100%. This should solve it for most browsers.

body {
  position: relative;
  height: auto;
  min-height: 100% !important;
}

Migrating from VMWARE to VirtualBox

Note: I am not sure this will be of any help to you, but you never know.

I found this link:http://www.ubuntugeek.com/howto-convert-vmware-image-to-virtualbox-image.html

ENJOY :-)

Adding a view controller as a subview in another view controller

This code will work for Swift 4.2.

let controller:SecondViewController = 
self.storyboard!.instantiateViewController(withIdentifier: "secondViewController") as! 
SecondViewController
controller.view.frame = self.view.bounds;
self.view.addSubview(controller.view)
self.addChild(controller)
controller.didMove(toParent: self)

How do I register a DLL file on Windows 7 64-bit?

There is a difference in Windows 7. Logging on as Administrator does not give the same rights as when running a program as Administrator.

Go to Start - All Programs - Accesories. Right click on the Command window and select "Run as administrator" Now register the dll normally via : regsrvr32 xxx.dll

What EXACTLY is meant by "de-referencing a NULL pointer"?

A NULL pointer points to memory that doesn't exist, and will raise Segmentation fault. There's an easier way to de-reference a NULL pointer, take a look.

int main(int argc, char const *argv[])
{
    *(int *)0 = 0; // Segmentation fault (core dumped)
    return 0;
}

Since 0 is never a valid pointer value, a fault occurs.

SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=NULL}

In Python, how do I loop through the dictionary and change the value if it equals something?

Comprehensions are usually faster, and this has the advantage of not editing mydict during the iteration:

mydict = dict((k, v if v else '') for k, v in mydict.items())

How do I use the conditional operator (? :) in Ruby?

A simple example where the operator checks if player's id is 1 and sets enemy id depending on the result

player_id=1
....
player_id==1? enemy_id=2 : enemy_id=1
# => enemy=2

And I found a post about to the topic which seems pretty helpful.

How to split a line into words separated by one or more spaces in bash?

If you want a specific word from the line, awk might be useful, e.g.

$ echo $LINE | awk '{print $2}'

Prints the second whitespace separated word in $LINE. You can also split on other characters, e.g.

$ echo "5:6:7" | awk -F: '{print $2}'
6

Get UTC time and local time from NSDate object

Swift 3

You can get Date based on your current timezone from UTC

extension Date {
    func currentTimeZoneDate() -> String {
        let dtf = DateFormatter()
        dtf.timeZone = TimeZone.current
        dtf.dateFormat = "yyyy-MM-dd HH:mm:ss"

        return dtf.string(from: self)
    }
}

Call like this:

Date().currentTimeZoneDate()

Difference between DOM parentNode and parentElement

Use .parentElement and you can't go wrong as long as you aren't using document fragments.

If you use document fragments, then you need .parentNode:

let div = document.createDocumentFragment().appendChild(document.createElement('div'));
div.parentElement // null
div.parentNode // document fragment

Also:

_x000D_
_x000D_
let div = document.getElementById('t').content.firstChild_x000D_
div.parentElement // null_x000D_
div.parentNode // document fragment
_x000D_
<template id="t"><div></div></template>
_x000D_
_x000D_
_x000D_


Apparently the <html>'s .parentNode links to the Document. This should be considered a decision phail as documents aren't nodes since nodes are defined to be containable by documents and documents can't be contained by documents.

How do I sort an observable collection?

WPF provides live sorting out-of-the-box using the ListCollectionView class...

public ObservableCollection<string> MyStrings { get; set; }
private ListCollectionView _listCollectionView;
private void InitializeCollection()
{
    MyStrings = new ObservableCollection<string>();
    _listCollectionView = CollectionViewSource.GetDefaultView(MyStrings) 
              as ListCollectionView;
    if (_listCollectionView != null)
    {
        _listCollectionView.IsLiveSorting = true;
        _listCollectionView.CustomSort = new 
                CaseInsensitiveComparer(CultureInfo.InvariantCulture);
    }
}

Once this initialization is complete, there's nothing more to do. The advantage over a passive sort is that the ListCollectionView does all the heavy lifting in a way that's transparent to the developer. New items are automatically placed in their correct sort order. Any class that derives from IComparer of T is suitable for the custom sort property.

See ListCollectionView for the documentation and other features.

How do I convert a list into a string with spaces in Python?

"".join([i for i in my_list])

This should work just like you asked!

How do I push a local Git branch to master branch in the remote?

Follow the below steps for push the local repo into Master branchenter code here

$git status

How to JOIN three tables in Codeigniter

public function getdata(){
        $this->db->select('c.country_name as country, s.state_name as state, ct.city_name as city, t.id as id');
        $this->db->from('tblmaster t'); 
        $this->db->join('country c', 't.country=c.country_id');
        $this->db->join('state s', 't.state=s.state_id');
        $this->db->join('city ct', 't.city=ct.city_id');
        $this->db->order_by('t.id','desc');
        $query = $this->db->get();      
        return $query->result();
}

How to identify unused CSS definitions from multiple CSS files in a project

I have just found this site – http://unused-css.com/

Looks good but I would need to thoroughly check its outputted 'clean' css before uploading it to any of my sites.

Also as with all these tools I would need to check it didn't strip id's and classes with no style but are used as JavaScript selectors.

The below content is taken from http://unused-css.com/ so credit to them for recommending other solutions:

Latish Sehgal has written a windows application to find and remove unused CSS classes. I haven't tested it but from the description, you have to provide the path of your html files and one CSS file. The program will then list the unused CSS selectors. From the screenshot, it looks like there is no way to export this list or download a new clean CSS file. It also looks like the service is limited to one CSS file. If you have multiple files you want to clean, you have to clean them one by one.

Dust-Me Selectors is a Firefox extension (for v1.5 or later) that finds unused CSS selectors. It extracts all the selectors from all the stylesheets on the page you're viewing, then analyzes that page to see which of those selectors are not used. The data is then stored so that when testing subsequent pages, selectors can be crossed off the list as they're encountered. This tool is supposed to be able to spider a whole website but I unfortunately could make it work. Also, I don't believe you can configure and download the CSS file with the styles removed.

Topstyle is a windows application including a bunch of tools to edit CSS. I haven't tested it much but it looks like it has the ability to removed unused CSS selectors. This software costs 80 USD.

Liquidcity CSS cleaner is a php script that uses regular expressions to check the styles of one page. It will tell you the classes that aren't available in the HTML code. I haven't tested this solution.

Deadweight is a CSS coverage tool. Given a set of stylesheets and a set of URLs, it determines which selectors are actually used and lists which can be "safely" deleted. This tool is a ruby module and will only work with rails website. The unused selectors have to be manually removed from the CSS file.

Helium CSS is a javascript tool for discovering unused CSS across many pages on a web site. You first have to install the javascript file to the page you want to test. Then, you have to call a helium function to start the cleaning.

UnusedCSS.com is web application with an easy to use interface. Type the url of a site and you will get a list of CSS selectors. For each selector, a number indicates how many times a selector is used. This service has a few limitations. The @import statement is not supported. You can't configure and download the new clean CSS file.

CSSESS is a bookmarklet that helps you find unused CSS selectors on any site. This tool is pretty easy to use but it won't let you configure and download clean CSS files. It will only list unused CSS files.

Encrypt and Decrypt in Java

KeyGenerator is used to generate keys

You may want to check KeySpec, SecretKey and SecretKeyFactory classes

http://docs.oracle.com/javase/1.5.0/docs/api/javax/crypto/spec/package-summary.html

SQLite add Primary Key

You can't modify SQLite tables in any significant way after they have been created. The accepted suggested solution is to create a new table with the correct requirements and copy your data into it, then drop the old table.

here is the official documentation about this: http://sqlite.org/faq.html#q11

HTML Submit-button: Different value / button-text?

I don't know if I got you right, but, as I understand, you could use an additional hidden field with the value "add tag" and let the button have the desired text.

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

I don't know that you are going to find a platform-neutral solution.

This is commonly called an "UPSERT".

See some related discussions:

How can I split this comma-delimited string in Python?

Question is a little vague.

list_of_lines = multiple_lines.split("\n")
for line in list_of_lines:
    list_of_items_in_line = line.split(",")
    first_int = int(list_of_items_in_line[0])

etc.

How to remove an app with active device admin enabled on Android?

You could also create a new DevicePolicyManager and then use removeAdmin(adminReceiver) from an onClickListener of a button in your app

//set the onClickListener here
{
   ComponentName devAdminReceiver = new ComponentName(context, deviceAdminReceiver.class);
   DevicePolicyManager dpm = (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE);
   dpm.removeActiveAdmin(devAdminReceiver);
}

And then you can uninstall

What does the "+" (plus sign) CSS selector mean?

p+p{
//styling the code
}

p+p{
} simply mean find all the adjacent/sibling paragraphs with respect to first paragraph in DOM body.

    <div>
    <input type="text" placeholder="something">
    <p>This is first paragraph</p>
    <button>Button </button>
    <p> This is second paragraph</p>
    <p>This is third paragraph</p>
    </div>

    Styling part 
    <style type="text/css">
        p+p{
            color: red;
            font-weight: bolder;
        }
    </style>

   It will style all sibling paragraph with red color.

final output look like this

enter image description here

How does "304 Not Modified" work exactly?

Last-Modified : The last modified date for the requested object

If-Modified-Since : Allows a 304 Not Modified to be returned if last modified date is unchanged.

ETag : An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL. If the resource representation at that URL ever changes, a new and different ETag is assigned.

If-None-Match : Allows a 304 Not Modified to be returned if ETag is unchanged.

the browser store cache with a date(Last-Modified) or id(ETag), when you need to request the URL again, the browser send request message with the header:

enter image description here

the server will return 304 when the if statement is False, and browser will use cache.

Why am I getting string does not name a type Error?

Try a using namespace std; at the top of game.h or use the fully-qualified std::string instead of string.

The namespace in game.cpp is after the header is included.

MySQL - force not to use cache for testing speed of query

If you want to disable the Query cache set the 'query_cache_size' to 0 in your mysql configuration file . If its set 0 mysql wont use the query cache.

How to merge two arrays of objects by ID using lodash?

Create dictionaries for both arrays using _.keyBy(), merge the dictionaries, and convert the result to an array with _.values(). In this way, the order of the arrays doesn't matter. In addition, it can also handle arrays of different length.

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = _(arr1) // start sequence_x000D_
  .keyBy('member') // create a dictionary of the 1st array_x000D_
  .merge(_.keyBy(arr2, 'member')) // create a dictionary of the 2nd array, and merge it to the 1st_x000D_
  .values() // turn the combined dictionary to array_x000D_
  .value(); // get the value (array) out of the sequence_x000D_
_x000D_
console.log(merged);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Using ES6 Map

Concat the arrays, and reduce the combined array to a Map. Use Object#assign to combine objects with the same member to a new object, and store in map. Convert the map to an array with Map#values and spread:

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = [...arr1.concat(arr2).reduce((m, o) => _x000D_
  m.set(o.member, Object.assign(m.get(o.member) || {}, o))_x000D_
, new Map()).values()];_x000D_
_x000D_
console.log(merged);
_x000D_
_x000D_
_x000D_

How to create a custom exception type in Java?

You need to create a class that extends from Exception. It should look like this:

public class MyOwnException extends Exception {
    public MyOwnException () {

    }

    public MyOwnException (String message) {
        super (message);
    }

    public MyOwnException (Throwable cause) {
        super (cause);
    }

    public MyOwnException (String message, Throwable cause) {
        super (message, cause);
    }
}

Your question does not specify if this new exception should be checked or unchecked.

As you can see here, the two types are different:

  • Checked exceptions are meant to flag a problematic situation that should be handled by the developer who calls your method. It should be possible to recover from such an exception. A good example of this is a FileNotFoundException. Those exceptions are subclasses of Exception.

  • Unchecked exceptions are meant to represent a bug in your code, an unexpected situation that you might not be able to recover from. A NullPointerException is a classical example. Those exceptions are subclasses of RuntimeException

Checked exception must be handled by the calling method, either by catching it and acting accordingly, or by throwing it to the calling method. Unchecked exceptions are not meant to be caught, even though it is possible to do so.

How do I fix the multiple-step OLE DB operation errors in SSIS?

'-2147217887' message 'IDispatch error #3105' source 'Microsoft OLE DB Service Components' description 'Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.'."

This is what I was also facing. The problem came from the fact that I changed my SQLOLEDB.1 provider to SQLNCLI11 without mentioning the compatibility mode in the connection string. When I set this DataTypeCompatibility=80; in the connection string, I got the problem solved.

sed command with -i option failing on Mac, but works on Linux

Here is an option in bash scripts:

#!/bin/bash

GO_OS=${GO_OS:-"linux"}

function detect_os {
    # Detect the OS name
    case "$(uname -s)" in
      Darwin)
        host_os=darwin
        ;;
      Linux)
        host_os=linux
        ;;
      *)
        echo "Unsupported host OS. Must be Linux or Mac OS X." >&2
        exit 1
        ;;
    esac

   GO_OS="${host_os}"
}

detect_os

if [ "${GO_OS}" == "darwin" ]; then
    sed -i '' -e ...
else
    sed -i -e ...
fi

SimpleDateFormat parse loses timezone

All I needed was this :

SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

SimpleDateFormat sdfLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

try {
    String d = sdf.format(new Date());
    System.out.println(d);
    System.out.println(sdfLocal.parse(d));
} catch (Exception e) {
    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
}

Output : slightly dubious, but I want only the date to be consistent

2013.08.08 11:01:08
Thu Aug 08 11:01:08 GMT+08:00 2013

Finding elements not in a list

list1 = [1,2,3,4]; list2 = [0,3,3,6]

print set(list2) - set(list1)

Insert current date in datetime format mySQL

set the type of column named dateposted as DATETIME and run the following query:

INSERT INTO table (`dateposted`) VALUES (CURRENT_TIMESTAMP)

How to add google-play-services.jar project dependency so my project will run and present map

Some of the solutions described here did not work for me. Others did, however they produced warnings on runtime and javadoc was still not linked. After some experimenting, I managed to solve this. The steps are:

  1. Install the Google Play Services as recommended on Android Developers.

  2. Set up your project as recommended on Android Developers.

  3. If you followed 1. and 2., you should see two projects in your workspace: your project and google-play-services_lib project. Copy the docs folder which contains the javadoc from <android-sdk>/extras/google/google_play_services/ to libs folder of your project.

  4. Copy google-play-services.jar from <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/libs to 'libs' folder of your project.

  5. In google-play-services_lib project, edit libs/google-play-services.jar.properties . The <path> in doc=<path> should point to the subfolder reference of the folder docs, which you created in step 3.

  6. In Eclipse, do Project > Clean. Done, javadoc is now linked.

Reading values from DataTable

You can do it using the foreach loop

DataTable dr_art_line_2 = ds.Tables["QuantityInIssueUnit"];

  foreach(DataRow row in dr_art_line_2.Rows)
  {
     QuantityInIssueUnit_value = Convert.ToInt32(row["columnname"]);
  }

json_encode function: special characters

To me, it works this way:

# Creating the ARRAY from Result.
$array=array();

while($row = $result->fetch_array(MYSQL_ASSOC))
{
    # Converting each column to UTF8
    $row = array_map('utf8_encode', $row);
    array_push($array,$row);
}

json_encode($array);

Installing Python packages from local file system folder to virtualenv with pip

An option --find-links does the job and it works from requirements.txt file!

You can put package archives in some folder and take the latest one without changing the requirements file, for example requirements:

.
+---requirements.txt
+---requirements
    +---foo_bar-0.1.5-py2.py3-none-any.whl
    +---foo_bar-0.1.6-py2.py3-none-any.whl
    +---wiz_bang-0.7-py2.py3-none-any.whl
    +---wiz_bang-0.8-py2.py3-none-any.whl
    +---base.txt
    +---local.txt
    +---production.txt

Now in requirements/base.txt put:

--find-links=requirements
foo_bar
wiz_bang>=0.8

A neat way to update proprietary packages, just drop new one in the folder

In this way you can install packages from local folder AND pypi with the same single call: pip install -r requirements/production.txt

PS. See my cookiecutter-djangopackage fork to see how to split requirements and use folder based requirements organization.

Purpose of a constructor in Java?

Constructor is basicaly used for initialising the variables at the time of creation of object

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

@XmlRootElement
public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;
}

Then your @POST method would look like the following:

@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);
}

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com

{"param1":"hello","param2":"world"}

Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


HTML <FORM>

The parameters would be annotated using @FormParam:

@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {
    ...
}

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25

param1=hello&param2=world

The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
    ...
}

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {
    ...
}

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.


HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {
    ...
}

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0
Host: www.example.com

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.


HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {
    ...
}

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.


As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

Getting full URL of action in ASP.NET MVC

As Paddy mentioned: if you use an overload of UrlHelper.Action() that explicitly specifies the protocol to use, the generated URL will be absolute and fully qualified instead of being relative.

I wrote a blog post called How to build absolute action URLs using the UrlHelper class in which I suggest to write a custom extension method for the sake of readability:

/// <summary>
/// Generates a fully qualified URL to an action method by using
/// the specified action name, controller name and route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="actionName">The name of the action method.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteAction(this UrlHelper url,
    string actionName, string controllerName, object routeValues = null)
{
    string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;

    return url.Action(actionName, controllerName, routeValues, scheme);
}

You can then simply use it like that in your view:

@Url.AbsoluteAction("Action", "Controller")

What's an appropriate HTTP status code to return by a REST API service for a validation failure?

From RFC 4918 (and also documented at http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml):

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

How to create Android Facebook Key Hash?

Just run this code in your OnCreateView Or OnStart Actvity and This Function Return you Development Key Hash.

private String generateKeyHash() {
    try {
        PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = (MessageDigest.getInstance("SHA"));
            md.update(signature.toByteArray());
            return new String(Base64.encode(md.digest(), 0));
        }
    }catch (Exception e) {
        Log.e("exception", e.toString());
    }
    return "key hash not found";
}

How to make a edittext box in a dialog

Try below code:

alert.setTitle(R.string.WtsOnYourMind);

 final EditText input = new EditText(context);
 input.setHeight(100);
 input.setWidth(340);
 input.setGravity(Gravity.LEFT);

 input.setImeOptions(EditorInfo.IME_ACTION_DONE);
 alert.setView(input);

React native ERROR Packager can't listen on port 8081

You should kill all processes running on port 8081 by kill -9 $(lsof -i:8081)

VSCode: How to Split Editor Vertically

Press CMD + SHIFT + P (MAC) and search for Toggle Editor Group

password for postgres

What's the default superuser username/password for postgres after a new install?:

CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!

This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.

What you should do is follow Chris James's answer:

sudo -u postgres psql postgres

# \password postgres

Enter new password: 

To explain it a little bit...

expected constructor, destructor, or type conversion before ‘(’ token

This is not only a 'newbie' scenario. I just ran across this compiler message (GCC 5.4) when refactoring a class to remove some constructor parameters. I forgot to update both the declaration and definition, and the compiler spit out this unintuitive error.

The bottom line seems to be this: If the compiler can't match the definition's signature to the declaration's signature it thinks the definition is not a constructor and then doesn't know how to parse the code and displays this error. Which is also what happened for the OP: std::string is not the same type as string so the declaration's signature differed from the definition's and this message was spit out.

As a side note, it would be nice if the compiler looked for almost-matching constructor signatures and upon finding one suggested that the parameters didn't match rather than giving this message.

Combine two integer arrays

int [] newArray = new int[old1.length+old2.length];
System.arraycopy( old1, 0, newArray, 0, old1.length);
System.arraycopy( old2, 0, newArray, old1.length, old2.length );

Don't use element-by-element copying, it's very slow compared to System.arraycopy()

Starting of Tomcat failed from Netbeans

None of the answers here solved my issue (as at February 2020), so I raised an issue at https://issues.apache.org/jira/browse/NETBEANS-3903 and Netbeans fixed the issue!

They're working on a pull request so the fix will be in a future .dmg installer soon, but in the meantime you can copy a file referenced in the bug and replace one in your netbeans modules folder.

Tip - if you right click on Applications > Netbeans and choose Show Package Contents Show Package Contents then you can find and replace the file org-netbeans-modules-tomcat5.jar that they refer to in your Netbeans folder, e.g. within /Applications/NetBeans/Apache NetBeans 11.2.app/Contents/Resources/NetBeans/netbeans/enterprise/modules

How to allow Cross domain request in apache2

put the following in the site's .htaccess file (in the /var/www/XXX):

Header set Access-Control-Allow-Origin "*"

instead of the .conf file.

You'll also want to use

AllowOverride All

in your .conf file for the domain so Apache looks at it.

check if directory exists and delete in one command unix

Assuming $WORKING_DIR is set to the directory... this one-liner should do it:

if [ -d "$WORKING_DIR" ]; then rm -Rf $WORKING_DIR; fi

(otherwise just replace with your directory)

What is a thread exit code?

As Sayse mentioned, exit code 259 (0x103) has special meaning, in this case the process being debugged is still running.

I saw this a lot with debugging web services, because the thread continues to run after executing each web service call (as it is still listening for further calls).

IndentationError: unexpected indent error

While the indentation errors are obvious in the StackOverflow page, they may not be in your editor. You have a mix of different indentation types here, 1, 4 and 8 spaces. You should always use four spaces for indentation, as per PEP8. You should also avoid mixing tabs and spaces.

I also recommend that you try to run your script using the '-tt' command-line option to determine when you accidentally mix tabs and spaces. Of course any decent editor will be able to highlight tabs versus spaces (such as Vim's 'list' option).

How to pass a callback as a parameter into another function

Yup. Function references are just like any other object reference, you can pass them around to your heart's content.

Here's a more concrete example:

_x000D_
_x000D_
function foo() {
    console.log("Hello from foo!");
}

function caller(f) {
    // Call the given function
    f();
}

function indirectCaller(f) {
    // Call `caller`, who will in turn call `f`
    caller(f);
}

// Do it
indirectCaller(foo); // logs "Hello from foo!"
_x000D_
_x000D_
_x000D_

You can also pass in arguments for foo:

_x000D_
_x000D_
function foo(a, b) {
    console.log(a + " + " + b + " = " + (a + b));
}

function caller(f, v1, v2) {
    // Call the given function
    f(v1, v2);
}

function indirectCaller(f, v1, v2) {
    // Call `caller`, who will in turn call `f`
    caller(f, v1, v2);
}

// Do it
indirectCaller(foo, 1, 2); // logs "1 + 2 = 3"
_x000D_
_x000D_
_x000D_

Shell command to sum integers, one per line?

BASH solution, if you want to make this a command (e.g. if you need to do this frequently):

addnums () {
  local total=0
  while read val; do
    (( total += val ))
  done
  echo $total
}

Then usage:

addnums < /tmp/nums

Makefiles with source files in different directories

RC's post was SUPER useful. I never thought about using the $(dir $@) function, but it did exactly what I needed it to do.

In parentDir, have a bunch of directories with source files in them: dirA, dirB, dirC. Various files depend on the object files in other directories, so I wanted to be able to make one file from within one directory, and have it make that dependency by calling the makefile associated with that dependency.

Essentially, I made one Makefile in parentDir that had (among many other things) a generic rule similar to RC's:

%.o : %.cpp
        @mkdir -p $(dir $@)
        @echo "============="
        @echo "Compiling $<"
        @$(CC) $(CFLAGS) -c $< -o $@

Each subdirectory included this upper-level makefile in order to inherit this generic rule. In each subdirectory's Makefile, I wrote a custom rule for each file so that I could keep track of everything that each individual file depended on.

Whenever I needed to make a file, I used (essentially) this rule to recursively make any/all dependencies. Perfect!

NOTE: there's a utility called "makepp" that seems to do this very task even more intuitively, but for the sake of portability and not depending on another tool, I chose to do it this way.

Hope this helps!

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

I recently ran into this issue for a different reason: I was running some tests synchronously using jest -i, and it would just timeout. For whatever reasoning, running the same tests using jest --runInBand (even though -i is meant to be an alias) doesn't time out.

Maybe this will help someone ¯\_(:/)_/¯

Insert new item in array on any position in PHP

Solution by jay.lee is perfect. In case you want to add item(s) to a multidimensional array, first add a single dimensional array and then replace it afterwards.

$original = (
[0] => Array
    (
        [title] => Speed
        [width] => 14
    )

[1] => Array
    (
        [title] => Date
        [width] => 18
    )

[2] => Array
    (
        [title] => Pineapple
        [width] => 30
     )
)

Adding an item in same format to this array will add all new array indexes as items instead of just item.

$new = array(
    'title' => 'Time',
    'width' => 10
);
array_splice($original,1,0,array('random_string')); // can be more items
$original[1] = $new;  // replaced with actual item

Note: Adding items directly to a multidimensional array with array_splice will add all its indexes as items instead of just that item.

How to insert a text at the beginning of a file?

my two cents:

sed  -i '1i /path/of/file.sh' filename

This will work even is the string containing forward slash "/"

Switch tabs using Selenium WebDriver with Java

To get parent window handles.

String parentHandle = driverObj.getWindowHandle();
public String switchTab(String parentHandle){
    String currentHandle ="";
    Set<String> win  = ts.getDriver().getWindowHandles();   

    Iterator<String> it =  win.iterator();
    if(win.size() > 1){
        while(it.hasNext()){
            String handle = it.next();
            if (!handle.equalsIgnoreCase(parentHandle)){
                ts.getDriver().switchTo().window(handle);
                currentHandle = handle;
            }
        }
    }
    else{
        System.out.println("Unable to switch");
    }
    return currentHandle;
}

WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."

I faced this problem

Forbidden You don't have permission to access /phpmyadmin/ on this server

Some help about this:

First check you installed a fresh wamp or replace the existing one. If it's fresh there is no problem, For done existing installation.

Follow these steps.

  1. Open your wamp\bin\mysql directory
  2. Check if in this folder there is another folder of mysql with different name, if exists delete it.
  3. enter to remain mysql folder and delete files with duplication.
  4. start your wamp server again. Wamp will be working.

How to extract text from a PDF file?

The below code is a solution to the question in Python 3. Before running the code, make sure you have installed the PyPDF2 library in your environment. If not installed, open the command prompt and run the following command:

pip3 install PyPDF2

Solution Code:

import PyPDF2
pdfFileObject = open('sample.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObject)
count = pdfReader.numPages
for i in range(count):
    page = pdfReader.getPage(i)
    print(page.extractText())

Best /Fastest way to read an Excel Sheet into a DataTable?

''' <summary>
''' ReadToDataTable reads the given Excel file to a datatable.
''' </summary>
''' <param name="table">The table to be populated.</param>
''' <param name="incomingFileName">The file to attempt to read to.</param>
''' <returns>TRUE if success, FALSE otherwise.</returns>
''' <remarks></remarks>
Public Function ReadToDataTable(ByRef table As DataTable,
                                incomingFileName As String) As Boolean
    Dim returnValue As Boolean = False
    Try

        Dim sheetName As String = ""
        Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & incomingFileName & ";Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
        Dim tablesInFile As DataTable
        Dim oleExcelCommand As OleDbCommand
        Dim oleExcelReader As OleDbDataReader
        Dim oleExcelConnection As OleDbConnection

        oleExcelConnection = New OleDbConnection(connectionString)
        oleExcelConnection.Open()

        tablesInFile = oleExcelConnection.GetSchema("Tables")

        If tablesInFile.Rows.Count > 0 Then
            sheetName = tablesInFile.Rows(0)("TABLE_NAME").ToString
        End If

        If sheetName <> "" Then

            oleExcelCommand = oleExcelConnection.CreateCommand()
            oleExcelCommand.CommandText = "Select * From [" & sheetName & "]"
            oleExcelCommand.CommandType = CommandType.Text

            oleExcelReader = oleExcelCommand.ExecuteReader

            'Determine what row of the Excel file we are on
            Dim currentRowIndex As Integer = 0

            While oleExcelReader.Read
                'If we are on the First Row, then add the item as Columns in the DataTable
                If currentRowIndex = 0 Then
                    For currentFieldIndex As Integer = 0 To (oleExcelReader.VisibleFieldCount - 1)
                        Dim currentColumnName As String = oleExcelReader.Item(currentFieldIndex).ToString
                        table.Columns.Add(currentColumnName, GetType(String))
                        table.AcceptChanges()
                    Next
                End If
                'If we are on a Row with Data, add the data to the SheetTable
                If currentRowIndex > 0 Then
                    Dim newRow As DataRow = table.NewRow
                    For currentFieldIndex As Integer = 0 To (oleExcelReader.VisibleFieldCount - 1)
                        Dim currentColumnName As String = table.Columns(currentFieldIndex).ColumnName
                        newRow(currentColumnName) = oleExcelReader.Item(currentFieldIndex)
                        If IsDBNull(newRow(currentFieldIndex)) Then
                            newRow(currentFieldIndex) = ""
                        End If
                    Next
                    table.Rows.Add(newRow)
                    table.AcceptChanges()
                End If

                'Increment the CurrentRowIndex
                currentRowIndex += 1
            End While

            oleExcelReader.Close()

        End If

        oleExcelConnection.Close()
        returnValue = True
    Catch ex As Exception
        'LastError = ex.ToString
        Return False
    End Try


    Return returnValue
End Function

Remove all values within one list from another list?

I was looking for fast way to do the subject, so I made some experiments with suggested ways. And I was surprised by results, so I want to share it with you.

Experiments were done using pythonbenchmark tool and with

a = range(1,50000) # Source list
b = range(1,15000) # Items to remove

Results:

 def comprehension(a, b):
     return [x for x in a if x not in b]

5 tries, average time 12.8 sec

def filter_function(a, b):
    return filter(lambda x: x not in b, a)

5 tries, average time 12.6 sec

def modification(a,b):
    for x in b:
        try:
            a.remove(x)
        except ValueError:
            pass
    return a

5 tries, average time 0.27 sec

def set_approach(a,b):
    return list(set(a)-set(b))

5 tries, average time 0.0057 sec

Also I made another measurement with bigger inputs size for the last two functions

a = range(1,500000)
b = range(1,100000)

And the results:

For modification (remove method) - average time is 252 seconds For set approach - average time is 0.75 seconds

So you can see that approach with sets is significantly faster than others. Yes, it doesn't keep similar items, but if you don't need it - it's for you. And there is almost no difference between list comprehension and using filter function. Using 'remove' is ~50 times faster, but it modifies source list. And the best choice is using sets - it's more than 1000 times faster than list comprehension!

Parsing xml using powershell

First step is to load your xml string into an XmlDocument, using powershell's unique ability to cast strings to [xml]

$doc = [xml]@'
<xml>
    <Section name="BackendStatus">
        <BEName BE="crust" Status="1" />
        <BEName BE="pizza" Status="1" />
        <BEName BE="pie" Status="1" />
        <BEName BE="bread" Status="1" />
        <BEName BE="Kulcha" Status="1" />
        <BEName BE="kulfi" Status="1" />
        <BEName BE="cheese" Status="1" />
    </Section>
</xml>
'@

Powershell makes it really easy to parse xml with the dot notation. This statement will produce a sequence of XmlElements for your BEName elements:

$doc.xml.Section.BEName

Then you can pipe these objects into the where-object cmdlet to filter down the results. You can use ? as a shortcut for where

$doc.xml.Section.BEName | ? { $_.Status -eq 1 }

The expression inside the braces will be evaluated for each XmlElement in the pipeline, and only those that have a Status of 1 will be returned. The $_ operator refers to the current object in the pipeline (an XmlElement).

If you need to do something for every object in your pipeline, you can pipe the objects into the foreach-object cmdlet, which executes a block for every object in the pipeline. % is a shortcut for foreach:

$doc.xml.Section.BEName | ? { $_.Status -eq 1 } | % { $_.BE + " is delicious" }

Powershell is great at this stuff. It's really easy to assemble pipelines of objects, filter pipelines, and do operations on each object in the pipeline.

What uses are there for "placement new"?

It is useful if you are building a kernel - where do you place the kernel code you read from disk or the pagetable? You need to know where to jump to.

Or in other, very rare circumstances such as when you have loads of allocated room and want to place a few structures behind each other. They can be packed this way without the need for the offsetof() operator. There are other tricks for that too, though.

I also believe some STL implementations make use of placement new, like std::vector. They allocate room for 2^n elements that way and don't need to always realloc.

Python can't find module in the same folder

Change your import in test.py to:

from .hello import hello1

Two values from one input in python?

In Python 2.*, input lets the user enter any expression, e.g. a tuple:

>>> a, b = input('Two numbers please (with a comma in between): ')
Two numbers please (with a comma in between): 23, 45
>>> print a, b
23 45

In Python 3.*, input is like 2.*'s raw_input, returning you a string that's just what the user typed (rather than evaling it as 2.* used to do on input), so you'll have to .split, and/or eval, &c but you'll also be MUCH more in control of the whole thing.

ldconfig error: is not a symbolic link

I ran into this issue with the Oracle 11R2 client. Not sure if the Oracle installer did this or someone did it here before i arrived. It was not 64-bit vs 32-bit, all was 64-bit.

The error was that libexpat.so.1 was not a symbolic link.

It turned out that there were two identical files, libexpat.so.1.5.2 and libexpat.so.1. Removing the offending file and making it a symlink to the 1.5.2 version caused the error to go away.

Makes sense that you'd want the well-known name to be a symlink to the current version. If you do this, it's less likely that you'll end up with a stale library.

Creating a JSON array in C#

You'd better create some class for each item instead of using anonymous objects. And in object you're serializing you should have array of those items. E.g.:

public class Item
{
    public string name { get; set; }
    public string index { get; set; }
    public string optional { get; set; }
}

public class RootObject
{
    public List<Item> items { get; set; }
}

Usage:

var objectToSerialize = new RootObject();
objectToSerialize.items = new List<Item> 
                          {
                             new Item { name = "test1", index = "index1" },
                             new Item { name = "test2", index = "index2" }
                          };

And in the result you won't have to change things several times if you need to change data-structure.

p.s. Here's very nice tool for complex jsons

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

Store an array in HashMap

You can store objects in a HashMap.

HashMap<String, Object> map = new HashMap<String, Object>();

You'll just need to cast it back out correctly.

Convert integer value to matching Java Enum

I know this question is a few years old, but as Java 8 has, in the meantime, brought us Optional, I thought I'd offer up a solution using it (and Stream and Collectors):

public enum PcapLinkType {
  DLT_NULL(0),
  DLT_EN3MB(2),
  DLT_AX25(3),
  /*snip, 200 more enums, not always consecutive.*/
  // DLT_UNKNOWN(-1); // <--- NO LONGER NEEDED

  private final int value;
  private PcapLinkType(int value) { this.value = value; }

  private static final Map<Integer, PcapLinkType> map;
  static {
    map = Arrays.stream(values())
        .collect(Collectors.toMap(e -> e.value, e -> e));
  }

  public static Optional<PcapLinkType> fromInt(int value) {
    return Optional.ofNullable(map.get(value));
  }
}

Optional is like null: it represents a case when there is no (valid) value. But it is a more type-safe alternative to null or a default value such as DLT_UNKNOWN because you could forget to check for the null or DLT_UNKNOWN cases. They are both valid PcapLinkType values! In contrast, you cannot assign an Optional<PcapLinkType> value to a variable of type PcapLinkType. Optional makes you check for a valid value first.

Of course, if you want to retain DLT_UNKNOWN for backward compatibility or whatever other reason, you can still use Optional even in that case, using orElse() to specify it as the default value:

public enum PcapLinkType {
  DLT_NULL(0),
  DLT_EN3MB(2),
  DLT_AX25(3),
  /*snip, 200 more enums, not always consecutive.*/
  DLT_UNKNOWN(-1);

  private final int value;
  private PcapLinkType(int value) { this.value = value; }

  private static final Map<Integer, PcapLinkType> map;
  static {
    map = Arrays.stream(values())
        .collect(Collectors.toMap(e -> e.value, e -> e));
  }

  public static PcapLinkType fromInt(int value) {
    return Optional.ofNullable(map.get(value)).orElse(DLT_UNKNOWN);
  }
}

Using UPDATE in stored procedure with optional parameters

UPDATE tbl_ClientNotes 
SET ordering=@ordering, title=@title, content=@content 
WHERE id=@id 
AND @ordering IS NOT NULL
AND @title IS NOT NULL
AND @content IS NOT NULL

Or if you meant you only want to update individual columns you would use the post above mine. I read it as do not update if any values are null

PostgreSQL - max number of parameters in "IN" clause?

Just tried it. the answer is -> out-of-range integer as a 2-byte value: 32768

Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified?

I've investigated this issue, referring to the LayoutInflater docs and setting up a small sample demonstration project. The following tutorials shows how to dynamically populate a layout using LayoutInflater.

Before we get started see what LayoutInflater.inflate() parameters look like:

  • resource: ID for an XML layout resource to load (e.g., R.layout.main_page)
  • root: Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)
  • attachToRoot: Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.

  • Returns: The root View of the inflated hierarchy. If root was supplied and attachToRoot is true, this is root; otherwise it is the root of the inflated XML file.

Now for the sample layout and code.

Main layout (main.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</LinearLayout>

Added into this container is a separate TextView, visible as small red square if layout parameters are successfully applied from XML (red.xml):

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="25dp"
    android:layout_height="25dp"
    android:background="#ff0000"
    android:text="red" />

Now LayoutInflater is used with several variations of call parameters

public class InflaterTest extends Activity {

    private View view;

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      setContentView(R.layout.main);
      ViewGroup parent = (ViewGroup) findViewById(R.id.container);

      // result: layout_height=wrap_content layout_width=match_parent
      view = LayoutInflater.from(this).inflate(R.layout.red, null);
      parent.addView(view);

      // result: layout_height=100 layout_width=100
      view = LayoutInflater.from(this).inflate(R.layout.red, null);
      parent.addView(view, 100, 100);

      // result: layout_height=25dp layout_width=25dp
      // view=textView due to attachRoot=false
      view = LayoutInflater.from(this).inflate(R.layout.red, parent, false);
      parent.addView(view);

      // result: layout_height=25dp layout_width=25dp 
      // parent.addView not necessary as this is already done by attachRoot=true
      // view=root due to parent supplied as hierarchy root and attachRoot=true
      view = LayoutInflater.from(this).inflate(R.layout.red, parent, true);
    }
}

The actual results of the parameter variations are documented in the code.

SYNOPSIS: Calling LayoutInflater without specifying root leads to inflate call ignoring the layout parameters from the XML. Calling inflate with root not equal null and attachRoot=true does load the layout parameters, but returns the root object again, which prevents further layout changes to the loaded object (unless you can find it using findViewById()). The calling convention you most likely would like to use is therefore this one:

loadedView = LayoutInflater.from(context)
                .inflate(R.layout.layout_to_load, parent, false);

To help with layout issues, the Layout Inspector is highly recommended.

How to find prime numbers between 0 - 100?

You can try this method also, this one is basic but easy to understand:

 var tw = 2, th = 3, fv = 5, se = 7; 

 document.write(tw + "," + th + ","+ fv + "," + se + ",");


for(var n = 0; n <= 100; n++)
{

  if((n % tw !== 0) && (n % th !==0) && (n % fv !==0 ) && (n % se !==0))

  {
      if (n == 1)
      {
          continue;
      }

    document.write(n +",");
  }
}

Jquery- Get the value of first td in table

If you need to get all td's inside tr without defining id for them, you can use the code below :

var items = new Array();

$('#TABLE_ID td:nth-child(1)').each(function () {
      items.push($(this).html());
});

The code above will add all first cells inside the Table into an Array variable.

you can change nth-child(1) which means the first cell to any cell number you need.

hope this code helps you.

Objective-C: Extract filename from path string

Taken from the NSString reference, you can use :

NSString *theFileName = [[string lastPathComponent] stringByDeletingPathExtension];

The lastPathComponent call will return thefile.ext, and the stringByDeletingPathExtension will remove the extension suffix from the end.

How do I change the value of a global variable inside of a function

Just use the name of that variable.

In JavaScript, variables are only local to a function, if they are the function's parameter(s) or if you declare them as local explicitely by typing the var keyword before the name of the variable.

If the name of the local value has the same name as the global value, use the window object

See this jsfiddle

_x000D_
_x000D_
x = 1;_x000D_
y = 2;_x000D_
z = 3;_x000D_
_x000D_
function a(y) {_x000D_
  // y is local to the function, because it is a function parameter_x000D_
  console.log('local y: should be 10:', y); // local y through function parameter_x000D_
  y = 3; // will only overwrite local y, not 'global' y_x000D_
  console.log('local y: should be 3:', y); // local y_x000D_
  // global value could be accessed by referencing through window object_x000D_
  console.log('global y: should be 2:', window.y) // global y, different from local y ()_x000D_
_x000D_
  var x; // makes x a local variable_x000D_
  x = 4; // only overwrites local x_x000D_
  console.log('local x: should be 4:', x); // local x_x000D_
  _x000D_
  z = 5; // overwrites global z, because there is no local z_x000D_
  console.log('local z: should be 5:', z); // local z, same as global_x000D_
  console.log('global z: should be 5 5:', window.z, z) // global z, same as z, because z is not local_x000D_
}_x000D_
a(10);_x000D_
console.log('global x: should be 1:', x); // global x_x000D_
console.log('global y: should be 2:', y); // global y_x000D_
console.log('global z: should be 5:', z); // global z, overwritten in function a
_x000D_
_x000D_
_x000D_

Edit

With ES2015 there came two more keywords const and let, which also affect the scope of a variable (Language Specification)

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

How to use MySQLdb with Python and Django in OSX 10.6?

This issue was the result of an incomplete / incorrect installation of the MySQL for Python adapter. Specifically, I had to edit the path to the mysql_config file to point to /usr/local/mysql/bin/mysql_config - discussed in greater detail in this article: http://dakrauth.com/blog/entry/python-and-django-setup-mac-os-x-leopard/

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

For me i was getting this error because i needed to put the arrays in paratheses. The error is a bit tricky in this case...

ie. concatenate((a, b)) is right

not concatenate(a, b)

hope that helps.

How to resolve conflicts in EGit

Just right click on a conflicting file and add it to the index after resolving conflicts.

create table with sequence.nextval in oracle

In Oracle 12c you can also declare an identity column

CREATE TABLE identity_test_tab (
  id          NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
  description VARCHAR2(30)
);

examples & performance tests here ... where, is shorts, the conclusion is that the direct use of the sequence or the new identity column are much faster than the triggers.

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

In VB:

from m in MyTable
take 10
select m.Foo

This assumes that MyTable implements IQueryable. You may have to access that through a DataContext or some other provider.

It also assumes that Foo is a column in MyTable that gets mapped to a property name.

See http://blogs.msdn.com/vbteam/archive/2008/01/08/converting-sql-to-linq-part-7-union-top-subqueries-bill-horst.aspx for more detail.

Find all elements with a certain attribute value in jquery

$('div[imageId="imageN"]').each(function() {
    // `this` is the div
});

To check for the sole existence of the attribute, no matter which value, you could use ths selector instead: $('div[imageId]')

Generating a unique machine id

What about just using the UniqueID of the processor?

adding directory to sys.path /PYTHONPATH

You could use:

import os
path = 'the path you want'
os.environ['PATH'] += ':'+path

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

SELECT Id   'PatientId',
       ISNULL(CONVERT(varchar(50),ParentId),'')  'ParentId'
FROM Patients

ISNULL always tries to return a result that has the same data type as the type of its first argument. So, if you want the result to be a string (varchar), you'd best make sure that's the type of the first argument.


COALESCE is usually a better function to use than ISNULL, since it considers all argument data types and applies appropriate precedence rules to determine the final resulting data type. Unfortunately, in this case, uniqueidentifier has higher precedence than varchar, so that doesn't help.

(It's also generally preferred because it extends to more than two arguments)

How to actually search all files in Visual Studio

One can access the "Find in Files" window via the drop-down menu selection and search all files in the Entire Solution: Edit > Find and Replace > Find in Files

enter image description here

Other, alternative is to open the "Find in Files" window via the "Standard Toolbars" button as highlighted in the below screen-short:

enter image description here

search in java ArrayList

Even if that topic is quite old, I'd like to add something. If you overwrite equals for you classes, so it compares your getId, you can use:

customer = new Customer(id);
customers.get(customers.indexOf(customer));

Of course, you'd have to check for an IndexOutOfBounds-Exception, which oculd be translated into a null pointer or a custom CustomerNotFoundException.

How to store arrays in MySQL?

A sidenote to consider, you can store arrays in Postgres.

How to read a text file?

It depends on what you are trying to do.

file, err := os.Open("file.txt")
fmt.print(file)

The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File), not file-content. To obtain file-content, you may READ from a file-descriptor.


To read all file content(in bytes) to memory, ioutil.ReadAll

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


  b, err := ioutil.ReadAll(file)
  fmt.Print(b)
}

But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read from *os.File

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


    buf := make([]byte, 32*1024) // define your buffer size here.

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n]) // your read buffer.
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }

}

Otherwise, you could also use the standard util package: bufio, try Scanner. A Scanner reads your file in tokens: separator.

By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {             // internally, it advances token based on sperator
        fmt.Println(scanner.Text())  // token in unicode-char
        fmt.Println(scanner.Bytes()) // token in bytes

    }
}

Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

No need for cut or magic, in bash you can cut a string like so:

  ORGSTRING="123456"
  CUTSTRING=${ORGSTRING:0:-3}
  echo "The original string: $ORGSTRING"
  echo "The new, shorter and faster string: $CUTSTRING"

See http://tldp.org/LDP/abs/html/string-manipulation.html

Convert a string to datetime in PowerShell

You can simply cast strings to DateTime:

[DateTime]"2020-7-16"

or

[DateTime]"Jul-16"

or

$myDate = [DateTime]"Jul-16";

And you can format the resulting DateTime variable by doing something like this:

'{0:yyyy-MM-dd}' -f [DateTime]'Jul-16'

or

([DateTime]"Jul-16").ToString('yyyy-MM-dd')

or

$myDate = [DateTime]"Jul-16";
'{0:yyyy-MM-dd}' -f $myDate

Tomcat won't stop or restart

You can always try to kill the process in case you see this kind of issues. You can get the process ID either from PS or from pid file and kill the process.

How to add an onchange event to a select box via javascript?

replace:

transport_select.onChange = function(){toggleSelect(transport_select_id);};

with:

transport_select.onchange = function(){toggleSelect(transport_select_id);};

on'C'hange >> on'c'hange


You can use addEventListener too.

Parenthesis/Brackets Matching using Stack algorithm

Your code has some confusion in its handling of the '{' and '}' characters. It should be entirely parallel to how you handle '(' and ')'.

This code, modified slightly from yours, seems to work properly:

public static boolean isParenthesisMatch(String str) {
    if (str.charAt(0) == '{')
        return false;

    Stack<Character> stack = new Stack<Character>();

    char c;
    for(int i=0; i < str.length(); i++) {
        c = str.charAt(i);

        if(c == '(')
            stack.push(c);
        else if(c == '{')
            stack.push(c);
        else if(c == ')')
            if(stack.empty())
                return false;
            else if(stack.peek() == '(')
                stack.pop();
            else
                return false;
        else if(c == '}')
            if(stack.empty())
                return false;
            else if(stack.peek() == '{')
                stack.pop();
            else
                return false;
    }
    return stack.empty();
}

First char to upper case

userIdeaUC = userIdea.substring(0, 1).toUpperCase() + userIdea.length() > 1 ? userIdea.substring(1) : "";

or

userIdeaUC = userIdea.substring(0, 1).toUpperCase();
if(userIdea.length() > 1)
   userIdeaUC += userIdea.substring(1);

How to unset a JavaScript variable?

@scunlife's answer will work, but technically it ought to be

delete window.some_var; 

delete is supposed to be a no-op when the target isn't an object property. e.g.,

(function() {
   var foo = 123;
   delete foo; // wont do anything, foo is still 123
   var bar = { foo: 123 };
   delete bar.foo; // foo is gone
}());

But since global variables are actually members of the window object, it works.

When prototype chains are involved, using delete gets more complex because it only removes the property from the target object, and not the prototype. e.g.,

function Foo() {}
Foo.prototype = { bar: 123 };
var foo = new Foo();
// foo.bar is 123
foo.bar = 456;
// foo.bar is now 456
delete foo.bar;
// foo.bar is 123 again.

So be careful.

EDIT: My answer is somewhat inaccurate (see "Misconceptions" at the end). The link explains all the gory details, but the summary is that there can be big differences between browsers and depending on the object you are deleting from. delete object.someProp should generally be safe as long as object !== window. I still wouldn't use it to delete variables declared with var although you can under the right circumstances.

What does @@variable mean in Ruby?

@ - Instance variable of a class
@@ - Class variable, also called as static variable in some cases

A class variable is a variable that is shared amongst all instances of a class. This means that only one variable value exists for all objects instantiated from this class. If one object instance changes the value of the variable, that new value will essentially change for all other object instances.

Another way of thinking of thinking of class variables is as global variables within the context of a single class. Class variables are declared by prefixing the variable name with two @ characters (@@). Class variables must be initialized at creation time

Messagebox with input field

You can reference Microsoft.VisualBasic.dll.

Then using the code below.

Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");

Alternatively, by adding a using directive allowing for a shorter syntax in your code (which I'd personally prefer).

using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");

Or you can do what Pranay Rana suggests, that's what I would've done too...

How to change the default collation of a table?

It sets the default collation for the table; if you create a new column, that should be collated with latin_general_ci -- I think. Try specifying the collation for the individual column and see if that works. MySQL has some really bizarre behavior in regards to the way it handles this.

document .click function for touch device

can you use jqTouch or jquery mobile ? there it's much easier to handle touch events. If not then you need to simulate click on touch device, follow this articles:

iphone-touch-events-in-javascript

A touch demo

More in this thread

What are the differences between a HashMap and a Hashtable in Java?

Hashtable is synchronized, whereas HashMap isn't. That makes Hashtable slower than Hashmap.

For single thread applications, use HashMap since they are otherwise the same in terms of functionality.

Substitute a comma with a line break in a cell

You can also do this without VBA from the find/replace dialogue box. My answer was at https://stackoverflow.com/a/6116681/509840 .

How to convert entire dataframe to numeric while preserving decimals?

Using dplyr (a bit like sapply..)

df2 <- mutate_all(df1, function(x) as.numeric(as.character(x)))

which gives:

glimpse(df2)
Observations: 4
Variables: 2
$ a <dbl> 0.01, 0.02, 0.03, 0.04
$ b <dbl> 2, 4, 5, 7

from your df1 which was:

glimpse(df1)
Observations: 4
Variables: 2
$ a <fctr> 0.01, 0.02, 0.03, 0.04
$ b <dbl> 2, 4, 5, 7

How to call a method function from another class?

You need to instantiate the other classes inside the main class;

Date d = new Date(params);
TemperatureRange t = new TemperatureRange(params);

You can then call their methods with:

object.methodname(params);
d.method();

You currently have constructors in your other classes. You should not return anything in these.

public Date(params){
    set variables for date object
}

Next you need a method to reference.

public returnType methodName(params){
  return something;
}

jQuery count number of divs with a certain class?

And for the plain js answer if anyone might be interested;

var count = document.getElementsByClassName("item");

Cheers.

Reference: https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp

Facebook page automatic "like" URL (for QR Code)

In my opinion, it is not possible for the like button (and I hope it is not possible).

But, you can trigger a custom OpenGraph v2 action, or display a like button linked to your facebook page.

Stock ticker symbol lookup API

Use YQL and you don't need to worry. It's a query language by Yahoo and you can get all the stock data including the name of the company for the ticker. It's a REST API and it returns the results via XML or JSON. I have a full tutorial and source code on my site take a look: http://www.jarloo.com/yahoo-stock-symbol-lookup/

How can I align the columns of tables in Bash?

Not sure where you were running this, but the code you posted would not produce the output you gave, at least not in the bash that I'm familiar with.

Try this instead:

stringarray=('test' 'some thing' 'very long long long string' 'blah')
numberarray=(1 22 7777 8888888888)
anotherfieldarray=('other' 'mixed' 456 'data')
array_size=4

for((i=0;i<array_size;i++))
do
    echo ${stringarray[$i]} $'\x1d' ${numberarray[$i]} $'\x1d' ${anotherfieldarray[$i]}
done | column -t -s$'\x1d'

Note that I'm using the group seperator character (1d) intead of tab, because if you are getting these arrays from a file, they might contain tabs.

PHP exec() vs system() vs passthru()

They have slightly different purposes.

  • exec() is for calling a system command, and perhaps dealing with the output yourself.
  • system() is for executing a system command and immediately displaying the output - presumably text.
  • passthru() is for executing a system command which you wish the raw return from - presumably something binary.

Regardless, I suggest you not use any of them. They all produce highly unportable code.

How to redirect siteA to siteB with A or CNAME records

You can only make DNS name pont to a different IP address, so if You you are using virtual hosts redirecting with DNS won't work.

When you enter subdomain.hostone.com in your browser it will use DNS to get it's IP address (if it's a CNAME it will continue trying until it gets IP from A record) then it will connect to that IP and send a http request with

Host: subdomain.hostone.com 

somewhere in the http headers.

What are alternatives to ExtJS?

Nothing compares to in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.

Have in mind also that,

large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.

-- Announcement of YUI development being ceased

That said, below are a number of Ext JS alternatives currently available.

Leading client widget libraries

  1. Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.

    Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.

    Sandbox / demoGitHubDocs

  2. Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.

    Webix

    Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.

    Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.

    The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).

    The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.

    Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.

    WikipediaGitHubPlayground/sandboxAdmin dashboard demoDemosWidget samples

  3. react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.

  4. - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).

    enter image description here

    Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.

    A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.

    [Wikipedia] • GitHub/TelerikDemosPlaygroundTools

  5. OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.

    OpenUI5

    The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.

    The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.

    WikipediaGitHubMobile-first controls demosDesktop controls demosSO

  6. DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.

    DHTMLX

    Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.

  7. Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.

    Polymer Paper Elements

  8. Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).

    The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.

  9. PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.

  10. qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).

    Mobile themes look modern but desktop themes look old (gradients).

    Qooxdoo

    WikipediaGitHubWeb/Mobile/Desktop demosWidgets Demo browserWidget browserSOPlaygroundCommunity

  11. jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.

  12. + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).

  13. DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.

    Dojo Dijit

    Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.

    Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.

    With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.

    WikipediaGitHubThemesDemosDesktop widgetsSO

  14. Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.

  15. The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM

  16. Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.

  17. CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.

  18. ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.

  19. Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.

  20. CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.

CxJS

Widgets - Demo Apps - Examples - GitHub

Full-stack frameworks

  1. SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.

  2. Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:

  3. Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.

  4. SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.

  5. Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework

  6. Backbase - portal software

  7. Shiny - front-end library on top R, with visualization, layout and control widgets

  8. ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.

CSS libraries + minimal widgets

These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.

  1. Bootstrap

  2. Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library

  3. UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.

Libraries using HTML Canvas

Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.

  1. Zebra - demos

No longer developed as of Dec 2014

  1. Yahoo! User Interface - YUI, launched in 2005, but no longer maintained by the core contributors - see the announcement, which highlights reasons why large UI widget libraries are perceived as walled gardens that developers don't want to be locked into.
  2. echo3, GitHub. Supports writing either server-side Java applications that don't require developer knowledge of HTML, HTTP, or JavaScript, or client-side JavaScript-based applications do not require a server, but can communicate with one via AJAX. Last update: July 2013.
  3. ampleSDK
  4. Simpler widgets livepipe.net
  5. JxLib
  6. rialto
  7. Simple UI kit
  8. Prototype-ui

Other lists

Escape regex special characters in a Python string

As it was mentioned above, the answer depends on your case. If you want to escape a string for a regular expression then you should use re.escape(). But if you want to escape a specific set of characters then use this lambda function:

>>> escape = lambda s, escapechar, specialchars: "".join(escapechar + c if c in specialchars or c == escapechar else c for c in s)
>>> s = raw_input()
I'm "stuck" :\
>>> print s
I'm "stuck" :\
>>> print escape(s, "\\", ['"'])
I'm \"stuck\" :\\

Lint: How to ignore "<key> is not translated in <language>" errors?

If you want to turn off the warnings about the specific strings, you can use the following:

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>    

    <!--suppress MissingTranslation -->
    <string name="some_string">ignore my translation</string>
    ...

</resources>

If you want to warn on specific strings instead of an error, you will need to build a custom Lint rule to adjust the severity status for a specific thing.

http://tools.android.com/tips/lint-custom-rules

Error in if/while (condition) {: missing Value where TRUE/FALSE needed

this works with "NA" not for NA

comments = c("no","yes","NA")
  for (l in 1:length(comments)) {
    #if (!is.na(comments[l])) print(comments[l])
    if (comments[l] != "NA") print(comments[l])
  }

The requested resource does not support HTTP method 'GET'

In my case, the route signature was different from the method parameter. I had id, but I was accepting documentId as parameter, that caused the problem.

[Route("Documents/{id}")]   <--- caused the webapi error
[Route("Documents/{documentId}")] <-- solved
public Document Get(string documentId)
{
  ..
}

R memory management / cannot allocate vector of size n Mb

The save/load method mentioned above works for me. I am not sure how/if gc() defrags the memory but this seems to work.

# defrag memory 
save.image(file="temp.RData")
rm(list=ls())
load(file="temp.RData")

"UnboundLocalError: local variable referenced before assignment" after an if statement

FWIW: I got the same error for a different reason. I post the answer here not for the benefit of the OP, but for the benefit of those who may end up on this page due to its title... who might have made the same mistake I did.

I was confused why I was getting "local variable referenced before assignment" because I was calling a FUNCTION that I knew was already defined:

def job_fn(job):
  return job + ".job"

def do_something():
  a = 1
  b = 2
  job_fn = job_fn("foo")

do_something()

This was giving:

UnboundLocalError: local variable 'job_fn' referenced before assignment

Took me a while to see my obvious problem: I used a local variable named job_fn which masked the ability to see the prior function definition for job_fn.

Import CSV file as a pandas DataFrame

Note quite as clean, but:

import csv

with open("value.txt", "r") as f:
    csv_reader = reader(f)
    num = '  '
    for row in csv_reader:
        print num, '\t'.join(row)
        if num == '  ':  
            num=0
        num=num+1

Not as compact, but it does the job:

   Date price   factor_1    factor_2
1 2012-06-11    1600.20 1.255   1.548
2 2012-06-12    1610.02 1.258   1.554
3 2012-06-13    1618.07 1.249   1.552
4 2012-06-14    1624.40 1.253   1.556
5 2012-06-15    1626.15 1.258   1.552
6 2012-06-16    1626.15 1.263   1.558
7 2012-06-17    1626.15 1.264   1.572

How do I remove  from the beginning of a file?

Three words for you:

Byte Order Mark (BOM)

That's the representation for the UTF-8 BOM in ISO-8859-1. You have to tell your editor to not use BOMs or use a different editor to strip them out.

To automatize the BOM's removal you can use awk as shown in this question.

As another answer says, the best would be for PHP to actually interpret the BOM correctly, for that you can use mb_internal_encoding(), like this:

 <?php
   //Storing the previous encoding in case you have some other piece 
   //of code sensitive to encoding and counting on the default value.      
   $previous_encoding = mb_internal_encoding();

   //Set the encoding to UTF-8, so when reading files it ignores the BOM       
   mb_internal_encoding('UTF-8');

   //Process the CSS files...

   //Finally, return to the previous encoding
   mb_internal_encoding($previous_encoding);

   //Rest of the code...
  ?>

Onchange open URL via select - jQuery

**redirect on change option with jquery** 

 <select id="selectnav1" class="selectnav">
            <option value="#">Menu </option>
            <option value="   https://www.google.com">
            Google
            </option>
            <option value="http://stackoverflow.com/">
              stackoverflow
            </option>

         </select>

<script type="text/javascript">
   $(function () {

        $('#selectnav1').change( function() {
      location.href = $(this).val();
   });
   });
</script>

How do you scroll up/down on the console of a Linux VM

ALTERNATIVE FOR LINE-BY-LINE SCROLLING

Ctrl + Shift + Up Arrow or Down Arrow

Unlike Shift + Page Up or Page Down, which scrolls the entire page, this will help with a smoother line-by-line scrolling, which is exactly what I was looking for.

Link to "pin it" on pinterest without generating a button

The standard Pinterest button code (which you can generate here), is an <a> tag wrapping an <img> of the Pinterest button.

If you don't include the pinit.js script on your page, this <a> tag will work "as-is". You could improve the experience by registering your own click handler on these tags that opens a new window with appropriate dimensions, or at least adding target="_blank" to the tag to make it open clicks in a new window.

The tag syntax would look like:

<a href="http://pinterest.com/pin/create/button/?url={URI-encoded URL of the page to pin}&media={URI-encoded URL of the image to pin}&description={optional URI-encoded description}" class="pin-it-button" count-layout="horizontal">
    <img border="0" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" />
</a>

If using the JavaScript versions of sharing buttons are ruining your page load times, you can improve your site by using asynchronous loading methods. For an example of doing this with the Pinterest button, check out my GitHub Pinterest button project with an improved HTML5 syntax.

What's "this" in JavaScript onclick?

In the case you are asking about, this represents the HTML DOM element.

So it would be the <a> element that was clicked on.

Angular2 Routing with Hashtag to page anchor

Use this for the router module in app-routing.module.ts:

@NgModule({
  imports: [RouterModule.forRoot(routes, {
    useHash: true,
    scrollPositionRestoration: 'enabled',
    anchorScrolling: 'enabled',
    scrollOffset: [0, 64]
  })],
  exports: [RouterModule]
})

This will be in your HTML:

<a href="#/users/123#userInfo">

Does it matter what extension is used for SQLite database files?

SQLite doesn't define any particular extension for this, it's your own choice. Personally, I name them with the .sqlite extension, just so there isn't any ambiguity when I'm looking at my files later.

Android Fragment onClick button Method

This is not an issue, this is a design of Android. See here:

You should design each fragment as a modular and reusable activity component. That is, because each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can include one fragment in multiple activities, so you should design for reuse and avoid directly manipulating one fragment from another fragment.

A possible workaround would be to do something like this in your MainActivity:

Fragment someFragment;    

...onCreate etc instantiating your fragments

public void myClickMethod(View v){
    someFragment.myClickMethod(v);
}

and then in your Fragment class:

public void myClickMethod(View v){
    switch(v.getid()){
       // Your code here
    }
 } 

How do you count the elements of an array in java

What I think you may want is an ArrayList<Integer> instead of an array. This will allow you do to:

ArrayList<Integer> arr = new ArrayList<Integer>(20);
System.out.println(arr.size());

The output will be 0.

Then, you can add things to the list, and it will keep track of the count for you. (It will also grow the size of the backing storage as you need as well.)

Why can templates only be implemented in the header file?

If the concern is the extra compilation time and binary size bloat produced by compiling the .h as part of all the .cpp modules using it, in many cases what you can do is make the template class descend from a non-templatized base class for non type-dependent parts of the interface, and that base class can have its implementation in the .cpp file.

How to add/subtract dates with JavaScript?

startdate.setDate(startdate.getDate() - daysToSubtract);


startdate.setDate(startdate.getDate() + daysToAdd);

How do I remove the non-numeric character from a string in java?

Previous answers will strip your decimal point. If you want to save your decimal, you might want to

String str = "My values are : 900.00, 700.00, 650.50";

String[] values = str.split("[^\\d.?\\d]"); 
// split on wherever they are not digits except the '.' decimal point
// values: { "900.00", "700.00", "650.50"}  

New og:image size for Facebook share?

EDIT: The current best practices regarding Open Graph image sizes are officially outlined here: https://developers.facebook.com/docs/sharing/best-practices#images


There was a post in the Facebook developers group today, where one of the FB guys uploaded a PDF containing their new rules about image sizes – since that seems to be available only if you’re a member of the group, I uploaded it here: http://www.sendspace.com/file/ghqwhr

And they also said they will post about it in the developer blog in the coming days, so keep checking there as well

To summarize the linked document:

  • Minimum size in pixels is 600x315
  • Recommended size is 1200x630 - Images this size will get a larger display treatment.
  • Aspect ratio should be 1.91:1

MySQL: Can't create table (errno: 150)

I faced this kind of issue while creating DB from the textfile.

mysql -uroot -padmin < E:\important\sampdb\createdb.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\create_student.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\create_absence.sql

mysql -uroot -padmin sampdb < E:\important\sampdb\insert_student.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\insert_absence.sql

mysql -uroot -padmin sampdb < E:\important\sampdb\load_student.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\load_absence.sql 

I just wrote the above lines in Create.batand run the bat file.

My mistake is in the sequence order of execution in my sql files. I tried to create table with primary key and also foreign key. While its running it will search for the reference table but tables are not there. So it will return those kind of error.

If you creating tables with foreign key then check the reference tables were present or not. And also check the name of the reference tables and fields.

TypeError: unhashable type: 'dict'

You're trying to use a dict as a key to another dict or in a set. That does not work because the keys have to be hashable. As a general rule, only immutable objects (strings, integers, floats, frozensets, tuples of immutables) are hashable (though exceptions are possible). So this does not work:

>>> dict_key = {"a": "b"}
>>> some_dict[dict_key] = True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

To use a dict as a key you need to turn it into something that may be hashed first. If the dict you wish to use as key consists of only immutable values, you can create a hashable representation of it like this:

>>> key = frozenset(dict_key.items())

Now you may use key as a key in a dict or set:

>>> some_dict[key] = True
>>> some_dict
{frozenset([('a', 'b')]): True}

Of course you need to repeat the exercise whenever you want to look up something using a dict:

>>> some_dict[dict_key]                     # Doesn't work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> some_dict[frozenset(dict_key.items())]  # Works
True

If the dict you wish to use as key has values that are themselves dicts and/or lists, you need to recursively "freeze" the prospective key. Here's a starting point:

def freeze(d):
    if isinstance(d, dict):
        return frozenset((key, freeze(value)) for key, value in d.items())
    elif isinstance(d, list):
        return tuple(freeze(value) for value in d)
    return d

What MIME type should I use for CSV?

For anyone struggling with Google API mimeType for *.csv files. I have found the list of MIME types for google api docs files (look at snipped result)

_x000D_
_x000D_
<table border="1"><thead><tr><th>Google Doc Format</th><th>Conversion Format</th><th>Corresponding MIME type</th></tr></thead><tbody><tr><td>Documents</td><td>HTML</td><td>text/html</td></tr><tr></tr><tr><td></td><td>HTML (zipped)</td><td>application/zip</td></tr><tr><td></td><td>Plain text</td><td>text/plain</td></tr><tr><td></td><td>Rich text</td><td>application/rtf</td></tr><tr><td></td><td>Open Office doc</td><td>application/vnd.oasis.opendocument.text</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>MS Word document</td><td>application/vnd.openxmlformats-officedocument.wordprocessingml.document</td></tr><tr><td></td><td>EPUB</td><td>application/epub+zip</td></tr><tr><td>Spreadsheets</td><td>MS Excel</td><td>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</td></tr><tr><td></td><td>Open Office sheet</td><td>application/x-vnd.oasis.opendocument.spreadsheet</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>CSV (first sheet only)</td><td>text/csv</td></tr><tr><td></td><td>TSV (first sheet only)</td><td>text/tab-separated-values</td></tr><tr><td></td><td>HTML (zipped)</td><td>application/zip</td></tr><tr></tr><tr><td>Drawings</td><td>JPEG</td><td>image/jpeg</td></tr><tr><td></td><td>PNG</td><td>image/png</td></tr><tr><td></td><td>SVG</td><td>image/svg+xml</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td>Presentations</td><td>MS PowerPoint</td><td>application/vnd.openxmlformats-officedocument.presentationml.presentation</td></tr><tr><td></td><td>Open Office presentation</td><td>application/vnd.oasis.opendocument.presentation</td></tr><tr></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>Plain text</td><td>text/plain</td></tr><tr><td>Apps Scripts</td><td>JSON</td><td>application/vnd.google-apps.script+json</td></tr></tbody></table>
_x000D_
_x000D_
_x000D_

Source here: https://developers.google.com/drive/v3/web/manage-downloads#downloading_google_documents the table under: "Google Doc formats and supported export MIME types map to each other as follows"

There is also another list

_x000D_
_x000D_
<table border="1"><thead><tr><th>MIME Type</th><th>Description</th></tr></thead><tbody><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>audio</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>document</span></code></td><td>Google Docs</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>drawing</span></code></td><td>Google Drawing</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>file</span></code></td><td>Google Drive file</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>folder</span></code></td><td>Google Drive folder</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>form</span></code></td><td>Google Forms</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>fusiontable</span></code></td><td>Google Fusion Tables</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>map</span></code></td><td>Google My Maps</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>photo</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>presentation</span></code></td><td>Google Slides</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>script</span></code></td><td>Google Apps Scripts</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>site</span></code></td><td>Google Sites</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>spreadsheet</span></code></td><td>Google Sheets</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>unknown</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>video</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>drive-sdk</span></code></td><td>3rd party shortcut</td></tr></tbody></table>
_x000D_
_x000D_
_x000D_

Source here: https://developers.google.com/drive/v3/web/mime-types

But the first one was more helpful for my use case..

Happy coding ;)

call a function in success of datatable ajax call

You can use dataSrc :

Here is a typical example of datatables.net

var table = $('#example').DataTable( {
    "ajax": {
            "type" : "GET",
            "url" : "ajax.php",
            "dataSrc": function ( json ) {
                //Make your callback here.
                alert("Done!");
                return json.data;
            }       
            },
    "columns": [
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "extn" },
            { "data": "start_date" },
            { "data": "salary" }

        ]
    } );

Get page title with Selenium WebDriver using Java

You can do it easily by using JUnit or TestNG framework. Do the assertion as below:

String actualTitle = driver.getTitle();
String expectedTitle = "Title of Page";
assertEquals(expectedTitle,actualTitle);

OR,

assertTrue(driver.getTitle().contains("Title of Page"));

Mysql: Select all data between two dates

You can use as an alternate solution:

SELECT * FROM TABLE_NAME WHERE `date` >= '1-jan-2013' 
OR `date` <= '12-jan-2013'

How can I stage and commit all files, including newly added files, using a single command?

I use this function:

gcaa() { git add --all && git commit -m "$*" }

In my zsh config file, so i can just do:

> gcaa This is the commit message

To automatically stage and commit all files.

Cloning specific branch

I don't think you fully understand how git by default gives you all history of all branches.

git clone --branch master <URL> will give you what you want.

But in fact, in any of the other repos where you ended up with test_1 checked out, you could have just done git checkout master and it would have switched you to the master branch.

(What @CodeWizard says is all true, I just think it's more advanced than what you really need.)

How do I pass multiple parameters into a function in PowerShell?

If you try:

PS > Test("ABC", "GHI") ("DEF")

you get:

$arg1 value: ABC GHI
$arg2 value: DEF

So you see that the parentheses separates the parameters


If you try:

PS > $var = "C"
PS > Test ("AB" + $var) "DEF"

you get:

$arg1 value: ABC
$arg2 value: DEF

Now you could find some immediate usefulness of the parentheses - a space will not become a separator for the next parameter - instead you have an eval function.

How to use enums in C++

If we want the strict type safety and scoped enum, using enum class is good in C++11.

If we had to work in C++98, we can using the advice given by InitializeSahib,San to enable the scoped enum.

If we also want the strict type safety, the follow code can implement somthing like enum.

#include <iostream>
class Color
{
public:
    static Color RED()
    {
        return Color(0);
    }
    static Color BLUE()
    {
        return Color(1);
    }
    bool operator==(const Color &rhs) const
    {
        return this->value == rhs.value;
    }
    bool operator!=(const Color &rhs) const
    {
        return !(*this == rhs);
    }

private:
    explicit Color(int value_) : value(value_) {}
    int value;
};

int main()
{
    Color color = Color::RED();
    if (color == Color::RED())
    {
        std::cout << "red" << std::endl;
    }
    return 0;
}

The code is modified from the class Month example in book Effective C++ 3rd: Item 18

How to remove foreign key constraint in sql server?

alter table <referenced_table_name> drop  primary key;

Foreign key constraint will be removed.

How to change TextField's height and width?

If you use "suffixIcon" to collapse the height of the TextField add: suffixIconConstraints

TextField(
                    style: TextStyle(fontSize: r * 1.8, color: Colors.black87),
                    decoration: InputDecoration(
                      isDense: true,
                      contentPadding: EdgeInsets.symmetric(vertical: r * 1.6, horizontal: r * 1.6),
                      suffixIcon: Icon(Icons.search, color: Colors.black54),
                      suffixIconConstraints: BoxConstraints(minWidth: 32, minHeight: 32),
                    ),
                  )

How to export/import PuTTy sessions list?

If you, like me, installed new Windows and only after you remember about putty sessions, you can still import them, if you have old Windows hard drive or at least your old "home" directory backed up (C:\Users\<user_name>).

In this directory there should be NTUSER.DAT file. It is hidden by default, so you should enable hidden files in your Windows explorer or use another file browser. This file contains the HKEY_CURRENT_USER branch of your old Windows registry.

To use it, you need to open regedit on your new Windows, and select HKEY_USERS key.

Then select File -> Load Hive... and find your old "home" directory of your old Windows installation. In this directory there should be NTUSER.DAT file. It is hidden by default, so, if you didn't enable to show hidden files in your Windows explorer properties, then you can just manually enter file name into File name input box of "Load Hive" dialog and press Enter. Then in the next dialog window enter some key name to load old registry into it. e.g. tmp.

Your old registry's HKEY_CURRENT_USER branch now should be accessible under HKEY_USERS\tmp branch of your current registry.

Now export HKEY_USERS\tmp\Software\SimonTatham branch into putty.reg file, open this file in your favorite text editor and find-and-replace all HKEY_USERS\tmp string with HKEY_CURRENT_USER. Now save the .reg file.

You can import now this file into your current Windows registry by double-clicking it. See m0nhawk's answer how to do this.

In the end, select HKEY_USERS\tmp branch in the registry editor and then select File -> Unload Hive... and confirm this operation.

How to Apply Mask to Image in OpenCV?

You can use the mask to copy only the region of interest of an original image to a destination one:

cvCopy(origImage,destImage,mask);

where mask should be an 8-bit single channel array.

See more at the OpenCV docs

AngularJS : Difference between the $observe and $watch methods

Why is $observe different than $watch?

The watchExpression is evaluated and compared to the previous value each digest() cycle, if there's a change in the watchExpression value, the watch function is called.

$observe is specific to watching for interpolated values. If a directive's attribute value is interpolated, eg dir-attr="{{ scopeVar }}", the observe function will only be called when the interpolated value is set (and therefore when $digest has already determined updates need to be made). Basically there's already a watcher for the interpolation, and the $observe function piggybacks off that.

See $observe & $set in compile.js

How can I upgrade specific packages using pip and a requirements file?

The shortcut command for --upgrade:

pip install Django --upgrade

Is:

pip install Django -U

How to get request URI without context path?

If you use request.getPathInfo() inside a Filter, you always seem to get null (at least with jetty).

This terse invalid bug + response alludes to the issue I think:

https://issues.apache.org/bugzilla/show_bug.cgi?id=28323

I suspect it is related to the fact that filters run before the servlet gets the request. It may be a container bug, or expected behaviour that I haven't been able to identify.

The contextPath is available though, so fforws solution works even in filters. I don't like having to do it by hand, but the implementation is broken or

Converting from hex to string

Like so?

static void Main()
{
    byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");
    string s = Encoding.ASCII.GetString(data); // GatewayServer
}
public static byte[] FromHex(string hex)
{
    hex = hex.Replace("-", "");
    byte[] raw = new byte[hex.Length / 2];
    for (int i = 0; i < raw.Length; i++)
    {
        raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
    }
    return raw;
}

Is there a function to round a float in C or do I need to write my own?

#include <math.h>

double round(double x);
float roundf(float x);

Don't forget to link with -lm. See also ceil(), floor() and trunc().

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

This esc behavior is IE only by the way. Instead of using jQuery use good old javascript for creating the element and it works.

var element = document.createElement('input');
element.type = 'text';
element.value = 100;
document.getElementsByTagName('body')[0].appendChild(element);

http://jsfiddle.net/gGrf9/

If you want to extend this functionality to other browsers then I would use jQuery's data object to store the default. Then set it when user presses escape.

//store default value for all elements on page. set new default on blur
$('input').each( function() {
    $(this).data('default', $(this).val());
    $(this).blur( function() { $(this).data('default', $(this).val()); });
});

$('input').keyup( function(e) {
    if (e.keyCode == 27) { $(this).val($(this).data('default')); }
});

How to check if a function exists on a SQL database

I tend to use the Information_Schema:

IF EXISTS ( SELECT  1
            FROM    Information_schema.Routines
            WHERE   Specific_schema = 'dbo'
                    AND specific_name = 'Foo'
                    AND Routine_Type = 'FUNCTION' ) 

for functions, and change Routine_Type for stored procedures

IF EXISTS ( SELECT  1
            FROM    Information_schema.Routines
            WHERE   Specific_schema = 'dbo'
                    AND specific_name = 'Foo'
                    AND Routine_Type = 'PROCEDURE' ) 

Get list of all tables in Oracle?

Oracle database to display the names of all tables using below query

SELECT owner, table_name FROM dba_tables;

SELECT owner, table_name FROM all_tables;

SELECT table_name FROM user_tables;

vist more : http://www.plsqlinformation.com/2016/08/get-list-of-all-tables-in-oracle.html

Python: print a generator expression?

Unlike a list or a dictionary, a generator can be infinite. Doing this wouldn't work:

def gen():
    x = 0
    while True:
        yield x
        x += 1
g1 = gen()
list(g1)   # never ends

Also, reading a generator changes it, so there's not a perfect way to view it. To see a sample of the generator's output, you could do

g1 = gen()
[g1.next() for i in range(10)]

Getting Current time to display in Label. VB.net

There are several problems here:

  • Your assignment is the wrong way round; you're trying to assign a value to DateTime.Now instead of Start
  • DateTime.Now is a value of type DateTime, not Integer, so the assignment wouldn't work anyway
  • There's no need to have the Start variable anyway; it's doing no good
  • total.Text is a property of type String - not DateTime or Integer

(Some of these would only show up at execution time unless you have Option Strict on, which you really should.)

You should use:

total.Text = DateTime.Now.ToString()

... possibly specifying a culture and/or format specifier if you want the result in a particular format.

Command /Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

I face this problem too. And ofc I looked for help in SO instead of use the common sense and check the error message.

The last part of the error message was the same as you.

Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 11

But few lines above I found:

In file included from /Users/Ricardo/Documents/XCode/RealEstate-Finder-v1.2/RealEstateFinder/RealEstateFinder/RealEstateFinder-Prefix.pch:26:
/Users/Ricardo/Documents/XCode/RealEstate-Finder-v1.2/RealEstateFinder/RealEstateFinder/Config/Config.h:174:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
http://www.myserver.com/apps/mobile/rest.php?id=12

Which points to my Config.h file.

Happy coding!

Mercurial: how to amend the last commit?

GUI equivalent for hg commit --amend:

This also works from TortoiseHG's GUI (I'm using v2.5):

Swich to the 'Commit' view or, in the workbench view, select the 'working directory' entry. The 'Commit' button has an option named 'Amend current revision' (click the button's drop-down arrow to find it).

enter image description here

          ||
          ||
          \/

enter image description here

Caveat emptor:

This extra option will only be enabled if the mercurial version is at least 2.2.0, and if the current revision is not public, is not a patch and has no children. [...]

Clicking the button will call 'commit --amend' to 'amend' the revision.

More info about this on the THG dev channel

How can I put strings in an array, split by new line?

StackOverflow will not allow me to comment on hesselbom's answer (not enough reputation), so I'm adding my own...

$array = preg_split('/\s*\R\s*/', trim($text), NULL, PREG_SPLIT_NO_EMPTY);

This worked best for me because it also eliminates leading (second \s*) and trailing (first \s*) whitespace automatically and also skips blank lines (the PREG_SPLIT_NO_EMPTY flag).

-= OPTIONS =-

If you want to keep leading whitespace, simply get rid of the second \s* and make it an rtrim() instead...

$array = preg_split('/\s*\R/', rtrim($text), NULL, PREG_SPLIT_NO_EMPTY);

If you need to keep empty lines, get rid of the NULL (it is only a placeholder) and PREG_SPLIT_NO_EMPTY flag, like so...

$array = preg_split('/\s*\R\s*/', trim($text));

Or keeping both leading whitespace and empty lines...

$array = preg_split('/\s*\R/', rtrim($text));

I don't see any reason why you'd ever want to keep trailing whitespace, so I suggest leaving the first \s* in there. But, if all you want is to split by new line (as the title suggests), it is THIS simple (as mentioned by Jan Goyvaerts)...

$array = preg_split('/\R/', $text);

What is the maximum size of a web browser's cookie's key?

You can also use web storage too if the app specs allows you that (it has support for IE8+).

It has 5M (most browsers) or 10M (IE) of memory at its disposal.

"Web Storage (Second Edition)" is the API and "HTML5 Local Storage" is a quick start.

multiple axis in matplotlib with different scales

if you want to do very quick plots with secondary Y-Axis then there is much easier way using Pandas wrapper function and just 2 lines of code. Just plot your first column then plot the second but with parameter secondary_y=True, like this:

df.A.plot(label="Points", legend=True)
df.B.plot(secondary_y=True, label="Comments", legend=True)

This would look something like below:

enter image description here

You can do few more things as well. Take a look at Pandas plotting doc.

Folder is locked and I can't unlock it

In addition to David M's answer, while doing cleanup -> check 'break locks' option. This will ensure release of locks. Then do svn update. This worked for me.

How do I round to the nearest 0.5?

Multiply your rating by 2, then round using Math.Round(rating, MidpointRounding.AwayFromZero), then divide that value by 2.

Math.Round(value * 2, MidpointRounding.AwayFromZero) / 2

Non-invocable member cannot be used like a method?

It have happened because you are trying to use the property "OffenceBox.Text" like a method. Try to remove parenteses from OffenceBox.Text() and it'll work fine.

Remember that you cannot create a method and a property with the same name in a class.


By the way, some alias could confuse you, since sometimes it's method or property, e.g: "Count" alias:


Namespace: System.Linq

using System.Linq

namespace Teste
{
    public class TestLinq
    {
        public return Foo()
        {
            var listX = new List<int>();
            return listX.Count(x => x.Id == 1);
        }
    }
}


Namespace: System.Collections.Generic

using System.Collections.Generic

namespace Teste
{
    public class TestList
    {
        public int Foo()
        {
            var listX = new List<int>();
            return listX.Count;
        }
    }
}

Adding System.Web.Script reference in class library

The ScriptIgnoreAttribute class is in the System.Web.Extensions.dll assembly (Located under Assemblies > Framework in the VS Reference Manager). You have to add a reference to that assembly in your class library project.

You can find this information at top of the MSDN page for the ScriptIgnoreAttribute class.

Understanding passport serialize deserialize

  1. Where does user.id go after passport.serializeUser has been called?

The user id (you provide as the second argument of the done function) is saved in the session and is later used to retrieve the whole object via the deserializeUser function.

serializeUser determines which data of the user object should be stored in the session. The result of the serializeUser method is attached to the session as req.session.passport.user = {}. Here for instance, it would be (as we provide the user id as the key) req.session.passport.user = {id: 'xyz'}

  1. We are calling passport.deserializeUser right after it where does it fit in the workflow?

The first argument of deserializeUser corresponds to the key of the user object that was given to the done function (see 1.). So your whole object is retrieved with help of that key. That key here is the user id (key can be any key of the user object i.e. name,email etc). In deserializeUser that key is matched with the in memory array / database or any data resource.

The fetched object is attached to the request object as req.user

Visual Flow

passport.serializeUser(function(user, done) {
    done(null, user.id);
});              ¦
                 ¦ 
                 ¦
                 +--------------------? saved to session
                                   ¦    req.session.passport.user = {id: '..'}
                                   ¦
                                   ?           
passport.deserializeUser(function(id, done) {
                   +---------------+
                   ¦
                   ? 
    User.findById(id, function(err, user) {
        done(err, user);
    });            +--------------? user object attaches to the request as req.user   
});

Writing numerical values on the plot with Matplotlib

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

What is the difference between JOIN and UNION?

They're completely different things.

A join allows you to relate similar data in different tables.

A union returns the results of two different queries as a single recordset.