Programs & Examples On #Url routing

URL routing is the process of mapping a URL to its content.

Using routes in Express-js

The route-map express example matches url paths with objects which in turn matches http verbs with functions. This lays the routing out in a tree, which is concise and easy to read. The apps's entities are also written as objects with the functions as enclosed methods.

var express = require('../../lib/express')
  , verbose = process.env.NODE_ENV != 'test'
  , app = module.exports = express();

app.map = function(a, route){
  route = route || '';
  for (var key in a) {
    switch (typeof a[key]) {
      // { '/path': { ... }}
      case 'object':
        app.map(a[key], route + key);
        break;
      // get: function(){ ... }
      case 'function':
        if (verbose) console.log('%s %s', key, route);
        app[key](route, a[key]);
        break;
    }
  }
};

var users = {
  list: function(req, res){
    res.send('user list');
  },

  get: function(req, res){
    res.send('user ' + req.params.uid);
  },

  del: function(req, res){
    res.send('delete users');
  }
};

var pets = {
  list: function(req, res){
    res.send('user ' + req.params.uid + '\'s pets');
  },

  del: function(req, res){
    res.send('delete ' + req.params.uid + '\'s pet ' + req.params.pid);
  }
};

app.map({
  '/users': {
    get: users.list,
    del: users.del,
    '/:uid': {
      get: users.get,
      '/pets': {
        get: pets.list,
        '/:pid': {
          del: pets.del
        }
      }
    }
  }
});

app.listen(3000);

RegEx to match stuff between parentheses

If s is your string:

s.replace(/^[^(]*\(/, "") // trim everything before first parenthesis
 .replace(/\)[^(]*$/, "") // trim everything after last parenthesis
 .split(/\)[^(]*\(/);      // split between parenthesis

Getting full URL of action in ASP.NET MVC

There is an overload of Url.Action that takes your desired protocol (e.g. http, https) as an argument - if you specify this, you get a fully qualified URL.

Here's an example that uses the protocol of the current request in an action method:

var fullUrl = this.Url.Action("Edit", "Posts", new { id = 5 }, this.Request.Url.Scheme);

HtmlHelper (@Html) also has an overload of the ActionLink method that you can use in razor to create an anchor element, but it also requires the hostName and fragment parameters. So I'd just opt to use @Url.Action again:

<span>
  Copy
  <a href='@Url.Action("About", "Home", null, Request.Url.Scheme)'>this link</a> 
  and post it anywhere on the internet!
</span>

AngularJS dynamic routing

angular.module('myapp', ['myapp.filters', 'myapp.services', 'myapp.directives']).
        config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/page/:name*', {
            templateUrl: function(urlattr){
                return '/pages/' + urlattr.name + '.html';
            },
            controller: 'CMSController'
        });
    }
]);
  • Adding * let you work with multiple levels of directories dynamically. Example: /page/cars/selling/list will be catch on this provider

From the docs (1.3.0):

"If templateUrl is a function, it will be called with the following parameters:

{Array.} - route parameters extracted from the current $location.path() by applying the current route"

Also

when(path, route) : Method

  • path can contain named groups starting with a colon and ending with a star: e.g.:name*. All characters are eagerly stored in $routeParams under the given name when the route matches.

Routing HTTP Error 404.0 0x80070002

The problem for me was a new server that System.Web.Routing was of version 3.5 while web.config requested version 4.0.0.0. The resolution was

%WINDIR%\Framework\v4.0.30319\aspnet_regiis -i

%WINDIR%\Framework64\v4.0.30319\aspnet_regiis -i

AngularJS - Animate ng-view transitions

Check this code:

Javascript:

app.config( ["$routeProvider"], function($routeProvider){
    $routeProvider.when("/part1", {"templateUrl" : "part1"});
    $routeProvider.when("/part2", {"templateUrl" : "part2"});
    $routeProvider.otherwise({"redirectTo":"/part1"});
  }]
);

function HomeFragmentController($scope) {
    $scope.$on("$routeChangeSuccess", function (scope, next, current) {
        $scope.transitionState = "active"
    });
}

CSS:

.fragmentWrapper {
    overflow: hidden;
}

.fragment {
    position: relative;
    -moz-transition-property: left;
    -o-transition-property: left;
    -webkit-transition-property: left;
    transition-property: left;
    -moz-transition-duration: 0.1s;
    -o-transition-duration: 0.1s;
    -webkit-transition-duration: 0.1s;
    transition-duration: 0.1s
}

.fragment:not(.active) {
    left: 540px;
}

.fragment.active {
    left: 0px;
}

Main page HTML:

<div class="fragmentWrapper" data-ng-view data-ng-controller="HomeFragmentController">
</div>

Partials HTML example:

<div id="part1" class="fragment {{transitionState}}">
</div>

Vue.js redirection to another page

To stay in line with your original request:

window.location.href = 'some_url'

You can do something like this:

<div @click="this.window.location='some_url'">
</div>

Note that this does not take advantage of using Vue's router, but if you want to "make a redirection in Vue.js similar to the vanilla javascript", this would work.

Get current url in Angular

You can make use of location service available in @angular/common and via this below code you can get the location or current URL

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-top-nav',
  templateUrl: './top-nav.component.html',
  styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {

  route: string;

  constructor(location: Location, router: Router) {
    router.events.subscribe((val) => {
      if(location.path() != ''){
        this.route = location.path();
      } else {
        this.route = 'Home'
      }
    });
  }

  ngOnInit() {
  }

}

here is the reference link from where I have copied thing to get location for my project. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts

Oracle Not Equals Operator

The difference is :

"If you use !=, it returns sub-second. If you use <>, it takes 7 seconds to return. Both return the right answer."

Oracle not equals (!=) SQL operator

Regards

Aligning a button to the center

You should use something like this:

<div style="text-align:center">  
    <input type="submit" />  
</div>  

Or you could use something like this. By giving the element a width and specifying auto for the left and right margins the element will center itself in its parent.

<input type="submit" style="width: 300px; margin: 0 auto;" />

How to convert An NSInteger to an int?

If you want to do this inline, just cast the NSUInteger or NSInteger to an int:

int i = -1;
NSUInteger row = 100;
i > row // true, since the signed int is implicitly converted to an unsigned int
i > (int)row // false

'any' vs 'Object'

any is something specific to TypeScript is explained quite well by alex's answer.

Object refers to the JavaScript object type. Commonly used as {} or sometimes new Object. Most things in javascript are compatible with the object data type as they inherit from it. But any is TypeScript specific and compatible with everything in both directions (not inheritance based). e.g. :

var foo:Object; 
var bar:any;
var num:number;

foo = num; // Not an error
num = foo; // ERROR 

// Any is compatible both ways 
bar = num;
num = bar;  

IPhone/IPad: How to get screen width programmatically?

use:

NSLog(@"%f",[[UIScreen mainScreen] bounds].size.width) ;

Selecting multiple columns in a Pandas dataframe

If you want to get one element by row index and column name, you can do it just like df['b'][0]. It is as simple as you can imagine.

Or you can use df.ix[0,'b'] - mixed usage of index and label.

Note: Since v0.20, ix has been deprecated in favour of loc / iloc.

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

Try something like this:

foreach (ListItem listItem in YrChkBox.Items)
{
    if (listItem.Selected)
    { 
       //do some work 
    }
    else 
    { 
      //do something else 
    }
}

How to declare an array in Python?

Following on from Lennart, there's also numpy which implements homogeneous multi-dimensional arrays.

CSS background opacity with rgba not working in IE 8

I'm late to the party, but for anyone else who finds this - this article is very useful: http://kilianvalkhof.com/2010/css-xhtml/how-to-use-rgba-in-ie/

It uses the gradient filter to display solid but transparent colour.

How to get row count using ResultSet in Java?

If you have table and storing the ID as primary and auto increment then this will work

Example code to get the total row count http://www.java2s.com/Tutorial/Java/0340__Database/GettheNumberofRowsinaDatabaseTable.htm

Below is code

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class Main {
  public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
        ResultSet.CONCUR_UPDATABLE);

    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
    st.executeUpdate("insert into survey (id,name ) values (2,null)");
    st.executeUpdate("insert into survey (id,name ) values (3,'Tom')");
    st = conn.createStatement();
    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    rs = st.executeQuery("SELECT COUNT(*) FROM survey");
    // get the number of rows from the result set
    rs.next();
    int rowCount = rs.getInt(1);
    System.out.println(rowCount);

    rs.close();
    st.close();
    conn.close();

  }

  private static Connection getConnection() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");
    String url = "jdbc:hsqldb:mem:data/tutorial";

    return DriverManager.getConnection(url, "sa", "");
  }
}

Is there a keyboard shortcut (hotkey) to open Terminal in macOS?

iTerm2 - an alternative to Terminal - has an option to use configurable system-wide hotkey to show/hide (initially set to Alt+Space, disabled by default)

How to capture UIView to UIImage without loss of quality on retina display

Switch from use of UIGraphicsBeginImageContext to UIGraphicsBeginImageContextWithOptions (as documented on this page). Pass 0.0 for scale (the third argument) and you'll get a context with a scale factor equal to that of the screen.

UIGraphicsBeginImageContext uses a fixed scale factor of 1.0, so you're actually getting exactly the same image on an iPhone 4 as on the other iPhones. I'll bet either the iPhone 4 is applying a filter when you implicitly scale it up or just your brain is picking up on it being less sharp than everything around it.

So, I guess:

#import <QuartzCore/QuartzCore.h>

+ (UIImage *)imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return img;
}

And in Swift 4:

func image(with view: UIView) -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0)
    defer { UIGraphicsEndImageContext() }
    if let context = UIGraphicsGetCurrentContext() {
        view.layer.render(in: context)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        return image
    }
    return nil
}

PRINT statement in T-SQL

Query Analyzer buffers messages. The PRINT and RAISERROR statements both use this buffer, but the RAISERROR statement has a WITH NOWAIT option. To print a message immediately use the following:

RAISERROR ('Your message', 0, 1) WITH NOWAIT

RAISERROR will only display 400 characters of your message and uses a syntax similar to the C printf function for formatting text.

Please note that the use of RAISERROR with the WITH NOWAIT option will flush the message buffer, so all previously buffered information will be output also.

C# : assign data to properties via constructor vs. instantiating

Object initializers are cool because they allow you to set up a class inline. The tradeoff is that your class cannot be immutable. Consider:

public class Album 
{
    // Note that we make the setter 'private'
    public string Name { get; private set; }
    public string Artist { get; private set; }
    public int Year { get; private set; }

    public Album(string name, string artist, int year)
    {
        this.Name = name;
        this.Artist = artist;
        this.Year = year;
    }
}

If the class is defined this way, it means that there isn't really an easy way to modify the contents of the class after it has been constructed. Immutability has benefits. When something is immutable, it is MUCH easier to determine that it's correct. After all, if it can't be modified after construction, then there is no way for it to ever be 'wrong' (once you've determined that it's structure is correct). When you create anonymous classes, such as:

new { 
    Name = "Some Name",
    Artist = "Some Artist",
    Year = 1994
};

the compiler will automatically create an immutable class (that is, anonymous classes cannot be modified after construction), because immutability is just that useful. Most C++/Java style guides often encourage making members const(C++) or final (Java) for just this reason. Bigger applications are just much easier to verify when there are fewer moving parts.

That all being said, there are situations when you want to be able quickly modify the structure of your class. Let's say I have a tool that I want to set up:

public void Configure(ConfigurationSetup setup);

and I have a class that has a number of members such as:

class ConfigurationSetup {
    public String Name { get; set; }
    public String Location { get; set; }
    public Int32 Size { get; set; }
    public DateTime Time { get; set; }

    // ... and some other configuration stuff... 
}

Using object initializer syntax is useful when I want to configure some combination of properties, but not neccesarily all of them at once. For example if I just want to configure the Name and Location, I can just do:

ConfigurationSetup setup = new ConfigurationSetup {
    Name = "Some Name",
    Location = "San Jose"
};

and this allows me to set up some combination without having to define a new constructor for every possibly permutation.

On the whole, I would argue that making your classes immutable will save you a great deal of development time in the long run, but having object initializer syntax makes setting up certain configuration permutations much easier.

Convert timestamp to readable date/time PHP

strtotime makes a date string into a timestamp. You want to do the opposite, which is date. The typical mysql date format is date('Y-m-d H:i:s'); Check the manual page for what other letters represent.

If you have a timestamp that you want to use (apparently you do), it is the second argument of date().

How to download a file over HTTP?

Python 3

  • urllib.request.urlopen

    import urllib.request
    response = urllib.request.urlopen('http://www.example.com/')
    html = response.read()
    
  • urllib.request.urlretrieve

    import urllib.request
    urllib.request.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')
    

    Note: According to the documentation, urllib.request.urlretrieve is a "legacy interface" and "might become deprecated in the future" (thanks gerrit)

Python 2

  • urllib2.urlopen (thanks Corey)

    import urllib2
    response = urllib2.urlopen('http://www.example.com/')
    html = response.read()
    
  • urllib.urlretrieve (thanks PabloG)

    import urllib
    urllib.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')
    

OAuth: how to test with local URLs?

You can edit the hosts file on windows or linux Windows : C:\Windows\System32\Drivers\etc\hosts Linux : /etc/hosts

localhost name resolution is handled within DNS itself.

127.0.0.1 mywebsite.com

after you finish your tests you just comment the line you add to disable it

127.0.0.1 mywebsite.com

Will iOS launch my app into the background if it was force-quit by the user?

Actually if you need to test background fetch you need to enable one option in scheme:

enabling bg fetch

Another way how you can test it: simulate bg fetch

Here is full information about this new feature: http://www.objc.io/issue-5/multitasking.html

fitting data with numpy

Note that you can use the Polynomial class directly to do the fitting and return a Polynomial instance.

from numpy.polynomial import Polynomial

p = Polynomial.fit(x, y, 4)
plt.plot(*p.linspace())

p uses scaled and shifted x values for numerical stability. If you need the usual form of the coefficients, you will need to follow with

pnormal = p.convert(domain=(-1, 1))

How to convert string date to Timestamp in java?

You can even try this.

   String date="09/08/1980";    // take a string  date
    Timestamp ts=null;  //declare timestamp
    Date d=new Date(date); // Intialize date with the string date
    if(d!=null){  // simple null check
        ts=new java.sql.Timestamp(d.getTime()); // convert gettime from date and assign it to your timestamp.
    }

Convert integer value to matching Java Enum

You would need to do this manually, by adding a a static map in the class that maps Integers to enums, such as

private static final Map<Integer, PcapLinkType> intToTypeMap = new HashMap<Integer, PcapLinkType>();
static {
    for (PcapLinkType type : PcapLinkType.values()) {
        intToTypeMap.put(type.value, type);
    }
}

public static PcapLinkType fromInt(int i) {
    PcapLinkType type = intToTypeMap.get(Integer.valueOf(i));
    if (type == null) 
        return PcapLinkType.DLT_UNKNOWN;
    return type;
}

Escape single quote character for use in an SQLite query

In bash scripts, I found that escaping double quotes around the value was necessary for values that could be null or contained characters that require escaping (like hyphens).

In this example, columnA's value could be null or contain hyphens.:

sqlite3 $db_name "insert into foo values (\"$columnA\", $columnB)";

How to clear PermGen space Error in tomcat

The PermGen space is what Tomcat uses to store class definitions (definitions only, no instantiations) and string pools that have been interned. From experience, the PermGen space issues tend to happen frequently in dev environments really since Tomcat has to load new classes every time it deploys a WAR or does a jspc (when you edit a jsp file). Personally, I tend to deploy and redeploy wars a lot when I’m in dev testing so I know I’m bound to run out sooner or later (primarily because Java’s GC cycles are still kinda crap so if you redeploy your wars quickly and frequently enough, the space fills up faster than they can manage).

This should theoretically be less of an issue in production environments since you (hopefully) don’t change the codebase on a 10 minute basis. If it still occurs, that just means your codebase (and corresponding library dependencies) are too large for the default memory allocation and you’ll just need to mess around with stack and heap allocation. I think the standards are stuff like:

-XX:MaxPermSize=SIZE

I’ve found however the best way to take care of that for good is to allow classes to be unloaded so your PermGen never runs out:

-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled

Stuff like that worked magic for me in the past. One thing tho, there’s a significant performance tradeoff in using those, since permgen sweeps will make like an extra 2 requests for every request you make or something along those lines. You’ll need to balance your use with the tradeoffs.

Writing files in Node.js

 var fs = require('fs');
 fs.writeFile(path + "\\message.txt", "Hello", function(err){
 if (err) throw err;
  console.log("success");
}); 

For example : read file and write to another file :

  var fs = require('fs');
    var path = process.cwd();
    fs.readFile(path+"\\from.txt",function(err,data)
                {
                    if(err)
                        console.log(err)
                    else
                        {
                            fs.writeFile(path+"\\to.text",function(erro){
                                if(erro)
                                    console.log("error : "+erro);
                                else
                                    console.log("success");
                            });
                        }
                });

Div height 100% and expands to fit content

This question may be old, but it deserves an update. Here is another way to do that:

#yourdiv {
    display: flex;
    width:100%;
    height:100%;
}

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

There is Mozilla official solution: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

(function() {
    /**Array*/
    // Production steps of ECMA-262, Edition 5, 15.4.4.14
    // Reference: http://es5.github.io/#x15.4.4.14
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function(searchElement, fromIndex) {
            var k;
            // 1. Let O be the result of calling ToObject passing
            //    the this value as the argument.
            if (null === this || undefined === this) {
                throw new TypeError('"this" is null or not defined');
            }
            var O = Object(this);
            // 2. Let lenValue be the result of calling the Get
            //    internal method of O with the argument "length".
            // 3. Let len be ToUint32(lenValue).
            var len = O.length >>> 0;
            // 4. If len is 0, return -1.
            if (len === 0) {
                return -1;
            }
            // 5. If argument fromIndex was passed let n be
            //    ToInteger(fromIndex); else let n be 0.
            var n = +fromIndex || 0;
            if (Math.abs(n) === Infinity) {
                n = 0;
            }
            // 6. If n >= len, return -1.
            if (n >= len) {
                return -1;
            }
            // 7. If n >= 0, then Let k be n.
            // 8. Else, n<0, Let k be len - abs(n).
            //    If k is less than 0, then let k be 0.
            k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
            // 9. Repeat, while k < len
            while (k < len) {
                // a. Let Pk be ToString(k).
                //   This is implicit for LHS operands of the in operator
                // b. Let kPresent be the result of calling the
                //    HasProperty internal method of O with argument Pk.
                //   This step can be combined with c
                // c. If kPresent is true, then
                //    i.  Let elementK be the result of calling the Get
                //        internal method of O with the argument ToString(k).
                //   ii.  Let same be the result of applying the
                //        Strict Equality Comparison Algorithm to
                //        searchElement and elementK.
                //  iii.  If same is true, return k.
                if (k in O && O[k] === searchElement) {
                    return k;
                }
                k++;
            }
            return -1;
        };
    }
})();

Passing Javascript variable to <a href >

If you use internationalization (i18n), and after switch to another language, something like ?locale=fror ?fr might be added at the end of the url. But when you go to another page on click event, translation switch wont be stable.

For this kind of cases a DOM click event handler function must be produced to handle all the a.href attributes by storing the switch state as a variable and add it to all a tags’ tail.

How to call an async method from a getter or setter?

You can use Task like this :

public int SelectedTab
        {
            get => selected_tab;
            set
            {
                selected_tab = value;

                new Task(async () =>
                {
                    await newTab.ScaleTo(0.8);
                }).Start();
            }
        }

How to export SQL Server 2005 query to CSV

In SQL 2005, this is simple: 1. Open SQL Server management studio and copy the sql statement you need into the TSQL , such as exec sp_whatever 2. Query->Results to Grid 3. Highlight the sql statement and run it 4. Highlight the data results (left-click on upper left area of results grid) 5. Now right-click and select Save Results As 6. Select CSV in the Save as type, enter a file name, select a location and click Save.

Easy!

Using an array from Observable Object with ngFor and Async Pipe Angular 2

I think what u r looking for is this

<article *ngFor="let news of (news$ | async)?.articles">
<h4 class="head">{{news.title}}</h4>
<div class="desc"> {{news.description}}</div>
<footer>
    {{news.author}}
</footer>

getActionBar() returns null

I faced the above issue where getActionBar() method returns null. I was calling the getActionBar() after setting the setContentView() and still its returning a null.

I resolved the issue by setting the min-sdk version in Android Manifest file that was missing initially. <uses-sdk android:minSdkVersion="11" />

HTML table with fixed headers and a fixed column?

The first column has a scrollbar on the cell right below the headers

<table>
    <thead>
        <th> Header 1</th>
        <th> Header 2</th>
        <th> Header 3</th>
    </thead>
    <tbody>
        <tr>
            <td>
                <div style="width: 50; height:30; overflow-y: scroll"> 
                    Tklasdjf alksjf asjdfk jsadfl kajsdl fjasdk fljsaldk 
                    fjlksa djflkasjdflkjsadlkf jsakldjfasdjfklasjdflkjasdlkfjaslkdfjasdf
                </div>
            </td>
            <td>
                Hello world
            </td>
            <td> Hello world2
        </tr>
    </tbody>
</table>

MySQL export into outfile : CSV escaping chars

Without actually seeing your output file for confirmation, my guess is that you've got to get rid of the FIELDS ESCAPED BY value.

MySQL's FIELDS ESCAPED BY is probably behaving in two ways that you were not counting on: (1) it is only meant to be one character, so in your case it is probably equal to just one quotation mark; (2) it is used to precede each character that MySQL thinks needs escaping, including the FIELDS TERMINATED BY and LINES TERMINATED BY values. This makes sense to most of the computing world, but it isn't the way Excel does escaping.

I think your double REPLACE is working, and that you are successfully replacing literal newlines with spaces (two spaces in the case of Windows-style newlines). But if you have any commas in your data (literals, not field separators), these are being preceded by quotation marks, which Excel treats much differently than MySQL. If that's the case, then the erroneous newlines that are tripping up Excel are actually newlines that MySQL had intended as line terminators.

How to create a checkbox with a clickable label?

It works too :

<form>
    <label for="male"><input type="checkbox" name="male" id="male" />Male</label><br />
    <label for="female"><input type="checkbox" name="female" id="female" />Female</label>
</form>

How to write data to a text file without overwriting the current data

Look into the File class.

You can create a streamwriter with

StreamWriter sw = File.Create(....) 

You can open an existing file with

File.Open(...)

You can append text easily with

File.AppendAllText(...);

How to determine a Python variable's type?

print type(variable_name)

I also highly recommend the IPython interactive interpreter when dealing with questions like this. It lets you type variable_name? and will return a whole list of information about the object including the type and the doc string for the type.

e.g.

In [9]: var = 123

In [10]: var?
Type:       int
Base Class: <type 'int'>
String Form:    123
Namespace:  Interactive
Docstring:
    int(x[, base]) -> integer

Convert a string or number to an integer, if possible. A floating point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If the argument is outside the integer range a long object will be returned instead.

Javascript getElementsByName.value not working

Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.

_x000D_
_x000D_
function myFunction() {_x000D_
  var selchbox = [];_x000D_
  var inputfields = document.getElementsByName("myCheck");_x000D_
  var ar_inputflds = inputfields.length;_x000D_
_x000D_
  for (var i = 0; i < ar_inputflds; i++) {_x000D_
    if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
      selchbox.push(inputfields[i].value);_x000D_
  }_x000D_
  return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
  var selchb = myFunction();_x000D_
  console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
_x000D_
_x000D_

Path of assets in CSS files in Symfony 2

I have came across the very-very-same problem.

In short:

  • Willing to have original CSS in an "internal" dir (Resources/assets/css/a.css)
  • Willing to have the images in the "public" dir (Resources/public/images/devil.png)
  • Willing that twig takes that CSS, recompiles it into web/css/a.css and make it point the image in /web/bundles/mynicebundle/images/devil.png

I have made a test with ALL possible (sane) combinations of the following:

  • @notation, relative notation
  • Parse with cssrewrite, without it
  • CSS image background vs direct <img> tag src= to the very same image than CSS
  • CSS parsed with assetic and also without parsing with assetic direct output
  • And all this multiplied by trying a "public dir" (as Resources/public/css) with the CSS and a "private" directory (as Resources/assets/css).

This gave me a total of 14 combinations on the same twig, and this route was launched from

  • "/app_dev.php/"
  • "/app.php/"
  • and "/"

thus giving 14 x 3 = 42 tests.

Additionally, all this has been tested working in a subdirectory, so there is no way to fool by giving absolute URLs because they would simply not work.

The tests were two unnamed images and then divs named from 'a' to 'f' for the CSS built FROM the public folder and named 'g to 'l' for the ones built from the internal path.

I observed the following:

Only 3 of the 14 tests were shown adequately on the three URLs. And NONE was from the "internal" folder (Resources/assets). It was a pre-requisite to have the spare CSS PUBLIC and then build with assetic FROM there.

These are the results:

  1. Result launched with /app_dev.php/ Result launched with /app_dev.php/

  2. Result launched with /app.php/ Result launched with /app.php/

  3. Result launched with / enter image description here

So... ONLY - The second image - Div B - Div C are the allowed syntaxes.

Here there is the TWIG code:

<html>
    <head>
            {% stylesheets 'bundles/commondirty/css_original/container.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

    {# First Row: ABCDEF #}

            <link href="{{ '../bundles/commondirty/css_original/a.css' }}" rel="stylesheet" type="text/css" />
            <link href="{{ asset( 'bundles/commondirty/css_original/b.css' ) }}" rel="stylesheet" type="text/css" />

            {% stylesheets 'bundles/commondirty/css_original/c.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets 'bundles/commondirty/css_original/d.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/public/css_original/e.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/public/css_original/f.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

    {# First Row: GHIJKL #}

            <link href="{{ '../../src/Common/DirtyBundle/Resources/assets/css/g.css' }}" rel="stylesheet" type="text/css" />
            <link href="{{ asset( '../src/Common/DirtyBundle/Resources/assets/css/h.css' ) }}" rel="stylesheet" type="text/css" />

            {% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/i.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/j.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/assets/css/k.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/assets/css/l.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

    </head>
    <body>
        <div class="container">
            <p>
                <img alt="Devil" src="../bundles/commondirty/images/devil.png">
                <img alt="Devil" src="{{ asset('bundles/commondirty/images/devil.png') }}">
            </p>
            <p>
                <div class="a">
                    A
                </div>
                <div class="b">
                    B
                </div>
                <div class="c">
                    C
                </div>
                <div class="d">
                    D
                </div>
                <div class="e">
                    E
                </div>
                <div class="f">
                    F
                </div>
            </p>
            <p>
                <div class="g">
                    G
                </div>
                <div class="h">
                    H
                </div>
                <div class="i">
                    I
                </div>
                <div class="j">
                    J
                </div>
                <div class="k">
                    K
                </div>
                <div class="l">
                    L
                </div>
            </p>
        </div>
    </body>
</html>

The container.css:

div.container
{
    border: 1px solid red;
    padding: 0px;
}

div.container img, div.container div 
{
    border: 1px solid green;
    padding: 5px;
    margin: 5px;
    width: 64px;
    height: 64px;
    display: inline-block;
    vertical-align: top;
}

And a.css, b.css, c.css, etc: all identical, just changing the color and the CSS selector.

.a
{
    background: red url('../images/devil.png');
}

The "directories" structure is:

Directories Directories

All this came, because I did not want the individual original files exposed to the public, specially if I wanted to play with "less" filter or "sass" or similar... I did not want my "originals" published, only the compiled one.

But there are good news. If you don't want to have the "spare CSS" in the public directories... install them not with --symlink, but really making a copy. Once "assetic" has built the compound CSS, and you can DELETE the original CSS from the filesystem, and leave the images:

Compilation process Compilation process

Note I do this for the --env=prod environment.

Just a few final thoughts:

  • This desired behaviour can be achieved by having the images in "public" directory in Git or Mercurial and the "css" in the "assets" directory. That is, instead of having them in "public" as shown in the directories, imagine a, b, c... residing in the "assets" instead of "public", than have your installer/deployer (probably a Bash script) to put the CSS temporarily inside the "public" dir before assets:install is executed, then assets:install, then assetic:dump, and then automating the removal of CSS from the public directory after assetic:dump has been executed. This would achive EXACTLY the behaviour desired in the question.

  • Another (unknown if possible) solution would be to explore if "assets:install" can only take "public" as the source or could also take "assets" as a source to publish. That would help when installed with the --symlink option when developing.

  • Additionally, if we are going to script the removal from the "public" dir, then, the need of storing them in a separate directory ("assets") disappears. They can live inside "public" in our version-control system as there will be dropped upon deploy to the public. This allows also for the --symlink usage.

BUT ANYWAY, CAUTION NOW: As now the originals are not there anymore (rm -Rf), there are only two solutions, not three. The working div "B" does not work anymore as it was an asset() call assuming there was the original asset. Only "C" (the compiled one) will work.

So... there is ONLY a FINAL WINNER: Div "C" allows EXACTLY what it was asked in the topic: To be compiled, respect the path to the images and do not expose the original source to the public.

The winner is C

The winner is C

How to install a previous exact version of a NPM package?

You can use the following command to install a previous version of an npm package:

npm install packagename@version

How can I show an image using the ImageView component in javafx and fxml?

You don't need an initializer, unless you're dynamically loading a different image each time. I think doing as much as possible in fxml is more organized. Here is an fxml file that will do what you need.

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>

<AnchorPane
    xmlns:fx="http://javafx.co/fxml/1"
    xmlns="http://javafx.com/javafx/2.2"
    fx:controller="application.SampleController"
    prefHeight="316.0"
    prefWidth="321.0"
    >
    <children>
        <ImageView
                fx:id="imageView"
                fitHeight="150.0"
                fitWidth="200.0"
                layoutX="61.0"
                layoutY="83.0"
                pickOnBounds="true"
                preserveRatio="true"
            >
            <image>
                <Image
                    url="src/Box13.jpg"
                    backgroundLoading="true"
                    />
            </image>
        </ImageView>
    </children>
</AnchorPane>

Specifying the backgroundLoading property in the Image tag is optional, it defaults to false. It's best to set backgroundLoading true when it takes a moment or longer to load the image, that way a placeholder will be used until the image loads, and the program wont freeze while loading.

Android - How to decode and decompile any APK file?

To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.

How can I get CMake to find my alternative Boost installation?

There is a generic method to give CMake directions about where to find libraries.

When looking for a library, CMake looks first in the following variables:

  • CMAKE_LIBRARY_PATH and LD_LIBRARY_PATH for libraries
  • CMAKE_INCLUDE_PATH and INCLUDE_PATH for includes

If you declare your Boost files in one of the environment variables, CMake will find it. Example:

export CMAKE_LIBRARY_PATH="/stuff/lib.boost.1.52/lib:$CMAKE_LIBRARY_PATH"
export CMAKE_INCLUDE_PATH="/stuff/lib.boost.1.52/include:$CMAKE_INCLUDE_PATH"

If it's too cumbersome, you can also use a nice installing tool I wrote that will do everything for you: C++ version manager

How can I tell if a Java integer is null?

Try this:

Integer startIn = null;

try {
  startIn = Integer.valueOf(startField.getText());
} catch (NumberFormatException e) {
  .
  .
  .
}

if (startIn == null) {
  // Prompt for value...
}

How to pass a function as a parameter in Java?

Java does not (yet) support closures. But there are other languages like Scala and Groovy which run in the JVM and do support closures.

Eloquent ->first() if ->exists()

(ps - I couldn't comment) I think your best bet is something like you've done, or similar to:

$user = User::where('mobile', Input::get('mobile'));
$user->exists() and $user = $user->first();

Oh, also: count() instead if exists but this could be something used after get.

Create SQLite database in android

If you want to keep the database between uninstalls you have to put it on the SD Card. This is the only place that won't be deleted at the moment your app is deleted. But in return it can be deleted by the user every time.

If you put your DB on the SD Card you can't use the SQLiteOpenHelper anymore, but you can use the source and the architecture of this class to get some ideas on how to implement the creation, updating and opening of a databse.

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

I don't usually post to these things but this was super annoying. The confusion comes from the fact that some of the Keras imdb.py files have already updated:

with np.load(path) as f:

to the version with allow_pickle=True. Make sure check the imdb.py file to see if this change was already implemented. If it has been adjusted, the following works fine:

from keras.datasets import imdb
(train_text, train_labels), (test_text, test_labels) = imdb.load_data(num_words=10000)

Java Map equivalent in C#

Dictionary<,> is the equivalent. While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:

class Test {
  Dictionary<int,String> entities;

  public String getEntity(int code) {
    return this.entities[code];
  }
}

If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys. You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).

Get the current year in JavaScript

Instantiate the class Date and call upon its getFullYear method to get the current year in yyyy format. Something like this:

let currentYear = new Date().getFullYear;

The currentYear variable will hold the value you are looking out for.

How do I get Month and Date of JavaScript in 2 digit format?

var net = require('net')

function zeroFill(i) {
  return (i < 10 ? '0' : '') + i
}

function now () {
  var d = new Date()
  return d.getFullYear() + '-'
    + zeroFill(d.getMonth() + 1) + '-'
    + zeroFill(d.getDate()) + ' '
    + zeroFill(d.getHours()) + ':'
    + zeroFill(d.getMinutes())
}

var server = net.createServer(function (socket) {
  socket.end(now() + '\n')
})

server.listen(Number(process.argv[2]))

How can I open two pages from a single click without using JavaScript?

it is working perfectly by only using html

<p><a href="#"onclick="window.open('http://google.com');window.open('http://yahoo.com');">Click to open Google and Yahoo</a></p>

Run exe file with parameters in a batch file

Unless it's just a simplified example for the question, my advice is that drop the batch wrapper and schedule PHP directly, more specifically the php-win.exe program, which won't open unnecessary windows.

Program: c:\program files\php\php-win.exe
Arguments: D:\mydocs\mp\index.php param1 param2

Otherwise, just quote stuff as Andrew points out.


In older versions of Windows, you should be able to put everything in the single "Run" text box (as long as you quote everything that has spaces):

"c:\program files\php\php-win.exe" D:\mydocs\mp\index.php param1 param2

Android - default value in editText

You can do it in this way

private EditText nameEdit;
private EditText emailEdit;
private String nameDefaultValue = "Your Name";
private String emailDefaultValue = "[email protected]";

and inside onCreate method

nameEdit = (EditText) findViewById(R.id.name);
    nameEdit.setText(nameDefaultValue); 
    nameEdit.setOnTouchListener( new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (nameEdit.getText().toString().equals(nameDefaultValue)){
                nameEdit.setText("");
            }
            return false;
        }
    });

    nameEdit.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {               
            if(!hasFocus && TextUtils.isEmpty(nameEdit.getText().toString())){
                nameEdit.setText(nameDefaultValue);
            } else if (hasFocus && nameEdit.getText().toString().equals(nameDefaultValue)){
                nameEdit.setText("");
            }
        }
    });     

    emailEdit = (EditText)findViewById(R.id.email);
    emailEdit.setText(emailDefaultValue);   
    emailEdit.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {               
            if(!hasFocus && TextUtils.isEmpty(emailEdit.getText().toString())){
                emailEdit.setText(emailDefaultValue);
            } else if (hasFocus && emailEdit.getText().toString().equals(emailDefaultValue)){
                emailEdit.setText("");
            }
        }
    });

How to hide the title bar for an Activity in XML with existing custom theme

You can modify your AndroidManifest.xml:

<activity android:name=".MainActivity"
          android:label="@string/app_name"
          android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">

or use android:theme="@android:style/Theme.Black.NoTitleBar" if you don't need a fullscreen Activity.

Note: If you've used a 'default' view before, you probably should also change the parent class from AppCompatActivity to Activity.

Testing for empty or nil-value string

variable = id if variable.to_s.empty?

Tomcat 7 "SEVERE: A child container failed during start"

This same issue occurred for me and stack trace

SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/XXXXSearch]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/XXXXSearch]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 6 more
Caused by: java.lang.IllegalStateException: Unable to complete the scan for annotations for web application [/XXXXSearch]. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies
    at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2109)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1981)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1947)
    at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1932)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1326)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:369)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: java.lang.StackOverflowError
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)

In my analysis what i found was, this issue is occurred when illegal cyclic inheritance dependencies caused for Tomcat startup annotation processing.

But my project had lot of dependency JARs, and couldn't found which one is responsible for this.

After trying so many unhappy approaches What i did was , I have updated my tomcat plugin to following and ran the same scenario,

<plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat8-maven-plugin</artifactId>
    <version>3.0-r1756463</version>
<\plugin>

Then i was able to find which JAR is caused to this issue ,

Aug 23, 2017 2:32:12 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar
SEVERE: Unable to process Jar entry [cryptix/test/TestLOKI91.class] from Jar [jar:file:/C:/Users/Tharinda/.m2/repository/cryptix/cryptix/1.2.2/cryptix-1.2.2.jar!/] for annotations
java.io.EOFException
    at org.apache.tomcat.util.bcel.classfile.FastDataInputStream.readUnsignedShort(FastDataInputStream.java:120)
    at org.apache.tomcat.util.bcel.classfile.ClassParser.readAttributes(ClassParser.java:110)
    at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:94)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:1994)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1944)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1919)
    at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1880)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1149)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:771)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:305)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5120)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Then just solving the issue with cryptix-1.2.2.jar solved this problem.

I strongly recommend to move tomcat8-maven-plugin which seems stable and less buggy at the moment.

How do I compile C++ with Clang?

Open a Terminal window and navigate to your project directory. Run these sets of commands, depending on which compiler you have installed:

To compile multiple C++ files using clang++:

$ clang++ *.cpp 
$ ./a.out 

To compile multiple C++ files using g++:

$ g++ -c *.cpp 
$ g++ -o temp.exe *.o
$ ./temp.exe

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

Cleanest version specially good if you just want to get the .value from the element.

document.getElementById('elementsid') ? function_if_exists(); function_if_doesnt_exists();

VBA Count cells in column containing specified value

Not what you asked but may be useful nevertheless.

Of course you can do the same thing with matrix formulas. Just read the result of the cell that contains:

Cell A1="Text to search"
Cells A2:C20=Range to search for

=COUNT(SEARCH(A1;A2:C20;1))

Remember that entering matrix formulas needs CTRL+SHIFT+ENTER, not just ENTER. After, it should look like :

{=COUNT(SEARCH(A1;A2:C20;1))}

How to Store Historical Data

In SQL Server 2016 and above, there is a new feature called Temporal Tables that aims to solve this challenge with minimal effort from developer. The concept of temporal table is similar to Change Data Capture (CDC), with the difference that temporal table has abstracted most of the things that you had to do manually if you were using CDC.

Curl not recognized as an internal or external command, operable program or batch file

Steps to install curl in windows

Install cURL on Windows

There are 4 steps to follow to get cURL installed on Windows.

Step 1 and Step 2 is to install SSL library. Step 3 is to install cURL. Step 4 is to install a recent certificate

Step One: Install Visual C++ 2008 Redistributables

From https://www.microsoft.com/en-za/download/details.aspx?id=29 For 64bit systems Visual C++ 2008 Redistributables (x64) For 32bit systems Visual C++ 2008 Redistributables (x32)

Step Two: Install Win(32/64) OpenSSL v1.0.0k Light

From http://www.shininglightpro.com/products/Win32OpenSSL.html For 64bit systems Win64 OpenSSL v1.0.0k Light For 32bit systems Win32 OpenSSL v1.0.0k Light

Step Three: Install cURL

Depending on if your system is 32 or 64 bit, download the corresponding** curl.exe.** For example, go to the Win64 - Generic section and download the Win64 binary with SSL support (the one where SSL is not crossed out). Visit http://curl.haxx.se/download.html

Copy curl.exe to C:\Windows\System32

Step Four: Install Recent Certificates

Do not skip this step. Download a recent copy of valid CERT files from https://curl.haxx.se/ca/cacert.pem Copy it to the same folder as you placed curl.exe (C:\Windows\System32) and rename it as curl-ca-bundle.crt

If you have already installed curl or after doing the above steps, add the directory where it's installed to the windows path:

1 - From the Desktop, right-click My Computer and click Properties.
2 - Click Advanced System Settings .
3 - In the System Properties window click the Environment Variables button.
4 - Select Path and click Edit.
5 - Append ;c:\path to curl directory at the end.
5 - Click OK.
6 - Close and re-open the command prompt

CentOS 64 bit bad ELF interpreter

You can also install OpenJDK 32-bit (.i686) instead. According to my test, it will be installed and works without problems.

sudo yum install java-1.8.0-openjdk.i686

Note:

The java-1.8.0-openjdk package contains just the Java Runtime Environment. If you want to develop Java programs then install the java-1.8.0-openjdk-devel package.

See here for more details.

How to add image in Flutter

Create your assets directory the same as lib level

like this

projectName
 -android
 -ios
 -lib
 -assets
 -pubspec.yaml

then your pubspec.yaml like

  flutter:
  assets:
    - assets/images/

now you can use Image.asset("/assets/images/")

How can I use interface as a C# generic type constraint?

What you have settled for is the best you can do:

public bool Foo<T>() where T : IBase;

Visual Studio debugging/loading very slow

For me it was that I was debugging in Managed Compatibility Mode. In Tools -> Options -> Debugging -> General at the bottom, un-check 'Use Managed Compatibility Mode'. Debugging became instantaneous where it used to take up to a minute to step through one line. I suspect that's what the 'Managed' means in OP's snippets above.

More on that here: https://blogs.msdn.microsoft.com/visualstudioalm/2013/10/16/switching-to-managed-compatibility-mode-in-visual-studio-2013/

Difference between using bean id and name in Spring configuration file

Since Spring 3.1 the id attribute is an xsd:string and permits the same range of characters as the name attribute.

The only difference between an id and a name is that a name can contain multiple aliases separated by a comma, semicolon or whitespace, whereas an id must be a single value.

From the Spring 3.2 documentation:

In XML-based configuration metadata, you use the id and/or name attributes to specify the bean identifier(s). The id attribute allows you to specify exactly one id. Conventionally these names are alphanumeric ('myBean', 'fooService', etc), but may special characters as well. If you want to introduce other aliases to the bean, you can also specify them in the name attribute, separated by a comma (,), semicolon (;), or white space. As a historical note, in versions prior to Spring 3.1, the id attribute was typed as an xsd:ID, which constrained possible characters. As of 3.1, it is now xsd:string. Note that bean id uniqueness is still enforced by the container, though no longer by XML parsers.

What .NET collection provides the fastest search

If it's possible to sort your items then there is a much faster way to do this then doing key lookups into a hashtable or b-tree. Though if you're items aren't sortable you can't really put them into a b-tree anyway.

Anyway, if sortable sort both lists then it's just a matter of walking the lookup list in order.

Walk lookup list
   While items in check list <= lookup list item
     if check list item = lookup list item do something
   Move to next lookup list item

List comprehension vs map

I find list comprehensions are generally more expressive of what I'm trying to do than map - they both get it done, but the former saves the mental load of trying to understand what could be a complex lambda expression.

There's also an interview out there somewhere (I can't find it offhand) where Guido lists lambdas and the functional functions as the thing he most regrets about accepting into Python, so you could make the argument that they're un-Pythonic by virtue of that.

How to know if an object has an attribute in Python

You can check whether object contains attribute by using hasattr builtin method.

For an instance if your object is a and you want to check for attribute stuff

>>> class a:
...     stuff = "something"
... 
>>> hasattr(a,'stuff')
True
>>> hasattr(a,'other_stuff')
False

The method signature itself is hasattr(object, name) -> bool which mean if object has attribute which is passed to second argument in hasattr than it gives boolean True or False according to the presence of name attribute in object.

How to get a cookie from an AJAX response?

You're looking for a response header of Set-Cookie:

xhr.getResponseHeader('Set-Cookie');

It won't work with HTTPOnly cookies though.

Update

According to the XMLHttpRequest Level 1 and XMLHttpRequest Level 2, this particular response headers falls under the "forbidden" response headers that you can obtain using getResponseHeader(), so the only reason why this could work is basically a "naughty" browser.

Correct set of dependencies for using Jackson mapper

Apart from fixing the imports, do a fresh maven clean compile -U. Note the -U option, that brings in new dependencies which sometimes the editor has hard time with. Let the compilation fail due to un-imported classes, but at least you have an option to import them after the maven command.

Just doing Maven->Reimport from Intellij did not work for me.

Git Push Error: insufficient permission for adding an object to repository database

I got this when pulling into an Rstudio project. I realised I forgot to do:

sudo rstudio

on program startup. In fact as there's another bug I've got, I need to actually do:

sudo rstudio --no-sandbox

Laravel 5 call a model function in a blade view

I ran into a similar issue where I wanted to call a function defined in my controller from my view. Although it perplexed me for a while trying to figure out how to get to the controller from the view it turned out to be fairly straightforward.

I hand off an array to my views with data records that the view formats and presents to the user with jQuery DataTables (big duh). One column in the presented UI table is a set of action buttons that need to be created per row based on the content of the data in each of the rows. I guess I could have added the button definitions to the data rows as a column sent to the views but not all views needed the buttons so why? Instead, I wanted the view that needed them add them.

In the controller I pass a reference to the controller itself to the view as in

->with('callbackController', $this)

I called it callbackController as that is what I was doing. Now, inside my view I can either escape to PHP to use $callbackController to access the parent controller as in

<?php echo $callbackController->makeButtons($parameters); ?>

or just use the Blade mechanism

{!! $callbackController->makeButtons($parameters); ?>

It seems to be working fine across multiple controllers and views. I have not noticed a performance penalty using this mechanism and I have one huge table with over 50K rows.

I have not tried to pass on references to other objects (e.g., models, etc) yet but I do not see what that would not work as well

Might not be elegant but it seems to get the job done.

How to POST using HTTPclient content type = application/x-www-form-urlencoded

Another variant to POST this content type and which does not use a dictionary would be:

StringContent postData = new StringContent(JSON_CONTENT, Encoding.UTF8, "application/x-www-form-urlencoded");
using (HttpResponseMessage result = httpClient.PostAsync(url, postData).Result)
{
    string resultJson = result.Content.ReadAsStringAsync().Result;
}

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

Use for in

var obj = { "10":5, "2":7, "3":0, "4":0, "5":0, "6":0, "7":0,
            "8":0, "9":0, "10":0, "11":0, "12":0 };

var objectToArray = function(obj) {
    var _arr = [];

    for (var key in obj) {
        _arr.push([key, obj[key]]);
    }
    return _arr;
}

console.log(objectToArray(obj));

Service Reference Error: Failed to generate code for the service reference

face same issue, resolved by running Visual Studio in Admin mode

Undefined symbols for architecture armv7

I had this warning, when wrote two classes in .h file of another class, but FORGOT to write the implementation for this classes in .m file.

SQLAlchemy insert or update example

assuming certain column names...

INSERT one

newToner = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

dbsession.add(newToner)   
dbsession.commit()

INSERT multiple

newToner1 = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

newToner2 = Toner(toner_id = 2,
                    toner_color = 'red',
                    toner_hex = '#F01731')

dbsession.add_all([newToner1, newToner2])   
dbsession.commit()

UPDATE

q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'

dbsession.commit()

or using a fancy one-liner using MERGE

record = dbsession.merge(Toner( **kwargs))

Control the size of points in an R scatterplot?

Try the cex argument:

?par

  • cex
    A numerical value giving the amount by which plotting text and symbols should be magnified relative to the default. Note that some graphics functions such as plot.default have an argument of this name which multiplies this graphical parameter, and some functions such as points accept a vector of values which are recycled. Other uses will take just the first value if a vector of length greater than one is supplied.

Fast way to concatenate strings in nodeJS/JavaScript

There is not really any other way in JavaScript to concatenate strings.
You could theoretically use .concat(), but that's way slower than just +

Libraries are more often than not slower than native JavaScript, especially on basic operations like string concatenation, or numerical operations.

Simply put: + is the fastest.

Play audio file from the assets directory

Fix of above function for play and pause

  public void playBeep ( String word )
{
    try
    {
        if ( ( m == null ) )
        {

            m = new MediaPlayer ();
        }
        else if( m != null&&lastPlayed.equalsIgnoreCase (word)){
            m.stop();
            m.release ();
            m=null;
            lastPlayed="";
            return;
        }else if(m != null){
            m.release ();
            m = new MediaPlayer ();
        }
        lastPlayed=word;

        AssetFileDescriptor descriptor = context.getAssets ().openFd ( "rings/" + word + ".mp3" );
        long                start      = descriptor.getStartOffset ();
        long                end        = descriptor.getLength ();

        // get title
        // songTitle=songsList.get(songIndex).get("songTitle");
        // set the data source
        try
        {
            m.setDataSource ( descriptor.getFileDescriptor (), start, end );
        }
        catch ( Exception e )
        {
            Log.e ( "MUSIC SERVICE", "Error setting data source", e );
        }

        m.prepare ();
        m.setVolume ( 1f, 1f );
        // m.setLooping(true);
        m.start ();
    }
    catch ( Exception e )
    {
        e.printStackTrace ();
    }
}

Turn off axes in subplots

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2)


To turn off axes for all subplots, do either:

[axi.set_axis_off() for axi in ax.ravel()]

or

map(lambda axi: axi.set_axis_off(), ax.ravel())

How do I open a URL from C++?

Here's an example in windows code using winsock.

#include <winsock2.h>
#include <windows.h>
#include <iostream>
#include <string>
#include <locale>
#pragma comment(lib,"ws2_32.lib")
using namespace std;

string website_HTML;
locale local;


void get_Website(char *url );

int main ()
{
    //open website
    get_Website("www.google.com" );

    //format website HTML
    for (size_t i=0; i<website_HTML.length(); ++i) 
        website_HTML[i]= tolower(website_HTML[i],local);

    //display HTML
    cout <<website_HTML;

    cout<<"\n\n";



    return 0;
}



//***************************
void get_Website(char *url )
{
    WSADATA wsaData;
    SOCKET Socket;
    SOCKADDR_IN SockAddr;


    int lineCount=0;
    int rowCount=0;

    struct hostent *host;
    char *get_http= new char[256];

        memset(get_http,' ', sizeof(get_http) );
        strcpy(get_http,"GET / HTTP/1.1\r\nHost: ");
        strcat(get_http,url);
        strcat(get_http,"\r\nConnection: close\r\n\r\n");

        if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) 
        {
            cout << "WSAStartup failed.\n";
            system("pause");
            //return 1;
        }

        Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
        host = gethostbyname(url);

        SockAddr.sin_port=htons(80);
        SockAddr.sin_family=AF_INET;
        SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);

        cout << "Connecting to "<< url<<" ...\n";

        if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0)
        {
            cout << "Could not connect";
            system("pause");
            //return 1;
        }

        cout << "Connected.\n";     
        send(Socket,get_http, strlen(get_http),0 );

        char buffer[10000];

        int nDataLength;
            while ((nDataLength = recv(Socket,buffer,10000,0)) > 0)
            {       
                int i = 0;

                while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') 
                {                    
                    website_HTML+=buffer[i];                     
                    i += 1;
                }               
            }
        closesocket(Socket);
        WSACleanup();

            delete[] get_http;
}

How to read until end of file (EOF) using BufferedReader in Java?

You are consuming a line at, which is discarded

while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at

BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to

while((str=input.readLine())!=null)

see related post string to bigint

readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

see javadocs

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

Qt 5.1.1: Application failed to start because platform plugin "windows" is missing

The application qtbase/bin/windeployqt.exe deploys automatically your application. If you start a prompt with envirenmentvariables set correctly, it deploys to the current directory. You find an example of script:

@echo off
set QTDIR=E:\QT\5110\vc2017

set INCLUDE=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\ATLMFC\include;S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\include;C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um;C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\ucrt;C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\shared;C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um;C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\winrt;C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\cppwinrt

set LIB=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\ATLMFC\lib\x86;S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\lib\x86;C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x86;C:\Program Files (x86)\Windows Kits\10\lib\10.0.14393.0\ucrt\x86;C:\Program Files (x86)\Windows Kits\10\lib\10.0.14393.0\um\x86;

set LIBPATH=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\ATLMFC\lib\x86;S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\lib\x86;S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\lib\x86\store\references;C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.17134.0;C:\ProgramFiles (x86)\Windows Kits\10\References\10.0.17134.0;C:\Windows\Microsoft.NET\Framework\v4.0.30319;

Path=%QTDIR%\qtbase\bin;%PATH%
set VCIDEInstallDir=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\VC\
set VCINSTALLDIR=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\
set VCToolsInstallDir=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.11.25503\
set VisualStudioVersion=15.0
set VS100COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools\
set VS110COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools\
set VS120COMNTOOLS=S:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\
set VS150COMNTOOLS=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\
set VS80COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 8\Common7\Tools\
set VS90COMNTOOLS=c:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\
set VSINSTALLDIR=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
set VSSDK110Install=C:\Program Files (x86)\Microsoft Visual Studio 11.0\VSSDK\
set VSSDK150INSTALL=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VSSDK
set WindowsLibPath=C:\Program Files (x86)\Windows Kits\10\UnionMetadata;C:\Program Files (x86)\Windows Kits\10\References
set WindowsSdkBinPath=C:\Program Files (x86)\Windows Kits\10\bin\
set WindowsSdkDir=C:\Program Files (x86)\Windows Kits\10\
set WindowsSDKLibVersion=10.0.14393.0\
set WindowsSdkVerBinPath=C:\Program Files (x86)\Windows Kits\10\bin\10.0.14393.0\
set WindowsSDKVersion=10.0.14393.0\
set WindowsSDK_ExecutablePath_x64=C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\x64\
set WindowsSDK_ExecutablePath_x86=C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\

mkdir C:\VCProjects\Application\Build\VS2017_QT5_11_32-Release\setup
cd C:\VCProjects\Application\Build\VS2017_QT5_11_32-Release\setup
copy /Y ..\Release\application.exe .
windeployqt application.exe
pause

javascript: calculate x% of a number

It may be a bit pedantic / redundant with its numeric casting, but here's a safe function to calculate percentage of a given number:

function getPerc(num, percent) {
    return Number(num) - ((Number(percent) / 100) * Number(num));
}

// Usage: getPerc(10000, 25);

How do you change text to bold in Android?

From the XML you can set the textStyle to bold as below

<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Bold text"
   android:textStyle="bold"/>

You can set the TextView to bold programmatically as below

textview.setTypeface(Typeface.DEFAULT_BOLD);

Detecting EOF in C

as a starting point you could try replacing

while(!EOF)

with

while(!feof(stdin))

Ruby replace string with captured regex pattern

\1 in double quotes needs to be escaped. So you want either

"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "\\1")

or

"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, '\1')

see the docs on gsub where it says "If it is a double-quoted string, both back-references must be preceded by an additional backslash."

That being said, if you just want the result of the match you can do:

"Z_sdsd: sdsd".scan(/^Z_.*(?=:)/)

or

"Z_sdsd: sdsd"[/^Z_.*(?=:)/]

Note that the (?=:) is a non-capturing group so that the : doesn't show up in your match.

css rotate a pseudo :after or :before content:""

Inline elements can't be transformed, and pseudo elements are inline by default, so you must apply display: block or display: inline-block to transform them:

_x000D_
_x000D_
#whatever:after {
  content: "\24B6";
  display: inline-block;
  transform: rotate(30deg);
}
_x000D_
<div id="whatever">Some text </div>
_x000D_
_x000D_
_x000D_

What is a reasonable code coverage % for unit tests (and why)?

Code Coverage is a misleading metric if 100% coverage is your goal (instead of 100% testing of all features).

  • You could get a 100% by hitting all the lines once. However you could still miss out testing a particular sequence (logical path) in which those lines are hit.
  • You could not get a 100% but still have tested all your 80%/freq used code-paths. Having tests that test every 'throw ExceptionTypeX' or similar defensive programming guard you've put in is a 'nice to have' not a 'must have'

So trust yourself or your developers to be thorough and cover every path through their code. Be pragmatic and don't chase the magical 100% coverage. If you TDD your code you should get a 90%+ coverage as a bonus. Use code-coverage to highlight chunks of code you have missed (shouldn't happen if you TDD though.. since you write code only to make a test pass. No code can exist without its partner test. )

initialize a numpy array

Introduced in numpy 1.8:

numpy.full

Return a new array of given shape and type, filled with fill_value.

Examples:

>>> import numpy as np
>>> np.full((2, 2), np.inf)
array([[ inf,  inf],
       [ inf,  inf]])
>>> np.full((2, 2), 10)
array([[10, 10],
       [10, 10]])

How to insert a SQLite record with a datetime set to 'now' in Android application?

Method 1

CURRENT_TIME – Inserts only time
CURRENT_DATE – Inserts only date
CURRENT_TIMESTAMP – Inserts both time and date

CREATE TABLE users(
    id INTEGER PRIMARY KEY,
    username TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

Method 2

db.execSQL("INSERT INTO users(username, created_at) 
            VALUES('ravitamada', 'datetime()'");

Method 3 Using java Date functions

private String getDateTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);
}

ContentValues values = new ContentValues();
values.put('username', 'ravitamada');
values.put('created_at', getDateTime());
// insert the row
long id = db.insert('users', null, values);

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

I use serializable classes for the WCF communication between different modules. Below is an example of serializable class which serves as DataContract as well. My approach is to use the power of LINQ to convert the Dictionary into out-of-the-box serializable List<> of KeyValuePair<>:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.Xml.Serialization;

    namespace MyFirm.Common.Data
    {
        [DataContract]
        [Serializable]
        public class SerializableClassX
        {
            // since the Dictionary<> class is not serializable,
            // we convert it to the List<KeyValuePair<>>
            [XmlIgnore]
            public Dictionary<string, int> DictionaryX 
            {
                get
                {
                    return  SerializableList == null ? 
                            null :
                            SerializableList.ToDictionary(item => item.Key, item => item.Value);
                }

                set
                {
                    SerializableList =  value == null ?
                                        null :
                                        value.ToList();
                }
            }

            [DataMember]
            [XmlArray("SerializableList")]
            [XmlArrayItem("Pair")]
            public List<KeyValuePair<string, int>> SerializableList { get; set; }
        }
    }

The usage is straightforward - I assign a dictionary to my data object's dictionary field - DictionaryX. The serialization is supported inside the SerializableClassX by conversion of the assigned dictionary into the serializable List<> of KeyValuePair<>:

    // create my data object
    SerializableClassX SerializableObj = new SerializableClassX(param);

    // this will call the DictionaryX.set and convert the '
    // new Dictionary into SerializableList
    SerializableObj.DictionaryX = new Dictionary<string, int>
    {
        {"Key1", 1},
        {"Key2", 2},
    };

Shrink a YouTube video to responsive width

Okay, looks like big solutions.

Why not to add width: 100%; directly in your iframe. ;)

So your code would looks something like <iframe style="width: 100%;" ...></iframe>

Try this it'll work as it worked in my case.

Enjoy! :)

Installing Numpy on 64bit Windows 7 with Python 2.7.3

Try the (unofficial) binaries in this site:

http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy

You can get the newest numpy x64 with or without Intel MKL libs for Python 2.7 or Python 3.

What is the difference between join and merge in Pandas?

To put it analogously to SQL "Pandas merge is to outer/inner join and Pandas join is to natural join". Hence when you use merge in pandas, you want to specify which kind of sqlish join you want to use whereas when you use pandas join, you really want to have a matching column label to ensure it joins

In SQL, is UPDATE always faster than DELETE+INSERT?

Delete + Insert is almost always faster because an Update has way more steps involved.

Update:

  1. Look for the row using PK.
  2. Read the row from disk.
  3. Check for which values have changed
  4. Raise the onUpdate Trigger with populated :NEW and :OLD variables
  5. Write New variables to disk (The entire row)

    (This repeats for every row you're updating)

Delete + Insert:

  1. Mark rows as deleted (Only in the PK).
  2. Insert new rows at the end of the table.
  3. Update PK Index with locations of new records.

    (This doesn't repeat, all can be perfomed in a single block of operation).

Using Insert + Delete will fragment your File System, but not that fast. Doing a lazy optimization on the background will allways free unused blocks and pack the table altogether.

How to SSH to a VirtualBox guest externally through a host?

Simply setting the Network Setting to bridged did the trick for me.

Your IP will change when you do this. However, in my case it didn't change immediately. ifconfig returned the same ip. I rebooted the vm and boom, the ip set itself to one start with 192.* and I was immediately allowed ssh access.

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Try using TempData:

public ActionResult Create(FormCollection collection) {
  ...
  TempData["notice"] = "Successfully registered";
  return RedirectToAction("Index");
  ...
}

Then, in your Index view, or master page, etc., you can do this:

<% if (TempData["notice"] != null) { %>
  <p><%= Html.Encode(TempData["notice"]) %></p>
<% } %>

Or, in a Razor view:

@if (TempData["notice"] != null) {
  <p>@TempData["notice"]</p>
}

Quote from MSDN (page no longer exists as of 2014, archived copy here):

An action method can store data in the controller's TempDataDictionary object before it calls the controller's RedirectToAction method to invoke the next action. The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.

How do I check two or more conditions in one <c:if>?

Recommendation:

when you have more than one condition with and and or is better separate with () to avoid verification problems

<c:if test="${(not validID) and (addressIso == 'US' or addressIso == 'BR')}">

SQL Server: Query fast, but slow from procedure

This is probably unlikely, but given that your observed behaviour is unusual it needs to be checked and no-one else has mentioned it.

Are you absolutely sure that all objects are owned by dbo and you don't have a rogue copies owned by yourself or a different user present as well?

Just occasionally when I've seen odd behaviour it's because there was actually two copies of an object and which one you get depends on what is specified and who you are logged on as. For example it is perfectly possible to have two copies of a view or procedure with the same name but owned by different owners - a situation that can arise where you are not logged onto the database as a dbo and forget to specify dbo as object owner when you create the object.

In note that in the text you are running some things without specifying owner, eg

sp_recompile ViewOpener

if for example there where two copies of viewOpener present owned by dbo and [some other user] then which one you actually recompile if you don't specify is dependent upon circumstances. Ditto with the Report_Opener view - if there where two copies (and they could differ in specification or execution plan) then what is used depends upon circumstances - and as you do not specify owner it is perfectly possible that your adhoc query might use one and the compiled procedure might use use the other.

As I say, it's probably unlikely but it is possible and should be checked because your issues could be that you're simply looking for the bug in the wrong place.

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

Simple solution using itertools that preserves order (latter dicts have precedence)

# py2
from itertools import chain, imap
merge = lambda *args: dict(chain.from_iterable(imap(dict.iteritems, args)))

# py3
from itertools import chain
merge = lambda *args: dict(chain.from_iterable(map(dict.items, args)))

And it's usage:

>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> merge(x, y)
{'a': 1, 'b': 10, 'c': 11}

>>> z = {'c': 3, 'd': 4}
>>> merge(x, y, z)
{'a': 1, 'b': 10, 'c': 3, 'd': 4}

How to clear Facebook Sharer cache?

If you used managed wordpress or caching plugins, you have to CLEAR YOUR CACHE before the facebook debugger tool can fetch new info!

I've been pulling my hair out for weeks figuring out why changes I made wouldn't show up in facebook debugger for 24 hours!!!! The fix is I have to go into my wordpress dashboard, click the godaddy icon on the top, and click "flush cache." I think many managed wordpress hosters have a cache to figure out how to clear it and you'll be golden.

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

You can also solve this problem by doing a:

rm -rf <tomcat-dir>/work/* <tomcat-dir>/temp/*

Clearing out the work and temp directories makes Tomcat do a clean startup.

Python variables as keys to dict

Well this is a bit, umm ... non-Pythonic ... ugly ... hackish ...

Here's a snippet of code assuming you want to create a dictionary of all the local variables you create after a specific checkpoint is taken:

checkpoint = [ 'checkpoint' ] + locals().keys()[:]
## Various local assigments here ...
var_keys_since_checkpoint = set(locals().keys()) - set(checkpoint)
new_vars = dict()
for each in var_keys_since_checkpoint:
   new_vars[each] = locals()[each]

Note that we explicitly add the 'checkpoint' key into our capture of the locals().keys() I'm also explicitly taking a slice of that though it shouldn't be necessary in this case since the reference has to be flattened to add it to the [ 'checkpoint' ] list. However, if you were using a variant of this code and tried to shortcut out the ['checkpoint'] + portion (because that key was already inlocals(), for example) ... then, without the [:] slice you could end up with a reference to thelocals().keys()` whose values would change as you added variables.

Offhand I can't think of a way to call something like new_vars.update() with a list of keys to be added/updated. So thefor loop is most portable. I suppose a dictionary comprehension could be used in more recent versions of Python. However that woudl seem to be nothing more than a round of code golf.

Best/Most Comprehensive API for Stocks/Financial Data

Markit On Demand provides a set of free financial APIs for playing around with. Looks like there is a stock quote API, a stock ticker/company search and a charting API available. Look at http://dev.markitondemand.com

HTML meta tag for content language

Html5 also recommend to use <html lang="es-ES"> The small letter lang tag only specifies: language code The large letter specifies: country code

This is really useful for ie.Chrome, when the browser is proposing to translate web content(ie google translate)

How can I create a border around an Android LinearLayout?

Try This in your res/drawable

    <?xml version="1.0" encoding="UTF-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
  <shape
    android:shape="rectangle">
    <padding android:left="15dp"
        android:right="15dp"
        android:top="15dp"
        android:bottom="15dp"/>
    <stroke android:width="10dp"
        android:color="@color/colorPrimary"/>
  </shape>
</item><item android:left="-5dp"
        android:right="-5dp"
        android:top="-5dp"
        android:bottom="-5dp">
  <shape android:shape="rectangle">
    <solid android:color="@color/background" />
  </shape></item></layer-list>

Python Dictionary Comprehension

Consider this example of counting the occurrence of words in a list using dictionary comprehension

my_list = ['hello', 'hi', 'hello', 'today', 'morning', 'again', 'hello']
my_dict = {k:my_list.count(k) for k in my_list}
print(my_dict)

And the result is

{'again': 1, 'hi': 1, 'hello': 3, 'today': 1, 'morning': 1}

Change the background color of CardView programmatically

It is very simple in kotlin. Use ColorStateList to change card view colour

   var color = R.color.green;
   cardView.setCardBackgroundColor(context.colorList(color));

A kotlin extension of ColorStateList:

fun Context.colorList(id: Int): ColorStateList {
    return ColorStateList.valueOf(ContextCompat.getColor(this, color))
}

"End of script output before headers" error in Apache

If this is a CGI script for the web, then you must output your header:

#!"C:\xampp\perl\bin\perl.exe"

print "Content-Type: text/html\n\n";
print "Hello World";

The following error message tells you this End of script output before headers: sample.pl

Or even better, use the CGI module to output the header:

#!"C:\xampp\perl\bin\perl.exe"

use strict;
use warnings;

use CGI;

print CGI::header();
print "Hello World";

Update label from another thread

Use MethodInvoker for updating label text in other thread.

private void AggiornaContatore()
{
    MethodInvoker inv = delegate 
    {
      this.lblCounter.Text = this.index.ToString(); 
    }

 this.Invoke(inv);
}

You are getting the error because your UI thread is holding the label, and since you are trying to update it through another thread you are getting cross thread exception.

You may also see: Threading in Windows Forms

Android checkbox style

The correct way to do it for Material design is :

Style :

<style name="MyCheckBox" parent="Theme.AppCompat.Light">  
    <item name="colorControlNormal">@color/foo</item>
    <item name="colorControlActivated">@color/bar</item>
</style>  

Layout :

<CheckBox  
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:text="Check Box"
    android:theme="@style/MyCheckBox"/>

It will preserve Material animations on Lollipop+.

Convert int to string?

int num = 10;
string str = Convert.ToString(num);

@font-face not working

Not sure exactly what your problem is, but try the following:

  1. Do the font files exist?
  2. Do you need quotes around the URLs?
  3. Are you using a CSS3-enabled browser?

Check here for examples, if they don't work for you then you have another problem

Edit:

You have a bunch of repeated declarations in your source, does this work?

@font-face { font-family: Gotham; src: url('../fonts/gothammedium.eot'); }

a { font-family:Gotham,Verdana,Arial; }

Permission denied (publickey) when SSH Access to Amazon EC2 instance

you must check these few things:

  1. Make sure your IP address is correct
  2. Make sure you are using the correct Key
  3. Make sure you are using the correct username, you can try: 3.1. admin 3.2. ec2-user 3.3. ubuntu

I had the same problem, and it solved after I changed username to ubuntu. In AWS documentation was mentioned to user ec2-user but somehow does not work for me.

node.js - request - How to "emitter.setMaxListeners()"?

This is how I solved the problem:

In main.js of the 'request' module I added one line:

Request.prototype.request = function () {
  var self = this
  self.setMaxListeners(0); // Added line

This defines unlimited listeners http://nodejs.org/docs/v0.4.7/api/events.html#emitter.setMaxListeners

In my code I set the 'maxRedirects' value explicitly:

var options = {uri:headingUri, headers:headerData, maxRedirects:100};

How to convert list of numpy arrays into single numpy array?

Starting in NumPy version 1.10, we have the method stack. It can stack arrays of any dimension (all equal):

# List of arrays.
L = [np.random.randn(5,4,2,5,1,2) for i in range(10)]

# Stack them using axis=0.
M = np.stack(L)
M.shape # == (10,5,4,2,5,1,2)
np.all(M == L) # == True

M = np.stack(L, axis=1)
M.shape # == (5,10,4,2,5,1,2)
np.all(M == L) # == False (Don't Panic)

# This are all true    
np.all(M[:,0,:] == L[0]) # == True
all(np.all(M[:,i,:] == L[i]) for i in range(10)) # == True

Enjoy,

Getting DOM node from React child element

If you want to access any DOM element simply add ref attribute and you can directly access that element.

<input type="text" ref="myinput">

And then you can directly:

componentDidMount: function() 
{
    this.refs.myinput.select();

},

Their is no need of using ReactDOM.findDOMNode(), if you have added a ref to any element.

Java creating .jar file

In order to create a .jar file, you need to use jar instead of java:

jar cf myJar.jar myClass.class

Additionally, if you want to make it executable, you need to indicate an entry point (i.e., a class with public static void main(String[] args)) for your application. This is usually accomplished by creating a manifest file that contains the Main-Class header (e.g., Main-Class: myClass).

However, as Mark Peters pointed out, with JDK 6, you can use the e option to define the entry point:

jar cfe myJar.jar myClass myClass.class 

Finally, you can execute it:

java -jar myJar.jar

See also

MySQL JOIN the most recent row only?

I know this question is old, but it's got a lot of attention over the years and I think it's missing a concept which may help someone in a similar case. I'm adding it here for completeness sake.

If you cannot modify your original database schema, then a lot of good answers have been provided and solve the problem just fine.

If you can, however, modify your schema, I would advise to add a field in your customer table that holds the id of the latest customer_data record for this customer:

CREATE TABLE customer (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  current_data_id INT UNSIGNED NULL DEFAULT NULL
);

CREATE TABLE customer_data (
   id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
   customer_id INT UNSIGNED NOT NULL, 
   title VARCHAR(10) NOT NULL,
   forename VARCHAR(10) NOT NULL,
   surname VARCHAR(10) NOT NULL
);

Querying customers

Querying is as easy and fast as it can be:

SELECT c.*, d.title, d.forename, d.surname
FROM customer c
INNER JOIN customer_data d on d.id = c.current_data_id
WHERE ...;

The drawback is the extra complexity when creating or updating a customer.

Updating a customer

Whenever you want to update a customer, you insert a new record in the customer_data table, and update the customer record.

INSERT INTO customer_data (customer_id, title, forename, surname) VALUES(2, 'Mr', 'John', 'Smith');
UPDATE customer SET current_data_id = LAST_INSERT_ID() WHERE id = 2;

Creating a customer

Creating a customer is just a matter of inserting the customer entry, then running the same statements:

INSERT INTO customer () VALUES ();

SET @customer_id = LAST_INSERT_ID();
INSERT INTO customer_data (customer_id, title, forename, surname) VALUES(@customer_id, 'Mr', 'John', 'Smith');
UPDATE customer SET current_data_id = LAST_INSERT_ID() WHERE id = @customer_id;

Wrapping up

The extra complexity for creating/updating a customer might be fearsome, but it can easily be automated with triggers.

Finally, if you're using an ORM, this can be really easy to manage. The ORM can take care of inserting the values, updating the ids, and joining the two tables automatically for you.

Here is how your mutable Customer model would look like:

class Customer
{
    private int id;
    private CustomerData currentData;

    public Customer(String title, String forename, String surname)
    {
        this.update(title, forename, surname);
    }

    public void update(String title, String forename, String surname)
    {
        this.currentData = new CustomerData(this, title, forename, surname);
    }

    public String getTitle()
    {
        return this.currentData.getTitle();
    }

    public String getForename()
    {
        return this.currentData.getForename();
    }

    public String getSurname()
    {
        return this.currentData.getSurname();
    }
}

And your immutable CustomerData model, that contains only getters:

class CustomerData
{
    private int id;
    private Customer customer;
    private String title;
    private String forename;
    private String surname;

    public CustomerData(Customer customer, String title, String forename, String surname)
    {
        this.customer = customer;
        this.title    = title;
        this.forename = forename;
        this.surname  = surname;
    }

    public String getTitle()
    {
        return this.title;
    }

    public String getForename()
    {
        return this.forename;
    }

    public String getSurname()
    {
        return this.surname;
    }
}

Retain precision with double in Java

Use java.math.BigDecimal

Doubles are binary fractions internally, so they sometimes cannot represent decimal fractions to the exact decimal.

How to convert a String to Bytearray

Since I cannot comment on the answer, I'd build on Jin Izzraeel's answer

var myBuffer = [];
var str = 'Stack Overflow';
var buffer = new Buffer(str, 'utf16le');
for (var i = 0; i < buffer.length; i++) {
    myBuffer.push(buffer[i]);
}

console.log(myBuffer);

by saying that you could use this if you want to use a Node.js buffer in your browser.

https://github.com/feross/buffer

Therefore, Tom Stickel's objection is not valid, and the answer is indeed a valid answer.

Indentation Error in Python

You are mixing tabs and spaces.

Find the exact location with:

python -tt yourscript.py

and replace all tabs with spaces. You really want to configure your text editor to only insert spaces for tabs as well.

Find the most frequent number in a NumPy array

You may use

values, counts = np.unique(a, return_counts=True)

ind = np.argmax(counts)
print(values[ind])  # prints the most frequent element

ind = np.argpartition(-counts, kth=10)[:10]
print(values[ind])  # prints the 10 most frequent elements

If some element is as frequent as another one, this code will return only the first element.

Convert List<T> to ObservableCollection<T> in WP7

To convert List<T> list to observable collection you may use following code:

var oc = new ObservableCollection<T>();
list.ForEach(x => oc.Add(x));

Default argument values in JavaScript functions

You cannot add default values for function parameters. But you can do this:

function tester(paramA, paramB){
 if (typeof paramA == "undefined"){
   paramA = defaultValue;
 }
 if (typeof paramB == "undefined"){
   paramB = defaultValue;
 }
}

Convert ArrayList<String> to String[] array

Try this

String[] arr = list.toArray(new String[list.size()]);

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

And do not forget the "new" service type (from the k8s docu):

ExternalName: Maps the Service to the contents of the externalName field (e.g. foo.bar.example.com), by returning a CNAME record with its value. No proxying of any kind is set up.

Note: You need either kube-dns version 1.7 or CoreDNS version 0.0.8 or higher to use the ExternalName type.

Compress files while reading data from STDIN

gzip > stdin.gz perhaps? Otherwise, you need to flesh out your question.

Can you set a border opacity in CSS?

No, there is no way to only set the opacity of a border with css.

For example, if you did not know the color, there is no way to only change the opacity of the border by simply using rgba().

What is Parse/parsing?

Parsing means we are analyzing an object specifically. For example, when we enter some keywords in a search engine, they parse the keywords and give back results by searching for each word. So it is basically taking a string from the file and processing it to extract the information we want.

Example of parsing using indexOf to calculate the position of a string in another string:

String s="What a Beautiful day!";

int i=s.indexOf("day");//value of i would be 17
int j=s.indexOf("be");//value of j would be -1
int k=s.indexOf("ea");//value of k would be 8

paresInt essentially converts a String to a Integer.

String s="9876543";
int a=new Integer(s);//uses constructor
System.out.println("Constructor method: " + a);
a=Integer.parseInt(s);//uses parseInt() method
System.out.println("parseInt() method: " + a);

Output:

Constructor method: 9876543

parseInt() method: 9876543

Links in <select> dropdown options

Maybe this will help:

<select onchange="location = this.value;">
 <option value="home.html">Home</option>
 <option value="contact.html">Contact</option>
 <option value="about.html">About</option>
</select>

unable to install pg gem

  • Ubuntu 20.10 (pop!_os)
  • Ruby 2.7.2
  • Rails 3.1.0
  • Postgresql 12

Uninstall and then reinstall postgresql-client libpq5 libpq-dev

sudo apt remove postgresql-client libpq5 libpq-dev
sudo apt install postgresql-client libpq5 libpq-dev

Then install the pg gem again pointing at /usr/lib to find the pg library:

gem install pg  --   --with-pg-lib=/usr/lib

Output (what you should see after the previous command):

Building native extensions with: '--with-pg-lib=/usr/lib'
This could take a while...
Successfully installed pg-1.2.3
Parsing documentation for pg-1.2.3
Installing ri documentation for pg-1.2.3
Done installing documentation for pg after 1 seconds
1 gem installed

Gem should install, then continue with normal bundle install or update:

bundle
bundle install
bundle update

Why does .NET foreach loop throw NullRefException when collection is null?

It is being answer long back but i have tried to do this in the following way to just avoid null pointer exception and may be useful for someone using C# null check operator ?.

     //fragments is a list which can be null
     fragments?.ForEach((obj) =>
        {
            //do something with obj
        });

Why is there an unexplainable gap between these inline-block div elements?

Found a solution not involving Flex, because Flex doesn't work in older Browsers. Example:

.container {
    display:block;
    position:relative;
    height:150px;
    width:1024px;
    margin:0 auto;
    padding:0px;
    border:0px;
    background:#ececec;
    margin-bottom:10px;
    text-align:justify;
    box-sizing:border-box;
    white-space:nowrap;
    font-size:0pt;
    letter-spacing:-1em;
}

.cols {
    display:inline-block;
    position:relative;
    width:32%;
    height:100%;
    margin:0 auto;
    margin-right:2%;
    border:0px;
    background:lightgreen;  
    box-sizing:border-box;
    padding:10px;
    font-size:10pt;
    letter-spacing:normal;
}

.cols:last-child {
    margin-right:0;
}

Mockito: Mock private field initialization

Using @Jarda's guide you can define this if you need to set the variable the same value for all tests:

@Before
public void setClientMapper() throws NoSuchFieldException, SecurityException{
    FieldSetter.setField(client, client.getClass().getDeclaredField("mapper"), new Mapper());
}

But beware that setting private values to be different should be handled with care. If they are private are for some reason.

Example, I use it, for example, to change the wait time of a sleep in the unit tests. In real examples I want to sleep for 10 seconds but in unit-test I'm satisfied if it's immediate. In integration tests you should test the real value.

Change default date time format on a single database in SQL Server

If this really is a QA issue and you can't change the code. Setup a new server instance on the machine and setup the language as "British English"

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.

"Object doesn't support this property or method" error in IE11

This unfortunately breaks other things. Here is the fix I found on another site that seemed to work for me:

I'd say leave the X-UA-Compatible as "IE=8" and add the following code to the bottom of your master page:

<script language="javascript">
    /* IE11 Fix for SP2010 */
    if (typeof(UserAgentInfo) != 'undefined' && !window.addEventListener) 
    {
        UserAgentInfo.strBrowser=1; 
    } 
</script>

This fixes a bug in core.js which incorrectly calculates that sets UserAgentInfo.strBrowse=3 for IE11 and thus supporting addEventListener. I'm not entirely sure on the details other than that but the combination of keeping IE=8 and using this script is working for me. Fingers crossed until I find the next IE11/SharePoint "bug"!

What are the differences between git branch, fork, fetch, merge, rebase and clone?

Here is Oliver Steele's image of how it all fits together:

enter image description here

Can't use System.Windows.Forms

To add the reference to "System.Windows.Forms", it seems to be a little different for Visual Studio Community 2017.

1) Go to solution explorer and select references

enter image description here

2) Right-click and select Add references enter image description here

3) In Assemblies, check System.Windows.Forms and press ok

enter image description here

4) That's it.

jQuery find events handlers registered with an object

I've combined both solutions from @jps to one function:

jQuery.fn.getEvents = function() {
    if (typeof(jQuery._data) === 'function') {
        return jQuery._data(this.get(0), 'events') || {};
    }

    // jQuery version < 1.7.?
    if (typeof(this.data) === 'function') {
        return this.data('events') || {};
    }

    return {};
};

But beware, this function can only return events that were set using jQuery itself.

Howto: Clean a mysql InnoDB storage engine?

Here is a more complete answer with regard to InnoDB. It is a bit of a lengthy process, but can be worth the effort.

Keep in mind that /var/lib/mysql/ibdata1 is the busiest file in the InnoDB infrastructure. It normally houses six types of information:

InnoDB Architecture

InnoDB Architecture

Many people create multiple ibdata files hoping for better disk-space management and performance, however that belief is mistaken.

Can I run OPTIMIZE TABLE ?

Unfortunately, running OPTIMIZE TABLE against an InnoDB table stored in the shared table-space file ibdata1 does two things:

  • Makes the table’s data and indexes contiguous inside ibdata1
  • Makes ibdata1 grow because the contiguous data and index pages are appended to ibdata1

You can however, segregate Table Data and Table Indexes from ibdata1 and manage them independently.

Can I run OPTIMIZE TABLE with innodb_file_per_table ?

Suppose you were to add innodb_file_per_table to /etc/my.cnf (my.ini). Can you then just run OPTIMIZE TABLE on all the InnoDB Tables?

Good News : When you run OPTIMIZE TABLE with innodb_file_per_table enabled, this will produce a .ibd file for that table. For example, if you have table mydb.mytable witha datadir of /var/lib/mysql, it will produce the following:

  • /var/lib/mysql/mydb/mytable.frm
  • /var/lib/mysql/mydb/mytable.ibd

The .ibd will contain the Data Pages and Index Pages for that table. Great.

Bad News : All you have done is extract the Data Pages and Index Pages of mydb.mytable from living in ibdata. The data dictionary entry for every table, including mydb.mytable, still remains in the data dictionary (See the Pictorial Representation of ibdata1). YOU CANNOT JUST SIMPLY DELETE ibdata1 AT THIS POINT !!! Please note that ibdata1 has not shrunk at all.

InnoDB Infrastructure Cleanup

To shrink ibdata1 once and for all you must do the following:

  1. Dump (e.g., with mysqldump) all databases into a .sql text file (SQLData.sql is used below)

  2. Drop all databases (except for mysql and information_schema) CAVEAT : As a precaution, please run this script to make absolutely sure you have all user grants in place:

    mkdir /var/lib/mysql_grants
    cp /var/lib/mysql/mysql/* /var/lib/mysql_grants/.
    chown -R mysql:mysql /var/lib/mysql_grants
    
  3. Login to mysql and run SET GLOBAL innodb_fast_shutdown = 0; (This will completely flush all remaining transactional changes from ib_logfile0 and ib_logfile1)

  4. Shutdown MySQL

  5. Add the following lines to /etc/my.cnf (or my.ini on Windows)

    [mysqld]
    innodb_file_per_table
    innodb_flush_method=O_DIRECT
    innodb_log_file_size=1G
    innodb_buffer_pool_size=4G
    

    (Sidenote: Whatever your set for innodb_buffer_pool_size, make sure innodb_log_file_size is 25% of innodb_buffer_pool_size.

    Also: innodb_flush_method=O_DIRECT is not available on Windows)

  6. Delete ibdata* and ib_logfile*, Optionally, you can remove all folders in /var/lib/mysql, except /var/lib/mysql/mysql.

  7. Start MySQL (This will recreate ibdata1 [10MB by default] and ib_logfile0 and ib_logfile1 at 1G each).

  8. Import SQLData.sql

Now, ibdata1 will still grow but only contain table metadata because each InnoDB table will exist outside of ibdata1. ibdata1 will no longer contain InnoDB data and indexes for other tables.

For example, suppose you have an InnoDB table named mydb.mytable. If you look in /var/lib/mysql/mydb, you will see two files representing the table:

  • mytable.frm (Storage Engine Header)
  • mytable.ibd (Table Data and Indexes)

With the innodb_file_per_table option in /etc/my.cnf, you can run OPTIMIZE TABLE mydb.mytable and the file /var/lib/mysql/mydb/mytable.ibd will actually shrink.

I have done this many times in my career as a MySQL DBA. In fact, the first time I did this, I shrank a 50GB ibdata1 file down to only 500MB!

Give it a try. If you have further questions on this, just ask. Trust me; this will work in the short term as well as over the long haul.

CAVEAT

At Step 6, if mysql cannot restart because of the mysql schema begin dropped, look back at Step 2. You made the physical copy of the mysql schema. You can restore it as follows:

mkdir /var/lib/mysql/mysql
cp /var/lib/mysql_grants/* /var/lib/mysql/mysql
chown -R mysql:mysql /var/lib/mysql/mysql

Go back to Step 6 and continue

UPDATE 2013-06-04 11:13 EDT

With regard to setting innodb_log_file_size to 25% of innodb_buffer_pool_size in Step 5, that's blanket rule is rather old school.

Back on July 03, 2006, Percona had a nice article why to choose a proper innodb_log_file_size. Later, on Nov 21, 2008, Percona followed up with another article on how to calculate the proper size based on peak workload keeping one hour's worth of changes.

I have since written posts in the DBA StackExchange about calculating the log size and where I referenced those two Percona articles.

Personally, I would still go with the 25% rule for an initial setup. Then, as the workload can more accurate be determined over time in production, you could resize the logs during a maintenance cycle in just minutes.

Change first commit of project with Git?

git rebase -i allows you to conveniently edit any previous commits, except for the root commit. The following commands show you how to do this manually.

# tag the old root, "git rev-list ..." will return the hash of first commit
git tag root `git rev-list HEAD | tail -1`

# switch to a new branch pointing at the first commit
git checkout -b new-root root

# make any edits and then commit them with:
git commit --amend

# check out the previous branch (i.e. master)
git checkout @{-1}

# replace old root with amended version
git rebase --onto new-root root

# you might encounter merge conflicts, fix any conflicts and continue with:
# git rebase --continue

# delete the branch "new-root"
git branch -d new-root

# delete the tag "root"
git tag -d root

How can I run a PHP script in the background after a form is submitted?

If you're on Windows, research proc_open or popen...

But if we're on the same server "Linux" running cpanel then this is the right approach:

#!/usr/bin/php 
<?php
$pid = shell_exec("nohup nice php -f            
'path/to/your/script.php' /dev/null 2>&1 & echo $!");
While(exec("ps $pid"))
{ //you can also have a streamer here like fprintf,        
 // or fgets
}
?>

Don't use fork() or curl if you doubt you can handle them, it's just like abusing your server

Lastly, on the script.php file which is called above, take note of this make sure you wrote:

<?php
ignore_user_abort(TRUE);
set_time_limit(0);
ob_start();
// <-- really optional but this is pure php

//Code to be tested on background

ob_flush(); flush(); 
//this two do the output process if you need some.        
//then to make all the logic possible


str_repeat(" ",1500); 
//.for progress bars or loading images

sleep(2); //standard limit

?>

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

You can also define a class for the bullets you want to show, so in the CSS:

ul {list-style:none; list-style-type:none; list-style-image:none;}

And in the HTML you just define which lists to show:

<ul style="list-style:disc;">

Or you alternatively define a CSS class:

.show-list {list-style:disc;}

Then apply it to the list you want to show:

<ul class="show-list">

All other lists won't show the bullets...

AngularJS For Loop with Numbers & Ranges

Set Scope in controller

var range = [];
for(var i=20;i<=70;i++) {
  range.push(i);
}
$scope.driverAges = range;

Set Repeat in Html Template File

<select type="text" class="form-control" name="driver_age" id="driver_age">
     <option ng-repeat="age in driverAges" value="{{age}}">{{age}}</option>
</select>

jQuery / Javascript code check, if not undefined

I like this:

if (wlocation !== undefined)

But if you prefer the second way wouldn't be as you posted. It would be:

if (typeof wlocation  !== "undefined")

How can I check if my Element ID has focus?

Write below code in script and also add jQuery library

var getElement = document.getElementById('myID');

if (document.activeElement === getElement) {
        $(document).keydown(function(event) {
            if (event.which === 40) {
                console.log('keydown pressed')
            }
        });
    }

Thank you...

Getting value of selected item in list box as string

If you want to retrieve the display text of the item, use the GetItemText method:

string text = listBox1.GetItemText(listBox1.SelectedItem);

"java.lang.OutOfMemoryError: PermGen space" in Maven build

If you want to make this part of your POM for a repeatable build, you can use the fork-variant of a few of the plugins (especially compiler:compile and surefire:test):

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.2</version>
    <configuration>
      <fork>true</fork>
      <meminitial>128m</meminitial>
      <maxmem>1024m</maxmem>
      <compilerArgs>
        <arg>-XX:MaxPermSize=256m</arg>
      </compilerArgs>
    </configuration>
  </plugin>

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18</version>
    <configuration>
        <forkCount>1</forkCount>
        <argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
    </configuration>
</plugin>

Gradle task - pass arguments to Java application

Since Gradle 4.9, the command line arguments can be passed with --args. For example, if you want to launch the application with command line arguments foo --bar, you can use

gradle run --args='foo --bar'

See Also Gradle Application Plugin

How to upgrade Gradle wrapper

Should __init__() call the parent class's __init__()?

In Python, calling the super-class' __init__ is optional. If you call it, it is then also optional whether to use the super identifier, or whether to explicitly name the super class:

object.__init__(self)

In case of object, calling the super method is not strictly necessary, since the super method is empty. Same for __del__.

On the other hand, for __new__, you should indeed call the super method, and use its return as the newly-created object - unless you explicitly want to return something different.

Set 4 Space Indent in Emacs in Text Mode

By the way, for C-mode, I add (setq-default c-basic-offset 4) to .emacs. See http://www.emacswiki.org/emacs/IndentingC for details.

How to create a new img tag with JQuery, with the src and id from a JavaScript object?

In jQuery, a new element can be created by passing a HTML string to the constructor, as shown below:

var img = $('<img id="dynamic">'); //Equivalent: $(document.createElement('img'))
img.attr('src', responseObject.imgurl);
img.appendTo('#imagediv');

MySQL show current connection info

You can use the status command in MySQL client.

mysql> status;
--------------
mysql  Ver 14.14 Distrib 5.5.8, for Win32 (x86)

Connection id:          1
Current database:       test
Current user:           ODBC@localhost
SSL:                    Not in use
Using delimiter:        ;
Server version:         5.5.8 MySQL Community Server (GPL)
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    gbk
Conn.  characterset:    gbk
TCP port:               3306
Uptime:                 7 min 16 sec

Threads: 1  Questions: 21  Slow queries: 0  Opens: 33  Flush tables: 1  Open tables: 26  Queries per second avg: 0.48
--------------

mysql>

On linux SUSE or RedHat, how do I load Python 2.7

The accepted answer by dr jimbob (using make altinstall) got me most of the way there, with python2.7 in /usr/local/bin but I also needed to install some third party modules. The nice thing is that easy_install gets its installation locations from the version of Python you are running, but I found I still needed to install easy_install for Python 2.7 otherwise I would get ImportError: No module named pkg_resources. So I did this:

wget http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg
sudo -i
export PATH=$PATH:/usr/local/bin
sh setuptools-0.6c11-py2.7.egg
exit

Now I have easy_install and easy_install-2.7 in /usr/local/bin and the former overrides my system's 2.6 version of easy_install, so I removed it:

sudo rm /usr/local/bin/easy_install

Now I can install libraries for the 2.7 version of Python like this:

sudo /usr/local/bin/easy_install-2.7 numpy

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

Gradients in Internet Explorer 9

I understand that IE9 still won't be supporting CSS gradients. Which is a shame, because it's supporting loads of other great new stuff.

You might want to look into CSS3Pie as a way of getting all versions of IE to support various CSS3 features (including gradients, but also border-radius and box-shadow) with the minimum of fuss.

I believe CSS3Pie works with IE9 (I've tried it on the pre-release versions, but not yet on the current beta).

Which rows are returned when using LIMIT with OFFSET in MySQL?

OFFSET is nothing but a keyword to indicate starting cursor in table

SELECT column FROM table LIMIT 18 OFFSET 8 -- fetch 18 records, begin with record 9 (OFFSET 8)

you would get the same result form

SELECT column FROM table LIMIT 8, 18

visual representation (R is one record in the table in some order)

 OFFSET        LIMIT          rest of the table
 __||__   _______||_______   __||__
/      \ /                \ /
RRRRRRRR RRRRRRRRRRRRRRRRRR RRRR...
         \________________/
                 ||
             your result

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Try below code,

$cookieFile = "cookies.txt";
if(!file_exists($cookieFile)) {
    $fh = fopen($cookieFile, "w");
    fwrite($fh, "");
    fclose($fh);
}


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_VERBOSE, true);
if(!curl_exec($ch)){
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
else{
    $response = curl_exec($ch); 
}
curl_close($ch);
$result = json_decode($response, true);

echo '<pre>';
var_dump($result);
echo'</pre>';

I hope this will help you.

Best regards, Dasitha.

How to get N rows starting from row M from sorted table in T-SQL

UPDATE If you you are using SQL 2012 new syntax was added to make this really easy. See Implement paging (skip / take) functionality with this query

I guess the most elegant is to use the ROW_NUMBER function (available from MS SQL Server 2005):

WITH NumberedMyTable AS
(
    SELECT
        Id,
        Value,
        ROW_NUMBER() OVER (ORDER BY Id) AS RowNumber
    FROM
        MyTable
)
SELECT
    Id,
    Value
FROM
    NumberedMyTable
WHERE
    RowNumber BETWEEN @From AND @To

How can I get a process handle by its name in C++?

#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>

int main( int, char *[] )
{
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry) == TRUE)
    {
        while (Process32Next(snapshot, &entry) == TRUE)
        {
            if (stricmp(entry.szExeFile, "target.exe") == 0)
            {  
                HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);

                // Do stuff..

                CloseHandle(hProcess);
            }
        }
    }

    CloseHandle(snapshot);

    return 0;
}

Also, if you'd like to use PROCESS_ALL_ACCESS in OpenProcess, you could try this:

#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>

void EnableDebugPriv()
{
    HANDLE hToken;
    LUID luid;
    TOKEN_PRIVILEGES tkp;

    OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);

    LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid);

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Luid = luid;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    AdjustTokenPrivileges(hToken, false, &tkp, sizeof(tkp), NULL, NULL);

    CloseHandle(hToken); 
}

int main( int, char *[] )
{
    EnableDebugPriv();

    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry) == TRUE)
    {
        while (Process32Next(snapshot, &entry) == TRUE)
        {
            if (stricmp(entry.szExeFile, "target.exe") == 0)
            {  
                HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);

                // Do stuff..

                CloseHandle(hProcess);
            }
        }
    }

    CloseHandle(snapshot);

    return 0;
}

Python OpenCV2 (cv2) wrapper to get image size?

cv2 uses numpy for manipulating images, so the proper and best way to get the size of an image is using numpy.shape. Assuming you are working with BGR images, here is an example:

>>> import numpy as np
>>> import cv2
>>> img = cv2.imread('foo.jpg')
>>> height, width, channels = img.shape
>>> print height, width, channels
  600 800 3

In case you were working with binary images, img will have two dimensions, and therefore you must change the code to: height, width = img.shape

MySql export schema without data

Yes, you can use mysqldump with the --no-data option:

mysqldump -u user -h localhost --no-data -p database > database.sql

Clone contents of a GitHub repository (without the folder itself)

If the folder is not empty, a slightly modified version of @JohnLittle's answer worked for me:

git init
git remote add origin https://github.com/me/name.git
git pull origin master

As @peter-cordes pointed out, the only difference is using https protocol instead of git, for which you need to have SSH keys configured.

"Unable to acquire application service" error while launching Eclipse

This error happen cause you deleted the config.ini file while you deleted the plugins. So, when it can not find configuration in config.ini when eclipse lauching, then it use default configuration which is not fit with your os. The following steps solve you problem:

  1. Delete setting in configuration folder.

  2. create a new config.ini file.

  3. copy following setting and save:

  4. osgi.splashPath = platform:/base/plugins/org.eclipse.platform  
    osgi.bundles=org.eclipse.equinox.common@2:start, org.eclipse.update.configurator@3:start, org.eclipse.core.runtime@start  
    eclipse.product=org.eclipse.sdk.ide  
    [email protected]/workspace  
    eof=eof  
    
  5. restart eclipse.

Calculate logarithm in python

If you use log without base it uses e.

From the comment

Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.

Therefor you have to use:

import math
print( math.log(1.5, 10))

Javascript wait() function

You shouldn't edit it, you should completely scrap it.

Any attempt to make execution stop for a certain amount of time will lock up the browser and switch it to a Not Responding state. The only thing you can do is use setTimeout correctly.

How do I setup the InternetExplorerDriver so it works

Another way to resolve this problem is:

Let's assume:

path_to_driver_directory = C:\Work\drivers\

driver = IEDriverServer.exe

When getting messsage about path you can always add path_to_driver_directory containing driver to the PATH environment variable. Check: http://java.com/en/download/help/path.xml

Then simply check in cmd window if driver is available - just run cmd in any location and type name of driver.

If everything works fine then you get:

C:\Users\A>IEDriverServer.exe
Started InternetExplorerDriver server (32-bit)
2.28.0.0
Listening on port 5555

Thats it.

Open a URL in a new tab (and not a new window)

Opening a new tab from within a Firefox (Mozilla) extension goes like this:

gBrowser.selectedTab = gBrowser.addTab("http://example.com");

Refreshing data in RecyclerView and keeping its scroll position

Yes you can resolve this issue by making the adapter constructor only one time, I am explaining the coding part here :

if (appointmentListAdapter == null) {
        appointmentListAdapter = new AppointmentListAdapter(AppointmentsActivity.this);
        appointmentListAdapter.addAppointmentListData(appointmentList);
        appointmentListAdapter.setOnStatusChangeListener(onStatusChangeListener);
        appointmentRecyclerView.setAdapter(appointmentListAdapter);

    } else {
        appointmentListAdapter.addAppointmentListData(appointmentList);
        appointmentListAdapter.notifyDataSetChanged();
    }

Now you can see I have checked the adapter is null or not and only initialize when it is null.

If adapter is not null then I am assured that I have initialized my adapter at least one time.

So I will just add list to adapter and call notifydatasetchanged.

RecyclerView always holds the last position scrolled, therefore you don't have to store last position, just call notifydatasetchanged, recycler view always refresh data without going to top.

Thanks Happy Coding

How to read file contents into a variable in a batch file?

You can read multiple variables from file like this:

for /f "delims== tokens=1,2" %%G in (param.txt) do set %%G=%%H

where param.txt:

PARAM1=value1
PARAM2=value2
...

javascript: using a condition in switch case

If that's what you want to do, it would be better to use if statements. For example:

if(liCount == 0){
    setLayoutState('start');
}
if(liCount<=5 && liCount>0){
    setLayoutState('upload1Row');
}
if(liCount<=10 && liCount>5){
    setLayoutState('upload2Rows');
}             
var api = $('#UploadList').data('jsp');
    api.reinitialise();

How to split a comma-separated string?

Can try with this worked for me

 sg = sg.replaceAll(", $", "");

or else

if (sg.endsWith(",")) {
                    sg = sg.substring(0, sg.length() - 1);
                }

Getting Access Denied when calling the PutObject operation with bucket-level permission

I was having a similar problem. I was not using the ACL stuff, so I didn't need s3:PutObjectAcl.

In my case, I was doing (in Serverless Framework YML):

- Effect: Allow
  Action:
    - s3:PutObject
  Resource: "arn:aws:s3:::MyBucketName"

Instead of:

- Effect: Allow
  Action:
    - s3:PutObject
  Resource: "arn:aws:s3:::MyBucketName/*"

Which adds a /* to the end of the bucket ARN.

Hope this helps.

jquery, find next element by class

Given a first selector: SelectorA, you can find the next match of SelectorB as below:

Example with mouseover to change border-with:

$("SelectorA").on("mouseover", function() {
    var i = $(this).find("SelectorB")[0];
    $(i).css({"border" : "1px"});
    });
}

General use example to change border-with:

var i = $("SelectorA").find("SelectorB")[0];
$(i).css({"border" : "1px"});

Is it better to return null or empty collection?

Returning null could be more efficient, as no new object is created. However, it would also often require a null check (or exception handling.)

Semantically, null and an empty list do not mean the same thing. The differences are subtle and one choice may be better than the other in specific instances.

Regardless of your choice, document it to avoid confusion.

jQuery: If this HREF contains

$("a").each(function() {
    if (this.href.indexOf('?') != -1) {
        alert("Contains questionmark");
    }
});

What is the origin of foo and bar?

tl;dr

  • "Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.

  • Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).

  • Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.

  • Also, it seems likely the military FUBAR contributed to their popularity.


The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)


OK, so let's find some references.

STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:

On Foo-ism

The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")

As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.

It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!

The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:

By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.

...

It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.

Hopefully yours,

Indignant Mother of Five.

And The Tech in December 1938:

General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."


The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:

FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.

These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:

Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.

And from 1996's Jargon File 4.0.0:

Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."

A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):

Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!

Also 1964's MIT Voo Doo (PDF) references the TMRC usage:

Yes! I want to be an instant success and snow customers. Send me a degree in: ...

  • Foo Counters

  • Foo Jung


Let's find "foo", "bar" and "foobar" published in code examples.

So, Jargon File 4.4.7 says of "foobar":

Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.

The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:

Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.

Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z

I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:

car[((FOO . CROCK) . GLITCH)]

It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER

For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:

EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).


Some more recallations.

@Walter Mitty recalled on this site in 2008:

I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.

John V. Everett recalls in 1996:

When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.

Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.

It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.

Daniel P. B. Smith in 1998:

Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.

Robert Schuldenfrei in 1996:

The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?

Paul M. Wexelblat in 1992:

The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.

Bruce B. Reynolds in 1996:

On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...

Here's a straight IBM "BAR" from 1955.


Other early references:


I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.

Here are a some of even earlier F00s but I think they're coincidences/false positives:

How do I concatenate const/literal strings in C?

You are trying to copy a string into an address that is statically allocated. You need to cat into a buffer.

Specifically:

...snip...

destination

Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.

...snip...

http://www.cplusplus.com/reference/clibrary/cstring/strcat.html

There's an example here as well.

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon() destroys the session and the Session_OnEnd event is triggered.

Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.

So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

Use Session.Clear(), if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.

HTML5 iFrame Seamless Attribute

It is possible to use the semless attribute right now, here i found a german article http://www.solife.cc/blog/html5-iframe-attribut-seamless-beispiele.html

and here are another presentation about this topic: http://benvinegar.github.com/seamless-talk/

You have to use the window.postMessage method to communicate between the parent and the iframe.

How do I output lists as a table in Jupyter notebook?

I finally re-found the jupyter/IPython documentation that I was looking for.

I needed this:

from IPython.display import HTML, display

data = [[1,2,3],
        [4,5,6],
        [7,8,9],
        ]

display(HTML(
   '<table><tr>{}</tr></table>'.format(
       '</tr><tr>'.join(
           '<td>{}</td>'.format('</td><td>'.join(str(_) for _ in row)) for row in data)
       )
))

(I may have slightly mucked up the comprehensions, but display(HTML('some html here')) is what we needed)

How to make a pure css based dropdown menu?

View code online on: WebCrafts.org

HTML code:

<body id="body">
<div id="navigation">
    <h2>
        Pure CSS Drop-down Menu
    </h2>
  <div id="nav" class="nav">
    <ul>
        <li><a href="#">Menu1</a></li>
        <li>
            <a href="#">Menu2</a>
          <ul>
                <li><a href="#">Sub-Menu1</a></li>
                <li>
                    <a href="#">Sub-Menu2</a>
                  <ul>
                        <li><a href="#">Demo1</a></li>
                      <li><a href="#">Demo2</a></li>
                    </ul>
                </li>
                <li><a href="#">Sub-Menu3</a></li>
                <li><a href="#">Sub-Menu4</a></li>
            </ul>
        </li>
        <li><a href="#">Menu3</a></li>
        <li><a href="#">Menu4</a></li>
    </ul>
  </div>
</div>
</body>

Css code:

body{
    background-color:#111;
}

#navigation{
    text-align:center;
}
#navigation h2{
    color:#DDD;
}

.nav{
    display:inline-block;
    z-index:5;
    font-weight:bold;
}
.nav ul{
    width:auto;
    list-style:none;
}

.nav ul li{
    display:inline-block;
}

.nav ul li a{
    text-decoration:none;
    text-align:center;
    color:#222;
    display:block;
    width:120px;
    line-height:30px;
    background-color:gray;
}

.nav ul li a:hover{
    background-color:#EEC;   
}
.nav ul li ul{
    margin-top:0px;
    padding-left:0px;
    position:absolute;
    display:none;
}

.nav ul li:hover ul{
    display:block;
}

.nav ul li ul li{
    display:block;
}

.nav ul li ul li ul{
    margin-left:100%;
    margin-top:-30px;
    visibility:hidden;
}

.nav ul li ul li:hover ul{
    margin-left:100%;
    visibility:visible;
}

Makefile ifeq logical or

ifeq ($(GCC_MINOR), 4)
    CFLAGS += -fno-strict-overflow
endif
ifeq ($(GCC_MINOR), 5)
    CFLAGS += -fno-strict-overflow
endif

Another you can consider using in this case is:

GCC42_OR_LATER = $(shell $(CXX) -v 2>&1 | $(EGREP) -c "^gcc version (4.[2-9]|[5-9])")

# -Wstrict-overflow: http://www.airs.com/blog/archives/120
ifeq ($(GCC42_OR_LATER),1)
  CFLAGS += -Wstrict-overflow
endif

I actually use the same in my code because I don't want to maintain a separate config or Configure.

But you have to use a portable, non-anemic make, like GNU make (gmake), and not Posix's make.

And it does not address the issue of logical AND and OR.

pip installing in global site-packages instead of virtualenv

Lot of good discussion above, but virtualenv examples were used. Since 'conda' is now the recommended tool to manage virtualenv, I have summarized the steps in running pip in conda env as follow.

I'll use py36r as the name of the env, and /opt/conda/envs is the prefix to the envs):

$ source /opt/conda/etc/profile.d/conda.sh # skip if already done 
$ conda activate py36r
$ pip  install pkg_xyz
$ pip  list | grep pkg_xyz

Note that the pip executed should be in /opt/conda/envs/py36r/bin/pip (not /opt/conda/bin/pip).

Alternatively, you can simply run the following without conda activate

$ /opt/conda/envs/py36r/bin/pip

Also, if you install using conda, you can install without activate:

$ conda install -n py36r pkg_abc ...

How to redirect the output of an application in background to /dev/null

You use:

yourcommand  > /dev/null 2>&1

If it should run in the Background add an &

yourcommand > /dev/null 2>&1 &

>/dev/null 2>&1 means redirect stdout to /dev/null AND stderr to the place where stdout points at that time

If you want stderr to occur on console and only stdout going to /dev/null you can use:

yourcommand 2>&1 > /dev/null

In this case stderr is redirected to stdout (e.g. your console) and afterwards the original stdout is redirected to /dev/null

If the program should not terminate you can use:

nohup yourcommand &

Without any parameter all output lands in nohup.out

Git undo local branch delete

If you just deleted the branch, you will see something like this in your terminal:

Deleted branch branch_name(was e562d13)
  • where e562d13 is a unique ID (a.k.a. the "SHA" or "hash"), with this you can restore the deleted branch.

To restore the branch, use:

git checkout -b <branch_name> <sha>

for example:

git checkout -b branch_name e562d13 

How can I see the entire HTTP request that's being sent by my Python application?

The verbose configuration option might allow you to see what you want. There is an example in the documentation.

NOTE: Read the comments below: The verbose config options doesn't seem to be available anymore.

Initializing ArrayList with some predefined values

How about using overloaded ArrayList constructor.

 private ArrayList<String> symbolsPresent = new ArrayList<String>(Arrays.asList(new String[] {"One","Two","Three","Four"}));

Cannot authenticate into mongo, "auth fails"

The proper way to login into mongo shell is

mongo localhost:27017 -u 'uuuuu' -p '>xxxxxx' --authenticationDatabase dbname