Programs & Examples On #Jedit

jEdit is a multi-platform open source text editor written in Java.

PHP absolute path to root

use dirname(__FILE__) in a global configuration file.

List of macOS text editors and code editors

I used to use PageSpiner from optima Software (http://www.optima-system.com/pagespinner/) but converted to Coda when Panic first released it and haven't looked back.

Now that the latest version has multi-file find and replace it has just about everything I need and I use it on a daily basis. Another vote for Coda from me.

What generates the "text file busy" message in Unix?

This occurs when you try and write to a file that is currently being executed by the kernel, or execute a file that is currently open for writing.

Source: http://wiki.wlug.org.nz/ETXTBSY

Javascript call() & apply() vs bind()?

Here is one good article to illustrate the difference among bind(), apply() and call(), summarize it as below.

  • bind() allows us to easily set which specific object will be bound to this when a function or method is invoked.

    // This data variable is a global variable?
    var data = [
        {name:"Samantha", age:12},
        {name:"Alexis", age:14}
    ]
    var user = {
        // local data variable?
        data    :[
            {name:"T. Woods", age:37},
            {name:"P. Mickelson", age:43}
        ],
        showData:function (event) {
            var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1?
            console.log (this.data[randomNum].name + " " + this.data[randomNum].age);
        }
    }
    
    // Assign the showData method of the user object to a variable?
    var showDataVar = user.showData;
    showDataVar (); // Samantha 12 (from the global data array, not from the local data array)?
    /*
    This happens because showDataVar () is executed as a global function and use of this inside 
    showDataVar () is bound to the global scope, which is the window object in browsers.
    */
    
    // Bind the showData method to the user object?
    var showDataVar = user.showData.bind (user);
    // Now the we get the value from the user object because the this keyword is bound to the user object?
    showDataVar (); // P. Mickelson 43?
    
  • bind() allow us to borrow methods

    // Here we have a cars object that does not have a method to print its data to the console?
    var cars = {
        data:[
           {name:"Honda Accord", age:14},
           {name:"Tesla Model S", age:2}
       ]
    }
    
    // We can borrow the showData () method from the user object we defined in the last example.?
    // Here we bind the user.showData method to the cars object we just created.?
    cars.showData = user.showData.bind (cars);
    cars.showData (); // Honda Accord 14?
    

    One problem with this example is that we are adding a new method showData on the cars object and we might not want to do that just to borrow a method because the cars object might already have a property or method name showData. We don’t want to overwrite it accidentally. As we will see in our discussion of Apply and Call below, it is best to borrow a method using either the Apply or Call method.

  • bind() allow us to curry a function

    Function Currying, also known as partial function application, is the use of a function (that accept one or more arguments) that returns a new function with some of the arguments already set.

    function greet (gender, age, name) {
        // if a male, use Mr., else use Ms.?
        var salutation = gender === "male" ? "Mr. " : "Ms. ";
        if (age > 25) {
            return "Hello, " + salutation + name + ".";
        }else {
            return "Hey, " + name + ".";
        }
     }
    

    We can use bind() to curry this greet function

    // So we are passing null because we are not using the "this" keyword in our greet function.
    var greetAnAdultMale = greet.bind (null, "male", 45);
    
    greetAnAdultMale ("John Hartlove"); // "Hello, Mr. John Hartlove."
    
    var greetAYoungster = greet.bind (null, "", 16);
    greetAYoungster ("Alex"); // "Hey, Alex."?
    greetAYoungster ("Emma Waterloo"); // "Hey, Emma Waterloo."
    
  • apply() or call() to set this value

    The apply, call, and bind methods are all used to set the this value when invoking a method, and they do it in slightly different ways to allow use direct control and versatility in our JavaScript code.

    The apply and call methods are almost identical when setting the this value except that you pass the function parameters to apply () as an array, while you have to list the parameters individually to pass them to the call () method.

    Here is one example to use call or apply to set this in the callback function.

    // Define an object with some properties and a method?
    // We will later pass the method as a callback function to another function?
    var clientData = {
        id: 094545,
        fullName: "Not Set",
        // setUserName is a method on the clientData object?
        setUserName: function (firstName, lastName)  {
            // this refers to the fullName property in this object?
            this.fullName = firstName + " " + lastName;
        }
    };
    
    function getUserInput (firstName, lastName, callback, callbackObj) {
         // The use of the Apply method below will set the "this" value to callbackObj?
         callback.apply (callbackObj, [firstName, lastName]);
    }
    
    // The clientData object will be used by the Apply method to set the "this" value?
    getUserInput ("Barack", "Obama", clientData.setUserName, clientData);
    // the fullName property on the clientData was correctly set?
    console.log (clientData.fullName); // Barack Obama
    
  • Borrow functions with apply or call

    • Borrow Array methods

      Let’s create an array-like object and borrow some array methods to operate on the our array-like object.

      // An array-like object: note the non-negative integers used as keys?
      var anArrayLikeObj = {0:"Martin", 1:78, 2:67, 3:["Letta", "Marieta", "Pauline"], length:4 };
      
       // Make a quick copy and save the results in a real array:
       // First parameter sets the "this" value?
       var newArray = Array.prototype.slice.call (anArrayLikeObj, 0);
       console.log (newArray); // ["Martin", 78, 67, Array[3]]?
      
       // Search for "Martin" in the array-like object?
       console.log (Array.prototype.indexOf.call (anArrayLikeObj, "Martin") === -1 ? false : true); // true?
      

      Another common case is that convert arguments to array as following

        // We do not define the function with any parameters, yet we can get all the arguments passed to it?
       function doSomething () {
          var args = Array.prototype.slice.call (arguments);
          console.log (args);
       }
      
       doSomething ("Water", "Salt", "Glue"); // ["Water", "Salt", "Glue"]
      
    • Borrow other methods

      var gameController = {
           scores  :[20, 34, 55, 46, 77],
           avgScore:null,
           players :[
                {name:"Tommy", playerID:987, age:23},
                {name:"Pau", playerID:87, age:33}
           ]
       }
       var appController = {
           scores  :[900, 845, 809, 950],
           avgScore:null,
           avg     :function () {
                   var sumOfScores = this.scores.reduce (function (prev, cur, index, array) {
                        return prev + cur;
               });
               this.avgScore = sumOfScores / this.scores.length;
           }
         }
         // Note that we are using the apply () method, so the 2nd argument has to be an array?
         appController.avg.apply (gameController);
         console.log (gameController.avgScore); // 46.4?
         // appController.avgScore is still null; it was not updated, only gameController.avgScore was updated?
         console.log (appController.avgScore); // null?
      
  • Use apply() to execute variable-arity function

The Math.max is one example of variable-arity function,

// We can pass any number of arguments to the Math.max () method?
console.log (Math.max (23, 11, 34, 56)); // 56

But what if we have an array of numbers to pass to Math.max? We cannot do this:

var allNumbers = [23, 11, 34, 56];
// We cannot pass an array of numbers to the the Math.max method like this?
console.log (Math.max (allNumbers)); // NaN

This is where the apply () method helps us execute variadic functions. Instead of the above, we have to pass the array of numbers using apply () thus:

var allNumbers = [23, 11, 34, 56];
// Using the apply () method, we can pass the array of numbers:
console.log (Math.max.apply (null, allNumbers)); // 56

The remote host closed the connection. The error code is 0x800704CD

One can reproduce the error with the code below:

public ActionResult ClosingTheConnectionAction(){
   try
   {
      //we need to set buffer to false to
      //make sure data is written in chunks
      Response.Buffer = false;  
      var someText = "Some text here to make things happen ;-)";
      var content = GetBytes( someText );

      for(var i=0; i < 100; i++)
      {
         Response.OutputStream.Write(content, 0, content.Length);
      }

      return View();
   }
   catch(HttpException hex)
   {
      if (hex.Message.StartsWith("The remote host closed the connection. The error code is 0x800704CD."))
            {
                //react on remote host closed the connection exception.
                var msg = hex.Message;
            }  
   }
   catch(Exception somethingElseHappened)
   {
      //handle it with some other code
   }

   return View();
} 

Now run the website in debug mode. Put a breakpoint in the loop that writes to the output stream. Go to that action method and after the first iteration passed close the tab of the browser. Hit F10 to continue the loop. After it hit the next iteration you will see the exception. Enjoy your exception :-)

Ruby class instance variable vs. class variable

Instance variable on a class:

class Parent
  @things = []
  def self.things
    @things
  end
  def things
    self.class.things
  end
end

class Child < Parent
  @things = []
end

Parent.things << :car
Child.things  << :doll
mom = Parent.new
dad = Parent.new

p Parent.things #=> [:car]
p Child.things  #=> [:doll]
p mom.things    #=> [:car]
p dad.things    #=> [:car]

Class variable:

class Parent
  @@things = []
  def self.things
    @@things
  end
  def things
    @@things
  end
end

class Child < Parent
end

Parent.things << :car
Child.things  << :doll

p Parent.things #=> [:car,:doll]
p Child.things  #=> [:car,:doll]

mom = Parent.new
dad = Parent.new
son1 = Child.new
son2 = Child.new
daughter = Child.new

[ mom, dad, son1, son2, daughter ].each{ |person| p person.things }
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]

With an instance variable on a class (not on an instance of that class) you can store something common to that class without having sub-classes automatically also get them (and vice-versa). With class variables, you have the convenience of not having to write self.class from an instance object, and (when desirable) you also get automatic sharing throughout the class hierarchy.


Merging these together into a single example that also covers instance variables on instances:

class Parent
  @@family_things = []    # Shared between class and subclasses
  @shared_things  = []    # Specific to this class

  def self.family_things
    @@family_things
  end
  def self.shared_things
    @shared_things
  end

  attr_accessor :my_things
  def initialize
    @my_things = []       # Just for me
  end
  def family_things
    self.class.family_things
  end
  def shared_things
    self.class.shared_things
  end
end

class Child < Parent
  @shared_things = []
end

And then in action:

mama = Parent.new
papa = Parent.new
joey = Child.new
suzy = Child.new

Parent.family_things << :house
papa.family_things   << :vacuum
mama.shared_things   << :car
papa.shared_things   << :blender
papa.my_things       << :quadcopter
joey.my_things       << :bike
suzy.my_things       << :doll
joey.shared_things   << :puzzle
suzy.shared_things   << :blocks

p Parent.family_things #=> [:house, :vacuum]
p Child.family_things  #=> [:house, :vacuum]
p papa.family_things   #=> [:house, :vacuum]
p mama.family_things   #=> [:house, :vacuum]
p joey.family_things   #=> [:house, :vacuum]
p suzy.family_things   #=> [:house, :vacuum]

p Parent.shared_things #=> [:car, :blender]
p papa.shared_things   #=> [:car, :blender]
p mama.shared_things   #=> [:car, :blender]
p Child.shared_things  #=> [:puzzle, :blocks]  
p joey.shared_things   #=> [:puzzle, :blocks]
p suzy.shared_things   #=> [:puzzle, :blocks]

p papa.my_things       #=> [:quadcopter]
p mama.my_things       #=> []
p joey.my_things       #=> [:bike]
p suzy.my_things       #=> [:doll] 

Read only the first line of a file?

Lots of other answers here, but to answer precisely the question you asked (before @MarkAmery went and edited the original question and changed the meaning):

>>> f = open('myfile.txt')
>>> data = f.read()
>>> # I'm assuming you had the above before asking the question
>>> first_line = data.split('\n', 1)[0]

In other words, if you've already read in the file (as you said), and have a big block of data in memory, then to get the first line from it efficiently, do a split() on the newline character, once only, and take the first element from the resulting list.

Note that this does not include the \n character at the end of the line, but I'm assuming you don't want it anyway (and a single-line file may not even have one). Also note that although it's pretty short and quick, it does make a copy of the data, so for a really large blob of memory you may not consider it "efficient". As always, it depends...

How to check if a file exists from inside a batch file

Try something like the following example, quoted from the output of IF /? on Windows XP:

IF EXIST filename. (
    del filename.
) ELSE (
    echo filename. missing.
)

You can also check for a missing file with IF NOT EXIST.

The IF command is quite powerful. The output of IF /? will reward careful reading. For that matter, try the /? option on many of the other built-in commands for lots of hidden gems.  

how to align text vertically center in android

In relative layout you need specify textview height:

android:layout_height="100dp"

Or specify lines attribute:

android:lines="3"

stop all instances of node.js server

Windows & GitBash Terminal I needed to use this command inside Windows / Webstorm / GitBash terminal

cmd "/C TASKKILL /IM node.exe /F"

Command CompileSwift failed with a nonzero exit code in Xcode 10

It seems like this is a pretty vague error, so I will share what I did to fix it when I ran into this:

Using Xcode 10.1 and Swift 4.2 I tried pretty much all the suggestions here but none of them worked for me, then I realized a dependency I was using was not compatible with Swift 4.2 and that was causing me to get this error on other pods. So to fix it I just had to force that pod to use Swift 4.0 by putting this at the end of my Podfile:

post_install do |installer|
    installer.pods_project.targets.each do |target|
        if ['TKRadarChart'].include? target.name
            target.build_configurations.each do |config|
                config.build_settings['SWIFT_VERSION'] = '4.0'
            end
        end
    end
end

How do I find the maximum of 2 numbers?

numberList=[16,19,42,43,74,66]

largest = numberList[0]

for num2 in numberList:

    if num2 > largest:

        largest=num2

print(largest)

gives largest number out of the numberslist without using a Max statement

Sequence contains no elements?

Well, what is ID here? In particular, is it a local variable? There are some scope / capture issues, which mean that it may be desirable to use a second variable copy, just for the query:

var id = ID;
BlogPost post = (from p in dc.BlogPosts
                 where p.BlogPostID == id
                 select p).Single();

Also; if this is LINQ-to-SQL, then in the current version you get a slightly better behaviour if you use the form:

var id = ID;
BlogPost post = dc.BlogPosts.Single(p => p.BlogPostID == id);

Conditional Logic on Pandas DataFrame

In [1]: df
Out[1]:
   data
0     1
1     2
2     3
3     4

You want to apply a function that conditionally returns a value based on the selected dataframe column.

In [2]: df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')
Out[2]:
0     true
1     true
2    false
3    false
Name: data

You can then assign that returned column to a new column in your dataframe:

In [3]: df['desired_output'] = df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')

In [4]: df
Out[4]:
   data desired_output
0     1           true
1     2           true
2     3          false
3     4          false

Floating point exception

It's caused by n % x where x = 0 in the first loop iteration. You can't calculate a modulus with respect to 0.

How to find a min/max with Ruby

If you need to find the max/min of a hash, you can use #max_by or #min_by

people = {'joe' => 21, 'bill' => 35, 'sally' => 24}

people.min_by { |name, age| age } #=> ["joe", 21]
people.max_by { |name, age| age } #=> ["bill", 35]

Restore a deleted file in the Visual Studio Code Recycle Bin

  1. First go to Recycle Bin of your local machine.
  2. Your VS code deleted files is there in Recycle Bin.
  3. So, Right click on deleted files and select-> Restore option then your deleted files will be automatically restored in your VS code.

How to split page into 4 equal parts?

Demo at http://jsfiddle.net/CRSVU/

_x000D_
_x000D_
html,
body {
  height: 100%;
  padding: 0;
  margin: 0;
}

div {
  width: 50%;
  height: 50%;
  float: left;
}

#div1 {
  background: #DDD;
}

#div2 {
  background: #AAA;
}

#div3 {
  background: #777;
}

#div4 {
  background: #444;
}
_x000D_
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
_x000D_
_x000D_
_x000D_

What's the use of ob_start() in php?

You have it backwards. ob_start does not buffer the headers, it buffers the content. Using ob_start allows you to keep the content in a server-side buffer until you are ready to display it.

This is commonly used to so that pages can send headers 'after' they've 'sent' some content already (ie, deciding to redirect half way through rendering a page).

How to change scroll bar position with CSS?

Using CSS only:

Right/Left Flippiing: Working Fiddle

.Container
{
    height: 200px;
    overflow-x: auto;
}
.Content
{
    height: 300px;
}

.Flipped
{
    direction: rtl;
}
.Content
{
    direction: ltr;
}

Top/Bottom Flipping: Working Fiddle

.Container
{
    width: 200px;
    overflow-y: auto;
}
.Content
{
    width: 300px;
}

.Flipped, .Flipped .Content
{
    transform:rotateX(180deg);
    -ms-transform:rotateX(180deg); /* IE 9 */
    -webkit-transform:rotateX(180deg); /* Safari and Chrome */
}

Remove characters before character "."

String input = ....;
int index = input.IndexOf('.');
if(index >= 0)
{
    return input.Substring(index + 1);
}

This will return the new word.

Changing git commit message after push (given that no one pulled from remote)

git commit --amend

then edit and change the message in the current window. After that do

git push --force-with-lease

What is the meaning of curly braces?

Dictionaries in Python are data structures that store key-value pairs. You can use them like associative arrays. Curly braces are used when declaring dictionaries:

d = {'One': 1, 'Two' : 2, 'Three' : 3 }
print d['Two'] # prints "2"

Curly braces are not used to denote control levels in Python. Instead, Python uses indentation for this purpose.

I think you really need some good resources for learning Python in general. See https://stackoverflow.com/q/175001/10077

What is the use of adding a null key or value to a HashMap in Java?

A null key can also be helpful when the map stores data for UI selections where the map key represents a bean field.

A corresponding null field value would for example be represented as "(please select)" in the UI selection.

jQuery .each() with input elements

Assume if all the input elements are inside a form u can refer the below code.

 // get all the inputs into an array.

    var $inputs = $('#myForm :input');

    // not sure if you wanted this, but I thought I'd add it.
    // get an associative array of just the values.
    var values = {};
    $inputs.each(function() {
        values[this.name] = $(this).val();
    });

Difference in months between two dates

Apart from all given answers I find this piece of code very straightforward. AS DateTime.MinValue is 1/1/1, we have to subtract 1 from month, years and days.

var timespan = endDate.Subtract(startDate);
var tempdate = DateTime.MinValue + timespan;

var totalMonths = (tempdate.Year - 1) * 12 + tempdate.Month - 1;

var totalDays = tempdate.Day - 1;
if (totalDays > 0)
{
    totalMonths = totalMonths + 1;
}

How can I limit possible inputs in a HTML5 "number" element?

Simple solution which will work on,

  • Input scroll events

  • Copy paste via keyboard

  • Copy paste via mouse

  • Input type etc cases

    <input id="maxLengthCheck" 
           name="maxLengthCheck" 
           type="number" 
           step="1" 
           min="0" 
           oninput="this.value = this.value > 5 ? 5 : Math.abs(this.value)" />
    

See there is condition on this.value > 5, just update 5 with your max limit.

Explanation:

  • If our input number is more then our limit update input value this.value with proper number Math.abs(this.value)

  • Else just make it to your max limit which is again 5.

Height equal to dynamic width (CSS fluid layout)

width: 80vmin; height: 80vmin;

CSS does 80% of the smallest view, height or width

http://caniuse.com/#feat=viewport-units

Best way to find os name and version in Unix/Linux platform

This work fine for all Linux environment.

#!/bin/sh
cat /etc/*-release

In Ubuntu:

$ cat /etc/*-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=10.04
DISTRIB_CODENAME=lucid
DISTRIB_DESCRIPTION="Ubuntu 10.04.4 LTS"

or 12.04:

$ cat /etc/*-release

DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=12.04
DISTRIB_CODENAME=precise
DISTRIB_DESCRIPTION="Ubuntu 12.04.4 LTS"
NAME="Ubuntu"
VERSION="12.04.4 LTS, Precise Pangolin"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu precise (12.04.4 LTS)"
VERSION_ID="12.04"

In RHEL:

$ cat /etc/*-release
Red Hat Enterprise Linux Server release 6.5 (Santiago)
Red Hat Enterprise Linux Server release 6.5 (Santiago)

Or Use this Script:

#!/bin/sh
# Detects which OS and if it is Linux then it will detect which Linux
# Distribution.

OS=`uname -s`
REV=`uname -r`
MACH=`uname -m`

GetVersionFromFile()
{
    VERSION=`cat $1 | tr "\n" ' ' | sed s/.*VERSION.*=\ // `
}

if [ "${OS}" = "SunOS" ] ; then
    OS=Solaris
    ARCH=`uname -p` 
    OSSTR="${OS} ${REV}(${ARCH} `uname -v`)"
elif [ "${OS}" = "AIX" ] ; then
    OSSTR="${OS} `oslevel` (`oslevel -r`)"
elif [ "${OS}" = "Linux" ] ; then
    KERNEL=`uname -r`
    if [ -f /etc/redhat-release ] ; then
        DIST='RedHat'
        PSUEDONAME=`cat /etc/redhat-release | sed s/.*\(// | sed s/\)//`
        REV=`cat /etc/redhat-release | sed s/.*release\ // | sed s/\ .*//`
    elif [ -f /etc/SuSE-release ] ; then
        DIST=`cat /etc/SuSE-release | tr "\n" ' '| sed s/VERSION.*//`
        REV=`cat /etc/SuSE-release | tr "\n" ' ' | sed s/.*=\ //`
    elif [ -f /etc/mandrake-release ] ; then
        DIST='Mandrake'
        PSUEDONAME=`cat /etc/mandrake-release | sed s/.*\(// | sed s/\)//`
        REV=`cat /etc/mandrake-release | sed s/.*release\ // | sed s/\ .*//`
    elif [ -f /etc/debian_version ] ; then
        DIST="Debian `cat /etc/debian_version`"
        REV=""

    fi
    if [ -f /etc/UnitedLinux-release ] ; then
        DIST="${DIST}[`cat /etc/UnitedLinux-release | tr "\n" ' ' | sed s/VERSION.*//`]"
    fi

    OSSTR="${OS} ${DIST} ${REV}(${PSUEDONAME} ${KERNEL} ${MACH})"

fi

echo ${OSSTR}

How to clear/delete the contents of a Tkinter Text widget?

According to the tkinterbook the code to clear a text element should be:

text.delete(1.0,END)

This worked for me. source

It's different from clearing an entry element, which is done like this:

entry.delete(0,END) #note the 0 instead of 1.0

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

Here are the three web pages on which we found the answer. The most difficult part was setting up static ports for SQLEXPRESS.

Provisioning a SQL Server Virtual Machine on Windows Azure. These initial instructions provided 25% of the answer.

How to Troubleshoot Connecting to the SQL Server Database Engine. Reading this carefully provided another 50% of the answer.

How to configure SQL server to listen on different ports on different IP addresses?. This enabled setting up static ports for named instances (eg SQLEXPRESS.) It took us the final 25% of the way to the answer.

Hour from DateTime? in 24 hours format

You can get the desired result with the code below. Two'H' in HH is for 24-hour format.

return fechaHora.Value.ToString("HH:mm");

how to delete all commit history in github?

Deleting the .git folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:

  1. Checkout

    git checkout --orphan latest_branch

  2. Add all the files

    git add -A

  3. Commit the changes

    git commit -am "commit message"

  4. Delete the branch

    git branch -D main

  5. Rename the current branch to main

    git branch -m main

  6. Finally, force update your repository

    git push -f origin main

PS: this will not keep your old commit history around

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

I got this issue when i wrote :
export default connect (mapDispatchToProps,mapStateToProps)(SearchInsectsComponent); instead of export default connect (mapStateToProps,mapDispatchToProps)(SearchInsectsComponent);

Postgres: How to do Composite keys?

The error you are getting is in line 3. i.e. it is not in

CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)

but earlier:

CREATE TABLE tags
     (
              (question_id, tag_id) NOT NULL,

Correct table definition is like pilcrow showed.

And if you want to add unique on tag1, tag2, tag3 (which sounds very suspicious), then the syntax is:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    UNIQUE (tag1, tag2, tag3)
);

or, if you want to have the constraint named according to your wish:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    CONSTRAINT some_name UNIQUE (tag1, tag2, tag3)
);

How to split the screen with two equal LinearLayouts?

Just putting it out there:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FF0000"
    android:weightSum="4"
    android:padding="5dp"> <!-- to show what the parent is -->
    <LinearLayout
        android:background="#0000FF"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="2" />
    <LinearLayout
        android:background="#00FF00"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="1" />
</LinearLayout>

Should you use .htm or .html file extension? What is the difference, and which file is correct?

In short, they are exactly the same. If you notice the end of the URL, sometimes you'll see .htm and other times you'll see .html. It still refers to the Hyper-Text Markup Language.

RabbitMQ / AMQP: single queue, multiple consumers for same message?

The send pattern is a one-to-one relationship. If you want to "send" to more than one receiver you should be using the pub/sub pattern. See http://www.rabbitmq.com/tutorials/tutorial-three-python.html for more details.

Get skin path in Magento?

To use it in phtml apply :

echo $this->getSkinUrl('your_image_folder_under_skin/image_name.png');

To use skin path in cms page :

<img style="width: 715px; height: 266px;" src="{{skin url=images/banner1.jpg}}" alt="title" />

This part====> {{skin url=images/banner1.jpg}}

I hope this will help you.

What's a Good Javascript Time Picker?

NoGray is nice eye candy but there are a few usability considerations. Firstly, analog clocks are growing increasingly obscure, and younger people sometimes have a difficult time reading them. Secondly, dragging with a mouse to a specific time is a bit tedious, just like the time pickers that use a slider. Thirdly, keyboard interaction for this picker is a bit sporadic.

For a more usable time picker, check out the Any+Time™ Datepicker/Timepicker AJAX Calendar Widget. It's perhaps the fastest-and-easiest-to-use time picker available, because it uses simple buttons to select specific times with speed and ease.

An interesting test of usability is this: pick an odd time (say, 10:32pm), then see how long it takes to accurately select that time using various time pickers. You can probably do it faster with Any+Time™ than you could write out the time by hand--just try to find another picker you can say that about! Not to mention, Any+Time™ supports a countless variety of date/time formats, 12/24-hour clock, full CSS (or jQuery UI) customization and even time zones!

Allowing Java to use an untrusted certificate for SSL/HTTPS connection

Here is some relevant code:

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}

// Now you can access an https URL without having the certificate in the truststore
try {
    URL url = new URL("https://hostname/index.html");
} catch (MalformedURLException e) {
}

This will completely disable SSL checking—just don't learn exception handling from such code!

To do what you want, you would have to implement a check in your TrustManager that prompts the user.

How enable auto-format code for Intellij IDEA?

The way I implemented automatical reformating like in Microsoft Visual Studio (It doesn't work perfect):

1. Edit > Macros > Start Macro Recording
2. Press continuously: Enter + Ctrl+Alt+I
3. Edit > Macros > Stop Macro Recording (Name it for example ReformatingByEnter)

Now we need to perform same actions but for Ctrl+Alt+L+;

4. Edit > Macros > Start Macro Recording
5. Press continuously: ; + Ctrl+Alt+I
6. Edit > Macros > Stop Macro Recording (Name it for example ReformatingBy;)

Now we need to assign HotKeys to these macros:

7. File > Settings > Keymap > press on a gear button > Duplicate...
8. Unfold a macro button (beneath) and by right clicking on two 
ours macros assign HotKeys for them: "Enter" and ";" correspondingly.

How can I export tables to Excel from a webpage

   function normalexport() {

       try {
           var i;
           var j;
           var mycell;
           var tableID = "tblInnerHTML";
           var drop = document.getElementById('<%= ddl_sections.ClientID %>');
           var objXL = new ActiveXObject("Excel.Application");
           var objWB = objXL.Workbooks.Add();
           var objWS = objWB.ActiveSheet;
           var str = filterNum(drop.options[drop.selectedIndex].text);
           objWB.worksheets("Sheet1").activate; //activate dirst worksheet
           var XlSheet = objWB.activeSheet; //activate sheet
           XlSheet.Name = str; //rename


           for (i = 0; i < document.getElementById("ctl00_ContentPlaceHolder1_1").rows.length - 1; i++) {
               for (j = 0; j < document.getElementById("ctl00_ContentPlaceHolder1_1").rows(i).cells.length; j++) {
                   mycell = document.getElementById("ctl00_ContentPlaceHolder1_1").rows(i).cells(j);

                   objWS.Cells(i + 1, j + 1).Value = mycell.innerText;

                   //                                                objWS.Cells(i + 1, j + 1).style.backgroundColor = mycell.style.backgroundColor;
               }
           }

           objWS.Range("A1", "L1").Font.Bold = true;
           //                objWS.Range("A1", "L1").Font.ColorIndex = 2;
           //                 objWS.Range("A1", "Z1").Interior.ColorIndex = 47;

           objWS.Range("A1", "Z1").EntireColumn.AutoFit();

           //objWS.Range("C1", "C1").ColumnWidth = 50;

           objXL.Visible = true;

       } catch (err) {
           alert("Error. Scripting for ActiveX might be disabled")
           return
       }
       idTmr = window.setInterval("Cleanup();", 1);

   }


   function filterNum(str) {

       return str.replace(/[ / ]/g, '');
   }

Save attachments to a folder and rename them

Added simple code to save with readable date-time stamp.

Use sync2pst to sync all your data in outlook with all your devices, work like this:

  1. you only need to buy 1 license: save your pst file on one computer (let's call this pc 'server') on your network.
  2. create scheduled tasks that will synchronize the pst file on your 'server' with all the pst files on all your devices, no matter which device downloaded the emails first (you need some dos programming knowledge to bypass pst files that are open at sync time).
  3. save all your attachments on the same skydrive folder that is located on the same place on all your devices (e.g. e:\skydrive\attachments)
  4. Use the code below on all your devices to save attachments (change the path as mentioned above)
  5. Use ONLY ONE PST-file for all your accounts, make folders, subfolders and so ...

  6. in VBA: refer to 'microsoft scripting runtime'extra/references...'

  7. here's the code

Private Sub Application_NewMail()
SaveAttachments
End Sub

Public Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem 'Object
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String
Dim fs As FileSystemObject

' Get the path to your My Documents folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next

' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")

' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection

' Set the Attachment folder.
strFolderpath = "F:\SkyDrive\Attachments\"

' Check each selected item for attachments. If attachments exist,
' save them to the strFolderPath folder and strip them from the item.
For Each objMsg In objSelection

    ' This code only strips attachments from mail items.
    ' If objMsg.class=olMail Then
    ' Get the Attachments collection of the item.
    Set objAttachments = objMsg.Attachments
    lngCount = objAttachments.Count
    strDeletedFiles = ""

    If lngCount > 0 Then

        ' We need to use a count down loop for removing items
        ' from a collection. Otherwise, the loop counter gets
        ' confused and only every other item is removed.
        Set fs = New FileSystemObject

        For i = lngCount To 1 Step -1

            ' Save attachment before deleting from item.
            ' Get the file name.
            strFile = Left(objAttachments.Item(i).FileName, Len(objAttachments.Item(i).FileName) - 4) + "_" + Right("00" + Trim(Str$(Day(Now))), 2) + "_" + Right("00" + Trim(Str$(Month(Now))), 2) + "_" + Right("0000" + Trim(Str$(Year(Now))), 4) + "_" + Right("00" + Trim(Str$(Hour(Now))), 2) + "_" + Right("00" + Trim(Str$(Minute(Now))), 2) + "_" + Right("00" + Trim(Str$(Second(Now))), 2) + Right((objAttachments.Item(i).FileName), 4)

            ' Combine with the path to the Temp folder.
            strFile = strFolderpath & strFile

            ' Save the attachment as a file.
            objAttachments.Item(i).SaveAsFile strFile

            ' Delete the attachment.
            objAttachments.Item(i).Delete

            'write the save as path to a string to add to the message
            'check for html and use html tags in link
            If objMsg.BodyFormat <> olFormatHTML Then
                strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
            Else
                strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _
                strFile & "'>" & strFile & "</a>"
            End If

            'Use the MsgBox command to troubleshoot. Remove it from the final code.
            'MsgBox strDeletedFiles

        Next i

        ' Adds the filename string to the message body and save it
        ' Check for HTML body
        If objMsg.BodyFormat <> olFormatHTML Then
            objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
        Else
            objMsg.HTMLBody = "<p>" & "The file(s) were saved to " & strDeletedFiles & "</p>" & objMsg.HTMLBody
        End If

        objMsg.Save
    End If
Next

ExitSub:

Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub

node.js http 'get' request with query string parameters

Check out the request module.

It's more full featured than node's built-in http client.

var request = require('request');

var propertiesObject = { field1:'test1', field2:'test2' };

request({url:url, qs:propertiesObject}, function(err, response, body) {
  if(err) { console.log(err); return; }
  console.log("Get response: " + response.statusCode);
});

PHP session handling errors

You can fix the issue with the following steps:

  1. Verify the folder exists with sudo cd /var/lib/php/session. If it does not exist then sudo mkdir /var/lib/php/session or double check the logs to make sure you have the correct path.
  2. Give the folder full read and write permissions with sudo chmod 666 /var/lib/php/session.

Rerun you script and it should be working fine, however, it's not recommended to leave the folder with full permissions. For security, files and folders should only have the minimum permissions required. The following steps will fix that:

  1. You should already be in the session folder so just run sudo ls -l to find out the owner of the session file.
  2. Set the correct owner of the session folder with sudo chown user /var/lib/php/session.
  3. Give just the owner full read and write permissions with sudo chmod 600 /var/lib/php/session.

NB

You might not need to use the sudo command.

Is it possible to Turn page programmatically in UIPageViewController?

However using this 'self.pageViewController setViewControllers' method call does not call 'viewDidDissapear' on the viewController for the page that has been turned away, whereas manually turning a page does call viewDidDissapear on the turned away page. I believe this is the cause of my crash

"The number of view controllers provided (0) doesn't match the number required (1) for the requested transition"

How to get current relative directory of your Makefile?

THIS_DIR := $(dir $(abspath $(firstword $(MAKEFILE_LIST))))

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

You must have to define no-args or default constructor if you are creating your own constructor.

You can read why default or no argument constructor is required.

why-default-or-no-argument-constructor-java-class.html

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

How to limit depth for recursive file list?

All I'm really interested in is the ownership and permissions information for the first level subdirectories.

I found a easy solution while playing my fish, which fits your need perfectly.

ll `ls`

or

ls -l $(ls)

ASP.NET Button to redirect to another page

u can use this:

protected void btnConfirm_Click(object sender, EventArgs e)
{
  Response.Redirect("Confirm.aspx");
}

Pass all variables from one shell script to another?

You have basically two options:

  1. Make the variable an environment variable (export TESTVARIABLE) before executing the 2nd script.
  2. Source the 2nd script, i.e. . test2.sh and it will run in the same shell. This would let you share more complex variables like arrays easily, but also means that the other script could modify variables in the source shell.

UPDATE:

To use export to set an environment variable, you can either use an existing variable:

A=10
# ...
export A

This ought to work in both bash and sh. bash also allows it to be combined like so:

export A=10

This also works in my sh (which happens to be bash, you can use echo $SHELL to check). But I don't believe that that's guaranteed to work in all sh, so best to play it safe and separate them.

Any variable you export in this way will be visible in scripts you execute, for example:

a.sh:

#!/bin/sh

MESSAGE="hello"
export MESSAGE
./b.sh

b.sh:

#!/bin/sh

echo "The message is: $MESSAGE"

Then:

$ ./a.sh
The message is: hello

The fact that these are both shell scripts is also just incidental. Environment variables can be passed to any process you execute, for example if we used python instead it might look like:

a.sh:

#!/bin/sh

MESSAGE="hello"
export MESSAGE
./b.py

b.py:

#!/usr/bin/python

import os

print 'The message is:', os.environ['MESSAGE']

Sourcing:

Instead we could source like this:

a.sh:

#!/bin/sh

MESSAGE="hello"

. ./b.sh

b.sh:

#!/bin/sh

echo "The message is: $MESSAGE"

Then:

$ ./a.sh
The message is: hello

This more or less "imports" the contents of b.sh directly and executes it in the same shell. Notice that we didn't have to export the variable to access it. This implicitly shares all the variables you have, as well as allows the other script to add/delete/modify variables in the shell. Of course, in this model both your scripts should be the same language (sh or bash). To give an example how we could pass messages back and forth:

a.sh:

#!/bin/sh

MESSAGE="hello"

. ./b.sh

echo "[A] The message is: $MESSAGE"

b.sh:

#!/bin/sh

echo "[B] The message is: $MESSAGE"

MESSAGE="goodbye"

Then:

$ ./a.sh
[B] The message is: hello
[A] The message is: goodbye

This works equally well in bash. It also makes it easy to share more complex data which you could not express as an environment variable (at least without some heavy lifting on your part), like arrays or associative arrays.

Connect to Oracle DB using sqlplus

it would be something like this

sqlplus -s /nolog  <<-!
connect ${ORACLE_UID}/${ORACLE_PWD}@${ORACLE_DB};
whenever sqlerror exit sql.sqlcode;
set pagesize 0;
set linesize 150;
spool <query_output.dat> APPEND
@$<input_query.dat>
spool off;
exit;
!

here

ORACLE_UID=<user name>
ORACLE_PWD=<password>
ORACLE_DB=//<host>:<port>/<DB name>

mysqldump with create database line

By default mysqldump always creates the CREATE DATABASE IF NOT EXISTS db_name; statement at the beginning of the dump file.

[EDIT] Few things about the mysqldump file and it's options:

--all-databases, -A

Dump all tables in all databases. This is the same as using the --databases option and naming all the databases on the command line.

--add-drop-database

Add a DROP DATABASE statement before each CREATE DATABASE statement. This option is typically used in conjunction with the --all-databases or --databases option because no CREATE DATABASE statements are written unless one of those options is specified.

--databases, -B

Dump several databases. Normally, mysqldump treats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names. CREATE DATABASE and USE statements are included in the output before each new database.

--no-create-db, -n

This option suppresses the CREATE DATABASE statements that are otherwise included in the output if the --databases or --all-databases option is given.

Some time ago, there was similar question actually asking about not having such statement on the beginning of the file (for XML file). Link to that question is here.

So to answer your question:

  • if you have one database to dump, you should have the --add-drop-database option in your mysqldump statement.
  • if you have multiple databases to dump, you should use the option --databases or --all-databases and the CREATE DATABASE syntax will be added automatically

More information at MySQL Reference Manual

Redis command to get all available keys?

-->Get all keys from redis-cli

-redis 127.0.0.1:6379> keys *

-->Get list of patterns

-redis 127.0.0.1:6379> keys d??

This will produce keys which start by 'd' with three characters.

-redis 127.0.0.1:6379> keys *t*

This wil get keys with matches 't' character in key

-->Count keys from command line by

-redis-cli keys * |wc -l

-->Or you can use dbsize

-redis-cli dbsize

Pass table as parameter into sql server UDF

Step 1: Create a Type as Table with name TableType that will accept a table having one varchar column

create type TableType
as table ([value] varchar(100) null)

Step 2: Create a function that will accept above declared TableType as Table-Valued Parameter and String Value as Separator

create function dbo.fn_get_string_with_delimeter (@table TableType readonly,@Separator varchar(5))
returns varchar(500)
As
begin

    declare @return varchar(500)

    set @return = stuff((select @Separator + value from @table for xml path('')),1,1,'')

    return @return

end

Step 3: Pass table with one varchar column to the user-defined type TableType and ',' as separator in the function

select dbo.fn_get_string_with_delimeter(@tab, ',')

Is there any way to show a countdown on the lockscreen of iphone?

Or you could figure out the exacting amount of hours and minutes and have that displayed by puttin it into the timer app that already exist in every iphone :)

How to read/write arbitrary bits in C/C++

int x = 0xFF;   //your number - 11111111

How do I for example read a 3 bit integer value starting at the second bit

int y = x & ( 0x7 << 2 ) // 0x7 is 111
                         // and you shift it 2 to the left

Running unittest with typical test directory structure

This way will let you run the test scripts from wherever you want without messing around with system variables from the command line.

This adds the main project folder to the python path, with the location found relative to the script itself, not relative to the current working directory.

import sys, os

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

Add that to the top of all your test scripts. That will add the main project folder to the system path, so any module imports that work from there will now work. And it doesn't matter where you run the tests from.

You can obviously change the project_path_hack file to match your main project folder location.

Force re-download of release dependency using Maven

Deleting the ~/.m2/repository will solve your problem. But, if you still need to keep the old ~/.m2/repository you can just change the maven local path temporarily.

If you are working on IntelliJ just go to Maven Settings and change the Local Repository path to somewhere else. You may need to tick the override checkbox near there.

enter image description here

How to make IPython notebook matplotlib plot inline

I have to agree with foobarbecue (I don't have enough recs to be able to simply insert a comment under his post):

It's now recommended that python notebook isn't started wit the argument --pylab, and according to Fernando Perez (creator of ipythonnb) %matplotlib inline should be the initial notebook command.

See here: http://nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Part%203%20-%20Plotting%20with%20Matplotlib.ipynb

How can I drop all the tables in a PostgreSQL database?

If all of your tables are in a single schema, this approach could work (below code assumes that the name of your schema is public)

DROP SCHEMA public CASCADE;
CREATE SCHEMA public;

If you are using PostgreSQL 9.3 or greater, you may also need to restore the default grants.

GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO public;

String comparison in Python: is vs. ==

I would like to show a little example on how is and == are involved in immutable types. Try that:

a = 19998989890
b = 19998989889 +1
>>> a is b
False
>>> a == b
True

is compares two objects in memory, == compares their values. For example, you can see that small integers are cached by Python:

c = 1
b = 1
>>> b is c
True

You should use == when comparing values and is when comparing identities. (Also, from an English point of view, "equals" is different from "is".)

UTF-8 encoding problem in Spring MVC

In Spring 5, or maybe in earlier versions, there is MediaType class. It has already correct line, if you want to follow DRY:

public static final String APPLICATION_JSON_UTF8_VALUE = "application/json;charset=UTF-8";

So I use this set of controller-related annotations:

@RestController
@RequestMapping(value = "my/api/url", produces = APPLICATION_JSON_UTF8_VALUE)
public class MyController {
    // ... Methods here
}

It is marked deprecated in the docs, but I've run into this issue and it is better than copy-pastying the aforementioned line on every method/controller throughout your application, I think.

How to prevent http file caching in Apache httpd (MAMP)

I had the same issue, but I found a good solution here: Stop caching for PHP 5.5.3 in MAMP

Basically find the php.ini file and comment out the OPCache lines. I hope this alternative answer helps others else out as well.

Grouping into interval of 5 minutes within a time range

You should rather use GROUP BY UNIX_TIMESTAMP(time_stamp) DIV 300 instead of round(../300) because of the rounding I found that some records are counted into two grouped result sets.

How to pass parameters using ui-sref in ui-router to controller

You simply misspelled $stateParam, it should be $stateParams (with an s). That's why you get undefined ;)

How do you run JavaScript script through the Terminal?

This is a "roundabout" solution but you could use ipython

Start ipython notebook from terminal:

$ ipython notebook

It will open in a browser where you can run the javascript

enter image description here

System.BadImageFormatException: Could not load file or assembly

Try to configure the setting of your projects, it is usually due to x86/x64 architecture problems:

Go and set your choice as shown:

Proper way to assert type of variable in Python

The isinstance built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:

def my_print(text, begin, end):
    "Print 'text' in UPPER between 'begin' and 'end' in lower"
    try:
      print begin.lower() + text.upper() + end.lower()
    except (AttributeError, TypeError):
      raise AssertionError('Input variables should be strings')

This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)

IE8 issue with Twitter Bootstrap 3

Don't forget to place your css links in the <head> as respond.js takes only those.

Types in Objective-C on iOS

Note that you can also use the C99 fixed-width types perfectly well in Objective-C:

#import <stdint.h>
...
int32_t x; // guaranteed to be 32 bits on any platform

The wikipedia page has a decent description of what's available in this header if you don't have a copy of the C standard (you should, though, since Objective-C is just a tiny extension of C). You may also find the headers limits.h and inttypes.h to be useful.

Bash array with spaces in elements

There must be something wrong with the way you access the array's items. Here's how it's done:

for elem in "${files[@]}"
...

From the bash manpage:

Any element of an array may be referenced using ${name[subscript]}. ... If subscript is @ or *, the word expands to all members of name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS special variable, and ${name[@]} expands each element of name to a separate word.

Of course, you should also use double quotes when accessing a single member

cp "${files[0]}" /tmp

How do I get the logfile from an Android device?

For those not interested in USB debugging or using adb there is an easier solution. In Android 6 (Not sure about prior version) there is an option under developer tools: Take Bug Report

Clicking this option will prepare a bug report and prompt you to save it to drive or have it sent in email.

I found this to be the easiest way to get logs. I don't like to turn on USB debugging.

How to compare two NSDates: Which is more recent?

Late to the party, but another easy way of comparing NSDate objects is to convert them into primitive types which allows for easy use of '>' '<' '==' etc

eg.

if ([dateA timeIntervalSinceReferenceDate] > [dateB timeIntervalSinceReferenceDate]) {
    //do stuff
}

timeIntervalSinceReferenceDate converts the date into seconds since the reference date (1 January 2001, GMT). As timeIntervalSinceReferenceDate returns a NSTimeInterval (which is a double typedef), we can use primitive comparators.

How to run regasm.exe from command line other than Visual Studio command prompt?

If you created the DLL using .net 4.5 , then copy and paste this command on command prompt.

 %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\regasm.exe MyAssembly.dll

bash "if [ false ];" returns true instead of false -- why?

You are running the [ (aka test) command with the argument "false", not running the command false. Since "false" is a non-empty string, the test command always succeeds. To actually run the command, drop the [ command.

if false; then
   echo "True"
else
   echo "False"
fi

How do you remove a Cookie in a Java Servlet

The MaxAge of -1 signals that you want the cookie to persist for the duration of the session. You want to set MaxAge to 0 instead.

From the API documentation:

A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

What are FTL files

An ftl file could just have a series of html tags just as a JSP page or it can have freemarker template coding for representing the objects passed on from a controller java file.
But, its actual ability is to combine the contents of a java class and view/client side stuff(html/ JQuery/ javascript etc). It is quite similar to velocity. You could map a method or object of a class to a freemarker (.ftl) page and use it as if it is a variable or a functionality created in the very page.

How do I escape a string inside JavaScript code inside an onClick handler?

Another interesting solution might be to do this:

<a href="#" itemid="<%itemid%>" itemname="<%itemname%>" onclick="SelectSurveyItem(this.itemid, this.itemname); return false;">Select</a>

Then you can use a standard HTML-encoding on both the variables, without having to worry about the extra complication of the javascript quoting.

Yes, this does create HTML that is strictly invalid. However, it is a valid technique, and all modern browsers support it.

If it was my, I'd probably go with my first suggestion, and ensure the values are HTML-encoded and have single-quotes escaped.

Compile Views in ASP.NET MVC

You can use aspnet_compiler for this:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler -v /Virtual/Application/Path/Or/Path/In/IIS/Metabase -p C:\Path\To\Your\WebProject -f -errorstack C:\Where\To\Put\Compiled\Site

where "/Virtual/Application/Path/Or/Path/In/IIS/Metabase" is something like this: "/MyApp" or "/lm/w3svc2/1/root/"

Also there is a AspNetCompiler Task on MSDN, showing how to integrate aspnet_compiler with MSBuild:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <Target Name="PrecompileWeb">
        <AspNetCompiler
            VirtualPath="/MyWebSite"
            PhysicalPath="c:\inetpub\wwwroot\MyWebSite\"
            TargetPath="c:\precompiledweb\MyWebSite\"
            Force="true"
            Debug="true"
        />
    </Target>
</Project>

How can I delete a user in linux when the system says its currently used in a process

It worked i used userdell --force USERNAME Some times eventhough -f and --force is same -f is not working sometimes After i removed the account i exit back to that removed username which i removed from root then what happened is this

image description here

TypeError: unsupported operand type(s) for /: 'str' and 'str'

The first thing you should do is learn to read error messages. What does it tell you -- that you can't use two strings with the divide operator.

So, ask yourself why they are strings and how do you make them not-strings. They are strings because all input is done via strings. And the way to make then not-strings is to convert them.

One way to convert a string to an integer is to use the int function. For example:

percent = (int(pyc) / int(tpy)) * 100

How to create and handle composite primary key in JPA

The MyKey class must implement Serializable if you are using @IdClass

The correct way to read a data file into an array

There is the easiest method, using File::Slurp module:

use File::Slurp;
my @lines = read_file("filename", chomp => 1); # will chomp() each line

If you need some validation for each line you can use grep in front of read_file.

For example, filter lines which contain only integers:

my @lines = grep { /^\d+$/ } read_file("filename", chomp => 1);

GIT: Checkout to a specific folder

Use git archive branch-index | tar -x -C your-folder-on-PC to clone a branch to another folder. I think, then you can copy any file that you need

Simple PowerShell LastWriteTime compare

Try the following.

$d = [datetime](Get-ItemProperty -Path $source -Name LastWriteTime).lastwritetime

This is part of the item property weirdness. When you run Get-ItemProperty it does not return the value but instead the property. You have to use one more level of indirection to get to the value.

Checking Date format from a string in C#

you can use DateTime.ParseExact with the format string

DateTime dt = DateTime.ParseExact(inputString, formatString, System.Globalization.CultureInfo.InvariantCulture);

Above will throw an exception if the given string not in given format.

use DateTime.TryParseExact if you don't need exception in case of format incorrect but you can check the return value of that method to identify whether parsing value success or not.

check Custom Date and Time Format Strings

Printing all variables value from a class

Another simple approach is to let Lombok generate the toString method for you.

For this:

  1. Simply add Lombok to your project
  2. Add the annotation @ToString to the definition of your class
  3. Compile your class/project, and it is done

So for example in your case, your class would look like this:

@ToString
public class Contact {
    private String name;
    private String location;
    private String address;
    private String email;
    private String phone;
    private String fax;

    // Getters and setters.
}

Example of output in this case:

Contact(name=John, location=USA, address=SF, [email protected], phone=99999, fax=88888)

More details about how to use the annotation @ToString.

NB: You can also let Lombok generate the getters and setters for you, here is the full feature list.

Splitting strings in PHP and get last part

You can do it like this:

$str = "abc-123-xyz-789";
$last = array_pop( explode('-', $str) );
echo $last; //echoes 789

No log4j2 configuration file found. Using default configuration: logging only errors to the console

Tested with: log4j-ap 2.13.2, log4j-core 2.13.2.

  1. Keep XML file directly under below folder structure. src/main/java
  2. In the POM:
    <build>   
 <resources>       
             <resource>
                <filtering>false</filtering>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>             
            </resource>
 </resources>  
</build>
  1. Clean and build.

Calling ASP.NET MVC Action Methods from JavaScript

You can simply add this when you are using same controller to redirect

var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;

Eclipse error, "The selection cannot be launched, and there are no recent launches"

Follow these steps to run your application on the device connected. 1. Change directories to the root of your Android project and execute: ant debug 2. Make sure the Android SDK platform-tools/ directory is included in your PATH environment variable, then execute: adb install bin/<*your app name*>-debug.apk On your device, locate <*your app name*> and open it.

Refer Running App

How to set the environmental variable LD_LIBRARY_PATH in linux

Add

LD_LIBRARY_PATH="/path/you/want1:/path/you/want/2"

to /etc/environment

See the Ubuntu Documentation.

CORRECTION: I should take my own advice and actually read the documentation. It says that this does not apply to LD_LIBRARY_PATH: Since Ubuntu 9.04 Jaunty Jackalope, LD_LIBRARY_PATH cannot be set in $HOME/.profile, /etc/profile, nor /etc/environment files. You must use /etc/ld.so.conf.d/.conf configuration files.* So user1824407's answer is spot on.

Capturing image from webcam in java?

FMJ can do this, as can the supporting library it uses, LTI-CIVIL. Both are on sourceforge.

jquery to loop through table rows and cells, where checkob is checked, concatenate

UPDATED

I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/

Also, I've changed two ^= to *=. See http://api.jquery.com/category/selectors/

And note the :checked selector. See http://api.jquery.com/checked-selector/

function createcodes() {

    //run through each row
    $('.authors-list tr').each(function (i, row) {

        // reference all the stuff you need first
        var $row = $(row),
            $family = $row.find('input[name*="family"]'),
            $grade = $row.find('input[name*="grade"]'),
            $checkedBoxes = $row.find('input:checked');

        $checkedBoxes.each(function (i, checkbox) {
            // assuming you layout the elements this way, 
            // we'll take advantage of .next()
            var $checkbox = $(checkbox),
                $line = $checkbox.next(),
                $size = $line.next();

            $line.val(
                $family.val() + ' ' + $size.val() + ', ' + $grade.val()
            );

        });

    });
}

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

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

UPD 19.03.2019 Here is a version for browser on GitHub.

Setting focus to iframe contents

document.getElementsByName("iframe_name")[0].contentWindow.document.body.focus();

Get most recent file in a directory on Linux

This is a recursive version (i.e. it finds the most recently updated file in a certain directory or any of its subdirectory)

find $DIR -type f -printf "%T@ %p\n" | sort -n | cut -d' ' -f 2- | tail -n 1

Edit: use -f 2- instead of -f 2 as suggested by Kevin

Select option padding not working in chrome

This simple hack will indent the text. Works well.

select {
  text-indent: 5px;
}

Any way to declare an array in-line?

Another way to do that, if you want the result as a List inline, you can do it like this:

Arrays.asList(new String[] { "String1", "string2" });

Pure css close button

The disappointing thing here is that the "X" isn't transparent (which is how I would likely create a PNG, at least).

I put together this quick test. http://jsfiddle.net/UM3a2/22/embedded/result/ which allows you to color the positive space while leaving the negative space transparent. Since it is made entirely of borders it is easy to color since border-color defaults to the text color.

It doesn't fully support I.E. 8 and earlier (border-radius issues), but it degrades to a square fairly nicely (if you're okay with a square close button).

It also requires two HTML elements since you are only allowed two pseudo elements per selector. I don't know exactly where I learned this, but I think it was in an article by Chris Coyier.

<div id="close" class="arrow-t-b">
  Close
  <div class="arrow-l-r"> </div>
</div>

#close {
  border-width: 4px;
  border-style: solid;
  border-radius: 100%;
  color: #333;
  height: 12px;
  margin:auto;
  position: relative;
  text-indent: -9999px;
  width: 12px;
}
#close:hover {
  color: #39F;
}
.arrow-t-b:after,
.arrow-t-b:before,
.arrow-l-r:after, 
.arrow-l-r:before {
  border-color: transparent;
  border-style: solid;
  border-width: 4px;
  content: "";
  left: 2px;
  top: 0px;
  position: absolute;
}
.arrow-t-b:after {
  border-top-color: inherit;
}
.arrow-l-r:after {
  border-right-color: inherit;
  left: 4px;
  top: 2px;
}
.arrow-t-b:before {
  border-bottom-color: inherit;
  bottom: 0;
}
.arrow-l-r:before {
  border-left-color: inherit;
  left: 0;
  top: 2px;
}

Getting request payload from POST request in Java servlet

You can use Buffer Reader from request to read

    // Read from request
    StringBuilder buffer = new StringBuilder();
    BufferedReader reader = request.getReader();
    String line;
    while ((line = reader.readLine()) != null) {
        buffer.append(line);
        buffer.append(System.lineSeparator());
    }
    String data = buffer.toString()

How do I get time of a Python program's execution?

I used a very simple function to time a part of code execution:

import time
def timing():
    start_time = time.time()
    return lambda x: print("[{:.2f}s] {}".format(time.time() - start_time, x))

And to use it, just call it before the code to measure to retrieve function timing, and then call the function after the code with comments. The time will appear in front of the comments. For example:

t = timing()
train = pd.read_csv('train.csv',
                        dtype={
                            'id': str,
                            'vendor_id': str,
                            'pickup_datetime': str,
                            'dropoff_datetime': str,
                            'passenger_count': int,
                            'pickup_longitude': np.float64,
                            'pickup_latitude': np.float64,
                            'dropoff_longitude': np.float64,
                            'dropoff_latitude': np.float64,
                            'store_and_fwd_flag': str,
                            'trip_duration': int,
                        },
                        parse_dates = ['pickup_datetime', 'dropoff_datetime'],
                   )
t("Loaded {} rows data from 'train'".format(len(train)))

Then the output will look like this:

[9.35s] Loaded 1458644 rows data from 'train'

How to define multiple CSS attributes in jQuery?

You can also use attr along with style:

$('#message').attr("style", "width:550; height:300; font-size:8px" );

What's the difference between "git reset" and "git checkout"?

One simple use case when reverting change:
1. Use reset if you want to undo staging of a modified file.
2. Use checkout if you want to discard changes to unstaged file/s.

Detect when an HTML5 video finishes

You can simply add onended="myFunction()" to your video tag.

<video onended="myFunction()">
  ...
  Your browser does not support the video tag.
</video>

<script type='text/javascript'>
  function myFunction(){
    console.log("The End.")
  }
</script>

Is there a way to list all resources in AWS

I know it is old question but I would like to help too.

Actually, we have AWS Config, which help us to search for all resources in our cloud. You can perform SQL queries too.

I really encourage you all to know this awesome service.

SSRS - Checking whether the data is null

Or in your SQL query wrap that field with IsNull or Coalesce (SQL Server).

Either way works, I like to put that logic in the query so the report has to do less.

Is it possible to clone html element objects in JavaScript / JQuery?

Try this:

$('#foo1').html($('#foo2').children().clone());

Field 'id' doesn't have a default value?

Solution: Remove STRICT_TRANS_TABLES from sql_mode

To check your default setting,

mysql> set @@sql_mode = 
'STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
Query OK, 0 rows affected (0.00 sec)

mysql> select @@sql_mode;
+----------------------------------------------------------------+
| @@sql_mode                                                     |
+----------------------------------------------------------------+
| STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION |
+----------------------------------------------------------------+
1 row in set (0.00 sec)

Run a sample query

mysql> INSERT INTO nb (id) VALUES(3);
ERROR 1364 (HY000): Field 'field' doesn't have a default value

Remove your STRICT_TRANS_TABLES by resetting it to null.

mysql> set @@sql_mode = '';
Query OK, 0 rows affected (0.00 sec)

Now, run the same test query.

mysql> INSERT INTO nb (id) VALUES(3);
Query OK, 1 row affected, 1 warning (0.00 sec)

Source: https://netbeans.org/bugzilla/show_bug.cgi?id=190731

How to send data with angularjs $http.delete() request?

Please Try to pass parameters in httpoptions, you can follow function below

deleteAction(url, data) {
    const authToken = sessionStorage.getItem('authtoken');
    const options = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + authToken,
      }),
      body: data,
    };
    return this.client.delete(url, options);
  }

How to restart counting from 1 after erasing table in MS Access?

I always use below approach. I've created one table in database as Table1 with only one column i.e. Row_Id Number (Long Integer) and its value is 0

enter image description here

INSERT INTO <TABLE_NAME_TO_RESET>
SELECT Row_Id AS <COLUMN_NAME_TO_RESET>
FROM Table1;

This will insert one row with 0 value in AutoNumber column, later delete that row.

How to add form validation pattern in Angular 2?

You could build your form using FormBuilder as it let you more flexible way to configure form.

export class MyComp {
  form: ControlGroup;

  constructor(@Inject()fb: FormBuilder) {  
    this.form = fb.group({  
      foo: ['', MyValidators.regex(/^(?!\s|.*\s$).*$/)]  
    });  
  }

Then in your template :

<input type="text" ngControl="foo" />
<div *ngIf="!form.foo.valid">Please correct foo entry !</div> 

You can also customize ng-invalid CSS class.

As there is actually no validators for regex, you have to write your own. It is a simple function that takes a control in input, and return null if valid or a StringMap if invalid.

export class MyValidators {
  static regex(pattern: string): Function {
    return (control: Control): {[key: string]: any} => {
      return control.value.match(pattern) ? null : {pattern: true};
    };
  }
}

Hope that it help you.

Could not obtain information about Windows NT group user

In our case, the Windows service account that SQL Server and SQL Agent were running under were locked out in Active Directory.

Using iFrames In ASP.NET

try this

<iframe name="myIframe" id="myIframe" width="400px" height="400px" runat="server"></iframe>

Expose this iframe in the master page's codebehind:

public HtmlControl iframe
{
get
{
return this.myIframe;
}
}

Add the MasterType directive for the content page to strongly typed Master Page.

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits=_Default" Title="Untitled Page" %>
<%@ MasterType VirtualPath="~/MasterPage.master" %>

In code behind

protected void Page_Load(object sender, EventArgs e)
{
this.Master.iframe.Attributes.Add("src", "some.aspx");
}

How to find length of a string array?

String car [];

is a reference to an array of String-s. You can't see a length because there is no array there!

Function to get yesterday's date in Javascript in format DD/MM/YYYY

Try this:

function getYesterdaysDate() {
    var date = new Date();
    date.setDate(date.getDate()-1);
    return date.getDate() + '/' + (date.getMonth()+1) + '/' + date.getFullYear();
}

How to change colors of a Drawable in Android?

In your Activity you can tint your PNG image resources with a single colour:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    myColorTint();
    setContentView(R.layout.activity_main);
}

private void myColorTint() {
    int tint = Color.parseColor("#0000FF"); // R.color.blue;
    PorterDuff.Mode mode = PorterDuff.Mode.SRC_ATOP;
    // add your drawable resources you wish to tint to the drawables array...
    int drawables[] = { R.drawable.ic_action_edit, R.drawable.ic_action_refresh };
    for (int id : drawables) {
        Drawable icon = getResources().getDrawable(id);
        icon.setColorFilter(tint,mode);
    }
}

Now when you use the R.drawable.* it should be coloured with the desired tint. If you need additional colours then you should be able to .mutate() the drawable.

Call of overloaded function is ambiguous

Cast the value so the compiler knows which function to call:

p.setval(static_cast<const char *>( 0 ));

Note, that you have a segmentation fault in your code after you get it to compile (depending on which function you really wanted to call).

Javascript onHover event

If you use the JQuery library you can use the .hover() event which merges the mouseover and mouseout event and helps you with the timing and child elements:

$(this).hover(function(){},function(){});

The first function is the start of the hover and the next is the end. Read more at: http://docs.jquery.com/Events/hover

When to use CouchDB over MongoDB and vice versa

Of C, A & P (Consistency, Availability & Partition tolerance) which 2 are more important to you? Quick reference, the Visual Guide To NoSQL Systems

  • MongodB : Consistency and Partition Tolerance
  • CouchDB : Availability and Partition Tolerance

A blog post, Cassandra vs MongoDB vs CouchDB vs Redis vs Riak vs HBase vs Membase vs Neo4j comparison has 'Best used' scenarios for each NoSQL database compared. Quoting the link,

  • MongoDB: If you need dynamic queries. If you prefer to define indexes, not map/reduce functions. If you need good performance on a big DB. If you wanted CouchDB, but your data changes too much, filling up disks.
  • CouchDB : For accumulating, occasionally changing data, on which pre-defined queries are to be run. Places where versioning is important.

A recent (Feb 2012) and more comprehensive comparison by Riyad Kalla,

  • MongoDB : Master-Slave Replication ONLY
  • CouchDB : Master-Master Replication

A blog post (Oct 2011) by someone who tried both, A MongoDB Guy Learns CouchDB commented on the CouchDB's paging being not as useful.

A dated (Jun 2009) benchmark by Kristina Chodorow (part of team behind MongoDB),

I'd go for MongoDB.

Hope it helps.

Uploading files to file server using webclient class

namespace FileUpload
{
public partial class Form1 : Form
{
    string fileName = "";
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        string path = "";
        OpenFileDialog fDialog = new OpenFileDialog();
        fDialog.Title = "Attach customer proposal document";
        fDialog.Filter = "Doc Files|*.doc|Docx File|*.docx|PDF doc|*.pdf";
        fDialog.InitialDirectory = @"C:\";
        if (fDialog.ShowDialog() == DialogResult.OK)
        {
            fileName = System.IO.Path.GetFileName(fDialog.FileName);
            path = Path.GetDirectoryName(fDialog.FileName);
            textBox1.Text = path + "\\" + fileName;

        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            WebClient client = new WebClient();

            NetworkCredential nc = new NetworkCredential("erandika1986", "123");

            Uri addy = new Uri(@"\\192.168.2.4\UploadDocs\"+fileName);

            client.Credentials = nc;
            byte[] arrReturn = client.UploadFile(addy, textBox1.Text);
            MessageBox.Show(arrReturn.ToString());

        }
        catch (Exception ex1)
        {
            MessageBox.Show(ex1.Message);
        }
    }
}
}

Return background color of selected cell

The code below gives the HEX and RGB value of the range whether formatted using conditional formatting or otherwise. If the range is not formatted using Conditional Formatting and you intend to use iColor function in the Excel as UDF. It won't work. Read the below excerpt from MSDN.

Note that the DisplayFormat property does not work in user defined functions. For example, in a worksheet function that returns the interior color of a cell, if you use a line similar to:

Range.DisplayFormat.Interior.ColorIndex

then the worksheet function executes to return a #VALUE! error. If you are not finding color of the conditionally formatted range, then I encourage you to rather use

Range.Interior.ColorIndex

as then the function can also be used as UDF in Excel. Such as iColor(B1,"HEX")

Public Function iColor(rng As Range, Optional formatType As String) As Variant
'formatType: Hex for #RRGGBB, RGB for (R, G, B) and IDX for VBA Color Index
    Dim colorVal As Variant
    colorVal = rng.DisplayFormat.Interior.Color
    Select Case UCase(formatType)
        Case "HEX"
            iColor = "#" & Format(Hex(colorVal Mod 256),"00") & _
                           Format(Hex((colorVal \ 256) Mod 256),"00") & _
                           Format(Hex((colorVal \ 65536)),"00")
        Case "RGB"
            iColor = Format((colorVal Mod 256),"00") & ", " & _
                     Format(((colorVal \ 256) Mod 256),"00") & ", " & _
                     Format((colorVal \ 65536),"00")
        Case "IDX"
            iColor = rng.Interior.ColorIndex
        Case Else
            iColor = colorVal
    End Select
End Function

'Example use of the iColor function
Sub Get_Color_Format()
    Dim rng As Range

    For Each rng In Selection.Cells
        rng.Offset(0, 1).Value = iColor(rng, "HEX")
        rng.Offset(0, 2).Value = iColor(rng, "RGB")
    Next
End Sub

How to find tags with only certain attributes - BeautifulSoup

The easiest way to do this is with the new CSS style select method:

soup = BeautifulSoup(html)
results = soup.select('td[valign="top"]')

How to pass optional arguments to a method in C++?

With commas separating them, just like parameters without default values.

int func( int x = 0, int y = 0 );

func(); // doesn't pass optional parameters, defaults are used, x = 0 and y = 0

func(1, 2); // provides optional parameters, x = 1 and y = 2

Redirect stderr to stdout in C shell

I object the above answer and provide my own. csh DOES have this capability and here is how it's done:

xxx |& some_exec # will pipe merged output to your some_exec 

or

xxx |& cat > filename

or if you just want it to merge streams (to stdout) and not redirect to a file or some_exec:

xxx |& tee /dev/null

Multiple conditions in WHILE loop

If your code, if the user enters 'X' (for instance), when you reach the while condition evaluation it will determine that 'X' is differente from 'n' (nChar != 'n') which will make your loop condition true and execute the code inside of your loop. The second condition is not even evaluated.

Ignoring a class property in Entity Framework 4.1 Code First

You can use the NotMapped attribute data annotation to instruct Code-First to exclude a particular property

public class Customer
{
    public int CustomerID { set; get; }
    public string FirstName { set; get; } 
    public string LastName{ set; get; } 
    [NotMapped]
    public int Age { set; get; }
}

[NotMapped] attribute is included in the System.ComponentModel.DataAnnotations namespace.

You can alternatively do this with Fluent API overriding OnModelCreating function in your DBContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
   base.OnModelCreating(modelBuilder);
}

http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx

The version I checked is EF 4.3, which is the latest stable version available when you use NuGet.


Edit : SEP 2017

Asp.NET Core(2.0)

Data annotation

If you are using asp.net core (2.0 at the time of this writing), The [NotMapped] attribute can be used on the property level.

public class Customer
{
    public int Id { set; get; }
    public string FirstName { set; get; } 
    public string LastName { set; get; } 
    [NotMapped]
    public int FullName { set; get; }
}

Fluent API

public class SchoolContext : DbContext
{
    public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
        base.OnModelCreating(modelBuilder);
    }
    public DbSet<Customer> Customers { get; set; }
}

How to access Spring MVC model object in javascript file?

Another solution could be using in JSP: <input type="hidden" id="jsonBom" value='${jsonBom}'/>

and getting the value in Javascript with jQuery:

var jsonBom = $('#jsonBom').val();

Regular expression [Any number]

var mask = /^\d+$/;
if ( myString.exec(mask) ){
   /* That's a number */
}

Import file size limit in PHPMyAdmin

Increase phpMyAdmin upload / import size

By default you get a 2mb limit of upload / import size in phpmyadmin. That makes it odd and highly impossible to import larger files. You can increase the allowed upload size of phpmyadmin by editing your server’s php.ini configuration file. Usually in servers like CentOs it is located at /etc/php.ini.

Step 1: Go to php.ini and find the following and change their values to something more higher than your database size. (In this example i have used 20mb).

upload_max_filesize = 20M

post_max_size = 20M

Step2 : Restart your apache service for this new change to take effect. Usually the command to restart apache would be

service httpd restart (CentOs) / service apache2 restart (ubuntu)

You can also restart directly from their path like

/etc/init.d/apache2 restart or /etc/init.d/httpd restart

If you are in a shared hosting and do not have root access or access to your php.ini configuration file, then the other way is to create a .htaccess file in your application root and add the following line

php_value upload_max_filesize 10M
php_value post_max_size 10M

If you were still not able to increase it, please send me an email for more detailed assistance.

How to create a connection string in asp.net c#

Add this in your web.config file

<connectionStrings>
<add name="itmall" 
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-
02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

Why does z-index not work?

Make sure that this element you would like to control with z-index does not have a parent with z-index property, because element is in a lower stacking context due to its parent’s z-index level.

Here's an example:

<section class="content">            
    <div class="modal"></div>
</section>

<div class="side-tab"></div>

// CSS //
.content {
    position: relative;
    z-index: 1;
}

.modal {
    position: fixed;
    z-index: 100;
}

.side-tab {
    position: fixed;
    z-index: 5;
}

In the example above, the modal has a higher z-index than the content, although the content will appear on top of the modal because "content" is the parent with a z-index property.

Here's an article that explains 4 reasons why z-index might not work: https://coder-coder.com/z-index-isnt-working/

How to check for palindrome using Python logic

#compare 1st half with reversed second half
# i.e. 'abba' -> 'ab' == 'ba'[::-1]

def is_palindrome( s ):
   return True if len( s ) < 2 else s[ :len( s ) // 2 ] == s[ -( len( s ) // 2 ):][::-1]

How to write UTF-8 in a CSV file

For me the UnicodeWriter class from Python 2 CSV module documentation didn't really work as it breaks the csv.writer.write_row() interface.

For example:

csv_writer = csv.writer(csv_file)
row = ['The meaning', 42]
csv_writer.writerow(row)

works, while:

csv_writer = UnicodeWriter(csv_file)
row = ['The meaning', 42]
csv_writer.writerow(row)

will throw AttributeError: 'int' object has no attribute 'encode'.

As UnicodeWriter obviously expects all column values to be strings, we can convert the values ourselves and just use the default CSV module:

def to_utf8(lst):
    return [unicode(elem).encode('utf-8') for elem in lst]

...
csv_writer.writerow(to_utf8(row))

Or we can even monkey-patch csv_writer to add a write_utf8_row function - the exercise is left to the reader.

Why should I use IHttpActionResult instead of HttpResponseMessage?

We have the following benefits of using IHttpActionResult over HttpResponseMessage:

  1. By using the IHttpActionResult we are only concentrating on the data to be send not on the status code. So here the code will be cleaner and very easy to maintain.
  2. Unit testing of the implemented controller method will be easier.
  3. Uses async and await by default.

Can two or more people edit an Excel document at the same time?

yes if it is SharePoint 2010 and above by using the Office feature co-authoring

How to see tomcat is running or not

open http://localhost:8080/ in browser, if you get tomcat home page. it means tomcat is running

Switch statement fallthrough in C#?

(Copy/paste of an answer I provided elsewhere)

Falling through switch-cases can be achieved by having no code in a case (see case 0), or using the special goto case (see case 1) or goto default (see case 2) forms:

switch (/*...*/) {
    case 0: // shares the exact same code as case 1
    case 1:
        // do something
        goto case 2;
    case 2:
        // do something else
        goto default;
    default:
        // do something entirely different
        break;
}

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

How to use "not" in xpath?

Use boolean function like below:

//a[(contains(@id, 'xx'))=false]

Java NIO: What does IOException: Broken pipe mean?

Broken pipe means you wrote to a connection that is already closed by the other end.

isConnected() does not detect this condition. Only a write does.

is it wise to always call SocketChannel.isConnected() before attempting a SocketChannel.write()

It is pointless. The socket itself is connected. You connected it. What may not be connected is the connection itself, and you can only determine that by trying it.

How to add directory to classpath in an application run profile in IntelliJ IDEA?

Simply check that the directory/package of the class is marked as "Sources Root". I believe the package should be application or execution in your case.

To do so, right click on the package, and select Mark Directory As->Sources Root.

1

How to use SSH to run a local shell script on a remote machine?

If the script is short and is meant to be embedded inside your script and you are running under bash shell and also bash shell is available on the remote side, you may use declare to transfer local context to remote. Define variables and functions containing the state that will be transferred to the remote. Define a function that will be executed on the remote side. Then inside a here document read by bash -s you can use declare -p to transfer the variable values and use declare -f to transfer function definitions to the remote.

Because declare takes care of the quoting and will be parsed by the remote bash, the variables are properly quoted and functions are properly transferred. You may just write the script locally, usually I do one long function with the work I need to do on the remote side. The context has to be hand-picked, but the following method is "good enough" for any short scripts and is safe - should properly handle all corner cases.

somevar="spaces or other special characters"
somevar2="!@#$%^"
another_func() {
    mkdir -p "$1"
}
work() {
    another_func "$somevar"
    touch "$somevar"/"$somevar2"
}
ssh user@server 'bash -s' <<EOT
$(declare -p somevar somevar2)    # transfer variables values
$(declare -f work another_func)   # transfer function definitions
work                              # call the function
EOT

wait process until all subprocess finish?

subprocess.call

Automatically waits , you can also use:

p1.wait()

What is unexpected T_VARIABLE in PHP?

It could be some other line as well. PHP is not always that exact.

Probably you are just missing a semicolon on previous line.

How to reproduce this error, put this in a file called a.php:

<?php
  $a = 5
  $b = 7;        // Error happens here.
  print $b;
?>

Run it:

eric@dev ~ $ php a.php

PHP Parse error:  syntax error, unexpected T_VARIABLE in
/home/el/code/a.php on line 3

Explanation:

The PHP parser converts your program to a series of tokens. A T_VARIABLE is a Token of type VARIABLE. When the parser processes tokens, it tries to make sense of them, and throws errors if it receives a variable where none is allowed.

In the simple case above with variable $b, the parser tried to process this:

$a = 5 $b = 7;

The PHP parser looks at the $b after the 5 and says "that is unexpected".

JSLint says "missing radix parameter"

I solved it with just using the +foo, to convert the string.

Keep in mind it's not great for readability (dirty fix).

console.log( +'1' )
// 1 (int)

What are "named tuples" in Python?

Named tuples are basically easy-to-create, lightweight object types. Named tuple instances can be referenced using object-like variable dereferencing or the standard tuple syntax. They can be used similarly to struct or other common record types, except that they are immutable. They were added in Python 2.6 and Python 3.0, although there is a recipe for implementation in Python 2.4.

For example, it is common to represent a point as a tuple (x, y). This leads to code like the following:

pt1 = (1.0, 5.0)
pt2 = (2.5, 1.5)

from math import sqrt
line_length = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)

Using a named tuple it becomes more readable:

from collections import namedtuple
Point = namedtuple('Point', 'x y')
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)

from math import sqrt
line_length = sqrt((pt1.x-pt2.x)**2 + (pt1.y-pt2.y)**2)

However, named tuples are still backwards compatible with normal tuples, so the following will still work:

Point = namedtuple('Point', 'x y')
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)

from math import sqrt
# use index referencing
line_length = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)
 # use tuple unpacking
x1, y1 = pt1

Thus, you should use named tuples instead of tuples anywhere you think object notation will make your code more pythonic and more easily readable. I personally have started using them to represent very simple value types, particularly when passing them as parameters to functions. It makes the functions more readable, without seeing the context of the tuple packing.

Furthermore, you can also replace ordinary immutable classes that have no functions, only fields with them. You can even use your named tuple types as base classes:

class Point(namedtuple('Point', 'x y')):
    [...]

However, as with tuples, attributes in named tuples are immutable:

>>> Point = namedtuple('Point', 'x y')
>>> pt1 = Point(1.0, 5.0)
>>> pt1.x = 2.0
AttributeError: can't set attribute

If you want to be able change the values, you need another type. There is a handy recipe for mutable recordtypes which allow you to set new values to attributes.

>>> from rcdtype import *
>>> Point = recordtype('Point', 'x y')
>>> pt1 = Point(1.0, 5.0)
>>> pt1 = Point(1.0, 5.0)
>>> pt1.x = 2.0
>>> print(pt1[0])
    2.0

I am not aware of any form of "named list" that lets you add new fields, however. You may just want to use a dictionary in this situation. Named tuples can be converted to dictionaries using pt1._asdict() which returns {'x': 1.0, 'y': 5.0} and can be operated upon with all the usual dictionary functions.

As already noted, you should check the documentation for more information from which these examples were constructed.

MySQL/SQL: Group by date only on a Datetime column

I found that I needed to group by the month and year so neither of the above worked for me. Instead I used date_format

SELECT date
FROM blog 
GROUP BY DATE_FORMAT(date, "%m-%y")
ORDER BY YEAR(date) DESC, MONTH(date) DESC 

How can I show/hide a specific alert with twitter bootstrap?

I use this alert

_x000D_
_x000D_
function myFunction() {_x000D_
   $('#passwordsNoMatchRegister').fadeIn(1000);_x000D_
   setTimeout(function() { _x000D_
       $('#passwordsNoMatchRegister').fadeOut(1000); _x000D_
   }, 5000);_x000D_
}
_x000D_
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
  <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<button onclick="myFunction()">Try it</button> _x000D_
_x000D_
_x000D_
<div class="alert alert-danger" id="passwordsNoMatchRegister" style="display:none;">_x000D_
    <strong>Error!</strong> Looks like the passwords you entered don't match!_x000D_
  </div>_x000D_
  _x000D_
 _x000D_
  
_x000D_
_x000D_
_x000D_

"Uncaught Error: [$injector:unpr]" with angular after deployment

This problem occurs when the controller or directive are not specified as a array of dependencies and function. For example

angular.module("appName").directive('directiveName', function () {
    return {
        restrict: 'AE',
        templateUrl: 'calender.html',
        controller: function ($scope) {
            $scope.selectThisOption = function () {
                // some code
            };
        }
    };
});

When minified The '$scope' passed to the controller function is replaced by a single letter variable name . This will render angular clueless of the dependency . To avoid this pass the dependency name along with the function as a array.

angular.module("appName").directive('directiveName', function () {
    return {
        restrict: 'AE',
        templateUrl: 'calender.html'
        controller: ['$scope', function ($scope) { //<-- difference
            $scope.selectThisOption = function () {
                // some code
            };
        }]
    };
});

Reading images in python

From documentation:

Matplotlib can only read PNGs natively. Further image formats are supported via the optional dependency on Pillow.

So in case of PNG we may use plt.imread(). In other cases it's probably better to use Pillow directly.

Import XXX cannot be resolved for Java SE standard classes

If the project is Maven, you can try this way :

  1. right click the "Maven Dependencies"-->"Build Path"-->"Remove from the build path";
  2. right click the project ,navigate to "Maven"--->"Update project....";

Then the import issue should be solved .

jQuery window scroll event does not fire up

In my case you should put the function in $(document).ready

$(document).ready(function () {
    $('div#page').on('scroll', function () {
     ...
    });
});

Font scaling based on width of container

In order to make font-size fit its container, rather than the window, see the resizeFont() function I have shared in this question (a combination of other answers, most of which are already linked here). It is triggered using window.addEventListener('resize', resizeFont);.

Vanilla JavaScript: Resize font-awesome to fit container

JavaScript:

function resizeFont() {
  var elements  = document.getElementsByClassName('resize');
  console.log(elements);
  if (elements.length < 0) {
    return;
  }
  _len = elements.length;
  for (_i = 0; _i < _len; _i++) {
    var el = elements[_i];
    el.style.fontSize = "100%";
    for (var size = 100; el.scrollHeight > el.clientHeight; size -= 10) {
      el.style.fontSize = size + '%';
    }
  }
}

You could perhaps use vw/vh as a fallback, so you dynamically assign em or rem units using JavaScript, ensuring that the fonts do scale to the window if JavaScript is disabled.

Apply the .resize class to all elements containing text you wish to be scaled.

Trigger the function prior to adding the window resize event listener. Then, any text which doesn't fit its container will be scaled down when the page loads, as well as when it is resized.

NOTE: The default font-size must be set to either em,rem or % to achieve proper results.

Float vs Decimal in ActiveRecord

I remember my CompSci professor saying never to use floats for currency.

The reason for that is how the IEEE specification defines floats in binary format. Basically, it stores sign, fraction and exponent to represent a Float. It's like a scientific notation for binary (something like +1.43*10^2). Because of that, it is impossible to store fractions and decimals in Float exactly.

That's why there is a Decimal format. If you do this:

irb:001:0> "%.47f" % (1.0/10)
=> "0.10000000000000000555111512312578270211815834045" # not "0.1"!

whereas if you just do

irb:002:0> (1.0/10).to_s
=> "0.1" # the interprer rounds the number for you

So if you are dealing with small fractions, like compounding interests, or maybe even geolocation, I would highly recommend Decimal format, since in decimal format 1.0/10 is exactly 0.1.

However, it should be noted that despite being less accurate, floats are processed faster. Here's a benchmark:

require "benchmark" 
require "bigdecimal" 

d = BigDecimal.new(3) 
f = Float(3)

time_decimal = Benchmark.measure{ (1..10000000).each { |i| d * d } } 
time_float = Benchmark.measure{ (1..10000000).each { |i| f * f } }

puts time_decimal 
#=> 6.770960 seconds 
puts time_float 
#=> 0.988070 seconds

Answer

Use float when you don't care about precision too much. For example, some scientific simulations and calculations only need up to 3 or 4 significant digits. This is useful in trading off accuracy for speed. Since they don't need precision as much as speed, they would use float.

Use decimal if you are dealing with numbers that need to be precise and sum up to correct number (like compounding interests and money-related things). Remember: if you need precision, then you should always use decimal.

How to justify a single flexbox item (override justify-content)

There doesn't seem to be justify-self, but you can achieve similar result setting appropriate margin to auto¹. E. g. for flex-direction: row (default) you should set margin-right: auto to align the child to the left.

_x000D_
_x000D_
.container {_x000D_
  height: 100px;_x000D_
  border: solid 10px skyblue;_x000D_
  _x000D_
  display: flex;_x000D_
  justify-content: flex-end;_x000D_
}_x000D_
.block {_x000D_
  width: 50px;_x000D_
  background: tomato;_x000D_
}_x000D_
.justify-start {_x000D_
  margin-right: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="block justify-start"></div>_x000D_
  <div class="block"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

¹ This behaviour is defined by the Flexbox spec.

Update records in table from CTE

WITH CTE_DocTotal (DocTotal, InvoiceNumber)
AS
(
    SELECT  InvoiceNumber,
            SUM(Sale + VAT) AS DocTotal
    FROM    PEDI_InvoiceDetail
    GROUP BY InvoiceNumber
)    
UPDATE PEDI_InvoiceDetail
SET PEDI_InvoiceDetail.DocTotal = CTE_DocTotal.DocTotal
FROM CTE_DocTotal
INNER JOIN PEDI_InvoiceDetail ON ...

Export result set on Dbeaver to CSV

Is there a reason you couldn't select your results and right click and choose Advanced Copy -> Advanced Copy? I'm on a Mac and this is how I always copy results to the clipboard for pasting.

INNER JOIN ON vs WHERE clause

I know you're talking about MySQL, but anyway: In Oracle 9 explicit joins and implicit joins would generate different execution plans. AFAIK that has been solved in Oracle 10+: there's no such difference anymore.

How to specify table's height such that a vertical scroll bar appears?

Try using the overflow CSS property. There are also separate properties to define the behaviour of just horizontal overflow (overflow-x) and vertical overflow (overflow-y).

Since you only want the vertical scroll, try this:

table {
  height: 500px;
  overflow-y: scroll;
}

EDIT:

Apparently <table> elements don't respect the overflow property. This appears to be because <table> elements are not rendered as display: block by default (they actually have their own display type). You can force the overflow property to work by setting the <table> element to be a block type:

table {
  display: block;
  height: 500px;
  overflow-y: scroll;
}

Note that this will cause the element to have 100% width, so if you don't want it to take up the entire horizontal width of the page, you need to specify an explicit width for the element as well.

HTML image bottom alignment inside DIV container

Flexboxes can accomplish this by using align-items: flex-end; with display: flex; or display: inline-flex;

div#imageContainer {
    height: 160px;  
    align-items: flex-end;
    display: flex;

    /* This is the default value, so you only need to explicitly set it if it's already being set to something else elsewhere. */
    /*flex-direction: row;*/
}

JSFiddle example

CSS-Tricks has a good guide for flexboxes

Code signing is required for product type 'Application' in SDK 'iOS5.1'

The other issue here lies under Code Signing Identity under the Build Settings. Be sure that it contains the Code Signing Identity: "iOS Developer" as opposed to "Don't Code Sign." This will allow you to deploy it to your iOS device. Especially, if you have downloaded a GitHub example or something to this effect.

Count of "Defined" Array Elements

In recent browser, you can use filter

var size = arr.filter(function(value) { return value !== undefined }).length;

console.log(size);

Another method, if the browser supports indexOf for arrays:

var size = arr.slice(0).sort().indexOf(undefined);

If for absurd you have one-digit-only elements in the array, you could use that dirty trick:

console.log(arr.join("").length);

There are several methods you can use, but at the end we have to see if it's really worthy doing these instead of a loop.

C# how to change data in DataTable?

Try the SetField method:

table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);

This should get the job done and is a bit "cleaner" than using Rows[i][j].

How do I display local image in markdown?

The following works with a relative path to an image into a subfolder next to the document (currently only tested on a Windows System):

![image info](./pictures/image.png)

Convert date to UTC using moment.js

This worked for me. Others might find it useful.

// date = 2020-08-31T00:00:00Z I'm located in Denmark (timezone is +2 hours)

moment.utc(moment(date).utc()).format() // returns 2020-08-30T22:00:00Z

How to dump raw RTSP stream to file?

If you are reencoding in your ffmpeg command line, that may be the reason why it is CPU intensive. You need to simply copy the streams to the single container. Since I do not have your command line I cannot suggest a specific improvement here. Your acodec and vcodec should be set to copy is all I can say.

EDIT: On seeing your command line and given you have already tried it, this is for the benefit of others who come across the same question. The command:

ffmpeg -i rtsp://@192.168.241.1:62156 -acodec copy -vcodec copy c:/abc.mp4

will not do transcoding and dump the file for you in an mp4. Of course this is assuming the streamed contents are compatible with an mp4 (which in all probability they are).

What is the http-header "X-XSS-Protection"?

You can see in this List of useful HTTP headers.

X-XSS-Protection: This header enables the Cross-site scripting (XSS) filter built into most recent web browsers. It's usually enabled by default anyway, so the role of this header is to re-enable the filter for this particular website if it was disabled by the user. This header is supported in IE 8+, and in Chrome (not sure which versions). The anti-XSS filter was added in Chrome 4. Its unknown if that version honored this header.

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

Set the space between Elements in Row Flutter

Removing Space-:

new Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              GestureDetector(
                child: new Text('Don\'t have an account?',
                    style: new TextStyle(color: Color(0xFF2E3233))),
                onTap: () {},
              ),
              GestureDetector(
                onTap: (){},
                  child: new Text(
                'Register.',
                style: new TextStyle(
                    color: Color(0xFF84A2AF), fontWeight: FontWeight.bold),
              ))
            ],
          ),

OR

GestureDetector(
            onTap: (){},
            child: new Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Text('Don\'t have an account?',
                    style: new TextStyle(color: Color(0xFF2E3233))),
                new Text(
                  'Register.',
                  style: new TextStyle(
                  color: Color(0xFF84A2AF), fontWeight: FontWeight.bold),
                )
              ],
            ),
          ),

Check if a string contains another string

You can also use the special word like:

Public Sub Search()
  If "My Big String with, in the middle" Like "*,*" Then
    Debug.Print ("Found ','")
  End If
End Sub

How can I convert a Unix timestamp to DateTime and vice versa?

DateTime to UNIX timestamp:

public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
    return (TimeZoneInfo.ConvertTimeToUtc(dateTime) - 
           new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
}

Bootstrap 3: Keep selected tab on page refresh

Well, this is already in 2018 but I think it is better late than never (like a title in a TV program), lol. Down here is the jQuery code that I create during my thesis.

<script type="text/javascript">
$(document).ready(function(){
    $('a[data-toggle="tab"]').on('show.affectedDiv.tab', function(e) {
        localStorage.setItem('activeTab', $(e.target).attr('href'));
    });
    var activeTab = localStorage.getItem('activeTab');
    if(activeTab){
        $('#myTab a[href="' + activeTab + '"]').tab('show');
    }
});
</script>

and here is the code for bootstrap tabs:

<div class="affectedDiv">
    <ul class="nav nav-tabs" id="myTab">
        <li class="active"><a data-toggle="tab" href="#sectionA">Section A</a></li>
        <li><a data-toggle="tab" href="#sectionB">Section B</a></li>
        <li><a data-toggle="tab" href="#sectionC">Section C</a></li>
    </ul>
    <div class="tab-content">
        <div id="sectionA" class="tab-pane fade in active">
            <h3>Section A</h3>
            <p>Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui. Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth.</p>
        </div>
        <div id="sectionB" class="tab-pane fade">
            <h3>Section B</h3>
            <p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
        </div>
        <div id="sectionC" class="tab-pane fade">
            <h3>Section C</h3>
            <p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
        </div>
    </div>
</div>


Dont forget to call the bootstrap and other fundamental things 

here are quick codes for you:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


Now let's come to the explanation:

The jQuery code in the above example simply gets the element's href attribute value when a new tab has been shown using the jQuery .attr() method and save it locally in the user's browser through HTML5 localStorage object. Later, when the user refresh the page it retrieves this data and activate the related tab via .tab('show') method.

Looking up for some examples? here is one for you guys.. https://jsfiddle.net/Wineson123/brseabdr/

I wish my answer could help you all.. Cheerio! :)

What is the LDF file in SQL Server?

The LDF is the transaction log. It keeps a record of everything done to the database for rollback purposes.

You do not want to delete, but you can shrink it with the dbcc shrinkfile command. You can also right-click on the database in SQL Server Management Studio and go to Tasks > Shrink.

Homebrew: Could not symlink, /usr/local/bin is not writable

I found same problem, we can resolve in three steps:-

Step 1

sudo chown -R $(whoami) $(brew --prefix)/*

Step 2

brew doctor

Step 3

brew prune

If you still get any linking problem, lets say for mysql, just write

brew link mysql

This will work.

How do you round a double in Dart to a given degree of precision AFTER the decimal point?

Just write this extension on double

extension Round on double {
  double roundToPrecision(int n) {
    int fac = pow(10, n);
    return (this * fac).round() / fac;
  }
}

How to connect to Oracle 11g database remotely

First. It is necessary add static IP address for Computer A AND B. For example in my case Computer A (172.20.14.13) and B (172.20.14.78).

Second. In Computer A with Net Manager add for Listener new address (172.20.14.13) or manually add new record in listener.ora

# listener.ora Network Configuration File: E:\app\user\product\11.2.0\dbhome_1\NETWORK\ADMIN\listener.ora
# Generated by Oracle configuration tools.

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = E:\app\user\product\11.2.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:E:\app\user\product\11.2.0\dbhome_1\bin\oraclr11.dll")
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.13)(PORT = 1521))
    )
  )

ADR_BASE_LISTENER = E:\app\user

Third. With Net Manager create Service Naming with IP address computer B (172.20.14.78) or manually add new record in tnsnames.ora

# tnsnames.ora Network Configuration File: E:\app\user\product\11.2.0\dbhome_1\NETWORK\ADMIN\tnsnames.ora
# Generated by Oracle configuration tools.

ALINADB =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = alinadb)
    )
  )

LISTENER_ALINADB =
  (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))


LOCAL =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.13)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = alinadb)
    )
  )

ORACLR_CONNECTION_DATA =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
    (CONNECT_DATA =
      (SID = CLRExtProc)
      (PRESENTATION = RO)
    )
  )

ORCL =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.78)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    )
  )

Fourth. In computer B (172.20.14.78) install win64_11gR2_client (For example it is for me in Windows 10 Pro 64 bit )

Five. Create with Net Configuration Assistant listener (localhost) or manually add record in listener.ora

# listener.ora Network Configuration File: F:\app\alinasoft\product\11.2.0\client_1\network\admin\listener.ora
# Generated by Oracle configuration tools.

    LISTENER =
      (DESCRIPTION_LIST =
        (DESCRIPTION =
          (ADDRESS = (PROTOCOL = TCP)(HOST = myserver)(PORT = 1521))
          (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
        )
      )

    ADR_BASE_LISTENER = F:\app\alinasoft

Six. With Net Manager create Service Naming with IP address computer A (172.20.14.13) or manually add new record in tnsnames.ora.

SERVER-DB =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.13)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = alinadb)
    )
  )

Seven (Computer A - (172.20.14.13)) for database operations and connectivity from remote clients, the following executables must be added to the Windows Firewall exception list: (see image) Oracle_home\bin\oracle.exe - Oracle Database executable Oracle_home\bin\tnslsnr.exe - Oracle Listener

Eight Allow connections for port 1158 (Computer A - (172.20.14.13)) for Oracle Enterprise Manager (https://172.20.14.13:1158/em/console/logon/logon)

Ninth Allow connections for port 1521 ( in and out) (Computer A - (172.20.14.17))

Tenth In computer B 172.20.14.78 sqlplus /NOLOG CONNECT system/oracle@//172.20.14.13:1521/alinadb

If uses Toad, in my case is enter image description here

How to get an array of specific "key" in multidimensional array without looping

If id is the first key in the array, this'll do:

$ids = array_map('current', $users);

You should not necessarily rely on this though. :)

Python dict how to create key or append an element to key?

You can use a defaultdict for this.

from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')

This is slightly more efficient than setdefault since you don't end up creating new lists that you don't end up using. Every call to setdefault is going to create a new list, even if the item already exists in the dictionary.

How to get Wikipedia content using Wikipedia's API?

See Is there a clean wikipedia API just for retrieve content summary? for other proposed solutions. Here is one that I suggested:

There is actually a very nice prop called extracts that can be used with queries designed specifically for this purpose. Extracts allow you to get article extracts (truncated article text). There is a parameter called exintro that can be used to retrieve the text in the zeroth section (no additional assets like images or infoboxes). You can also retrieve extracts with finer granularity such as by a certain number of characters (exchars) or by a certain number of sentences(exsentences)

Here is a sample query http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=Stack%20Overflow and the API sandbox http://en.wikipedia.org/wiki/Special:ApiSandbox#action=query&prop=extracts&format=json&exintro=&titles=Stack%20Overflow to experiment more with this query.

Please note that if you want the first paragraph specifically you still need to get the first tag. However in this API call there are no additional assets like images to parse. If you are satisfied with this intro summary you can retrieve the text by running a function like php's strip_tag that remove the html tags.

How can I simulate a print statement in MySQL?

You can print some text by using SELECT command like that:

SELECT 'some text'

Result:

+-----------+
| some text |
+-----------+
| some text |
+-----------+
1 row in set (0.02 sec)

Detecting IE11 using CSS Capability/Feature Detection

You can try this:

if(document.documentMode) {
  document.documentElement.className+=' ie'+document.documentMode;
}

get unique machine id

I'd stay well away from using MAC addresses. On some hardware, the MAC address can change when you reboot. We learned quite early during our research not to rely on it.

Take a look at the article Developing for Software Protection and Licensing which has some pointers on how to design & implement apps to reduce piracy.

Obligatory disclaimer & plug: the company I co-founded produces the OffByZero Cobalt licensing solution. So it probably won't surprise you to hear that I recommend outsourcing your licensing, & focusing on your core competencies.

What is the difference between Nexus and Maven?

This has a good general description: https://gephi.wordpress.com/tag/maven/

Let me make a few statement that can put the difference in focus:

  1. We migrated our code base from Ant to Maven

  2. All 3rd party librairies have been uploaded to Nexus. Maven is using Nexus as a source for libraries.

  3. Basic functionalities of a repository manager like Sonatype are:

    • Managing project dependencies,
    • Artifacts & Metadata,
    • Proxying external repositories
    • and deployment of packaged binaries and JARs to share those artifacts with other developers and end-users.

How do I get user IP address in django?

def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

Make sure you have reverse proxy (if any) configured correctly (e.g. mod_rpaf installed for Apache).

Note: the above uses the first item in X-Forwarded-For, but you might want to use the last item (e.g., in the case of Heroku: Get client's real IP address on Heroku)

And then just pass the request as argument to it;

get_client_ip(request)

Expression must be a modifiable lvalue

Remember that a single = is always an assignment in C or C++.

Your test should be if ( match == 0 && k == M )you made a typo on the k == M test.

If you really mean k=M (i.e. a side-effecting assignment inside a test) you should for readability reasons code if (match == 0 && (k=m) != 0) but most coding rules advise not writing that.

BTW, your mistake suggests to ask for all warnings (e.g. -Wall option to g++), and to upgrade to recent compilers. The next GCC 4.8 will give you:

 % g++-trunk -Wall -c ederman.cc
 ederman.cc: In function ‘void foo()’:
 ederman.cc:9:30: error: lvalue required as left operand of assignment
          if ( match == 0 && k = M )
                               ^

and Clang 3.1 also tells you ederman.cc:9:30: error: expression is not assignable

So use recent versions of free compilers and enable all the warnings when using them.

Android: Center an image

Simply add this to your ImageView.

android:layout_gravity="center" 

CodeIgniter : Unable to load the requested file:

"Unable to load the requested file"

Can be also caused by access permissions under linux , make sure you set the correct read permissions for the directory "views/home"

Return outside function error in Python

As already explained by the other contributers, you could print out the counter and then replace the return with a break statement.

N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
    counter = counter * N
    N = N - 1
    print(counter)
    break

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

You can always check the latest gradle plugin version here: https://bintray.com/android/android-tools/com.android.tools.build.gradle

So as of today you should use:

classpath 'com.android.tools.build:gradle:2.2.2'

accordingly.

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

N+1 SELECT problem is really hard to spot, especially in projects with large domain, to the moment when it starts degrading the performance. Even if the problem is fixed i.e. by adding eager loading, a further development may break the solution and/or introduce N+1 SELECT problem again in other places.

I've created open source library jplusone to address those problems in JPA based Spring Boot Java applications. The library provides two major features:

  1. Generates reports correlating SQL statements with executions of JPA operations which triggered them and places in source code of your application which were involved in it
2020-10-22 18:41:43.236 DEBUG 14913 --- [           main] c.a.j.core.report.ReportGenerator        :
    ROOT
        com.adgadev.jplusone.test.domain.bookshop.BookshopControllerTest.shouldGetBookDetailsLazily(BookshopControllerTest.java:65)
        com.adgadev.jplusone.test.domain.bookshop.BookshopController.getSampleBookUsingLazyLoading(BookshopController.java:31)
        com.adgadev.jplusone.test.domain.bookshop.BookshopService.getSampleBookDetailsUsingLazyLoading [PROXY]
            SESSION BOUNDARY
                OPERATION [IMPLICIT]
                    com.adgadev.jplusone.test.domain.bookshop.BookshopService.getSampleBookDetailsUsingLazyLoading(BookshopService.java:35)
                    com.adgadev.jplusone.test.domain.bookshop.Author.getName [PROXY]
                    com.adgadev.jplusone.test.domain.bookshop.Author [FETCHING ENTITY]
                        STATEMENT [READ]
                            select [...] from
                                author author0_
                                left outer join genre genre1_ on author0_.genre_id=genre1_.id
                            where
                                author0_.id=1
                OPERATION [IMPLICIT]
                    com.adgadev.jplusone.test.domain.bookshop.BookshopService.getSampleBookDetailsUsingLazyLoading(BookshopService.java:36)
                    com.adgadev.jplusone.test.domain.bookshop.Author.countWrittenBooks(Author.java:53)
                    com.adgadev.jplusone.test.domain.bookshop.Author.books [FETCHING COLLECTION]
                        STATEMENT [READ]
                            select [...] from
                                book books0_
                            where
                                books0_.author_id=1
  1. Provides API which allows to write tests checking how effectively your application is using JPA (i.e. assert amount of lazy loading operations )
@SpringBootTest
class LazyLoadingTest {

    @Autowired
    private JPlusOneAssertionContext assertionContext;

    @Autowired
    private SampleService sampleService;

    @Test
    public void shouldBusinessCheckOperationAgainstJPlusOneAssertionRule() {
        JPlusOneAssertionRule rule = JPlusOneAssertionRule
                .within().lastSession()
                .shouldBe().noImplicitOperations().exceptAnyOf(exclusions -> exclusions
                        .loadingEntity(Author.class).times(atMost(2))
                        .loadingCollection(Author.class, "books")
                );

        // trigger business operation which you wish to be asserted against the rule,
        // i.e. calling a service or sending request to your API controller
        sampleService.executeBusinessOperation();

        rule.check(assertionContext);
    }
}

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

MySQL: Get column name or alias from query

Looks like MySQLdb doesn't actually provide a translation for that API call. The relevant C API call is mysql_fetch_fields, and there is no MySQLdb translation for that

Submit form after calling e.preventDefault()

In my case there was a race, as I needed the ajax response to fill a hidden field and send the form after it's filled. I fixed it with putting e.preventDefault() into a condition.

var all_is_done=false;
$("form").submit(function(e){
  if(all_is_done==false){
   e.preventDefault();
   do_the_stuff();
  }
});
function do_the_stuf(){
  //do stuff
  all_is_done=true;
  $("form").submit();
}

Getting Class type from String

Class<?> cls = Class.forName(className);

But your className should be fully-qualified - i.e. com.mycompany.MyClass

convert php date to mysql format

If you know the format of date in $_POST[intake_date] you can use explode to get year , month and time and then concatenate to form a valid mySql date. for example if you are getting something like 12/15/1988 in date you can do like this

    $date = explode($_POST['intake_date'], '/');
    mysql_date = $date[2].'-'$date[1].'-'$date[0];

though if you have valid date date('y-m-d', strtotime($date)); should also work