Programs & Examples On #Extensibility

Make sure that the controller has a parameterless public constructor error

Sometimes because you are resolving your interface in ContainerBootstraper.cs it's very difficult to catch the error. In my case there was an error in resolving the implementation of the interface I've injected to the api controller. I couldn't find the error because I have resolve the interface in my bootstraperContainer like this: container.RegisterType<IInterfaceApi, MyInterfaceImplementaionHelper>(new ContainerControlledLifetimeManager());
then I've adde the following line in my bootstrap container : container.RegisterType<MyController>(); so when I compile the project , compiler complained and stopped in above line and showed the error.

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

I had a similar problem and I solved it by setting a static IP on the Android device.

When you add the network on Android, first you enter the SSID and password, then underneath you can open advanced options and set a static IP.

What is the difference between angular-route and angular-ui-router?

ngRoute is a basic routing library, where you can specify just one view and controller for any route.

With ui-router, you can specify multiple views, both parallel and nested. So if your application requires (or may require in future) any kind of complex routing/views, then go ahead with ui-router.

This is best getting started guide for AngularUI Router.

" netsh wlan start hostednetwork " command not working no matter what I try

This was a real issue for me, and quite a sneaky problem to try and remedy...

The problem I had was that a module that was installed on my WiFi adapter was conflicting with the Microsoft Virtual Adapter (or whatever it's actually called).

To fix it:

  1. Hold the Windows Key + Push R
  2. Type: ncpa.cpl in to the box, and hit OK.
  3. Identify the network adapter you want to use for the hostednetwork, right-click it, and select Properties.
  4. You'll see a big box in the middle of the properties window, under the heading The connection uses the following items:. Look down the list for anything that seems out of the ordinary, and uncheck it. Hit OK.
  5. Try running the netsh wlan start hostednetwork command again.
  6. Repeat steps 4 and 5 as necessary.

In my case my adapter was running a module called SoftEther Lightweight Network Protocol, which I believe is used to help connect to VPN Gate VPN servers via the SoftEther software.

If literally nothing else works, then I'd suspect something similar to the problem I encountered, namely that a module on your network adapter is interfering with the hostednetwork aspect of your driver.

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

If you are looking for high performance matrix/linear algebra/optimization on Intel processors, I'd look at Intel's MKL library.

MKL is carefully optimized for fast run-time performance - much of it based on the very mature BLAS/LAPACK fortran standards. And its performance scales with the number of cores available. Hands-free scalability with available cores is the future of computing and I wouldn't use any math library for a new project doesn't support multi-core processors.

Very briefly, it includes:

  1. Basic vector-vector, vector-matrix, and matrix-matrix operations
  2. Matrix factorization (LU decomp, hermitian,sparse)
  3. Least squares fitting and eigenvalue problems
  4. Sparse linear system solvers
  5. Non-linear least squares solver (trust regions)
  6. Plus signal processing routines such as FFT and convolution
  7. Very fast random number generators (mersenne twist)
  8. Much more.... see: link text

A downside is that the MKL API can be quite complex depending on the routines that you need. You could also take a look at their IPP (Integrated Performance Primitives) library which is geared toward high performance image processing operations, but is nevertheless quite broad.

Paul

CenterSpace Software ,.NET Math libraries, centerspace.net

Android Studio - Emulator - eglSurfaceAttrib not implemented

Fix: Unlock your device before running it.

Hi Guys: Think I may have a fix for this:

Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!

Replace contents of factor column in R dataframe

You want to replace the values in a dataset column, but you're getting an error like this:

invalid factor level, NA generated

Try this instead:

levels(dataframe$column)[levels(dataframe$column)=='old_value'] <- 'new_value'

Which equals operator (== vs ===) should be used in JavaScript comparisons?

Let me add this counsel:

If in doubt, read the specification!

ECMA-262 is the specification for a scripting language of which JavaScript is a dialect. Of course in practice it matters more how the most important browsers behave than an esoteric definition of how something is supposed to be handled. But it is helpful to understand why new String("a") !== "a".

Please let me explain how to read the specification to clarify this question. I see that in this very old topic nobody had an answer for the very strange effect. So, if you can read a specification, this will help you in your profession tremendously. It is an acquired skill. So, let's continue.

Searching the PDF file for === brings me to page 56 of the specification: 11.9.4. The Strict Equals Operator ( === ), and after wading through the specificationalese I find:

11.9.6 The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
  1. If Type(x) is different from Type(y), return false.
  2. If Type(x) is Undefined, return true.
  3. If Type(x) is Null, return true.
  4. If Type(x) is not Number, go to step 11.
  5. If x is NaN, return false.
  6. If y is NaN, return false.
  7. If x is the same number value as y, return true.
  8. If x is +0 and y is -0, return true.
  9. If x is -0 and y is +0, return true.
  10. Return false.
  11. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
  12. If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
  13. Return true if x and y refer to the same object or if they refer to objects joined to each other (see 13.1.2). Otherwise, return false.

Interesting is step 11. Yes, strings are treated as value types. But this does not explain why new String("a") !== "a". Do we have a browser not conforming to ECMA-262?

Not so fast!

Let's check the types of the operands. Try it out for yourself by wrapping them in typeof(). I find that new String("a") is an object, and step 1 is used: return false if the types are different.

If you wonder why new String("a") does not return a string, how about some exercise reading a specification? Have fun!


Aidiakapi wrote this in a comment below:

From the specification

11.2.2 The new Operator:

If Type(constructor) is not Object, throw a TypeError exception.

With other words, if String wouldn't be of type Object it couldn't be used with the new operator.

new always returns an Object, even for String constructors, too. And alas! The value semantics for strings (see step 11) is lost.

And this finally means: new String("a") !== "a".

How to remove MySQL completely with config and library files?

With the command:

sudo apt-get remove --purge mysql\*

you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).

You can list all installed mysql packages with the command:

sudo dpkg -l | grep -i mysql

For more cleanup of the package cache, you can use the command:

sudo apt-get clean

Also, remember to use the command:

sudo updatedb

Otherwise the "locate" command will display old data.

To install mysql again, use the following command:

sudo apt-get install libmysqlclient-dev mysql-client

This will install the mysql client, libmysql and its headers files.

To install the mysql server, use the command:

sudo apt-get install mysql-server

How do I convert a TimeSpan to a formatted string?

Use String.Format() with multiple parameters.

using System;

namespace TimeSpanFormat
{
    class Program
    {
        static void Main(string[] args)
        {
            TimeSpan dateDifference = new TimeSpan(0, 0, 6, 32, 445);
            string formattedTimeSpan = string.Format("{0:D2} hrs, {1:D2} mins, {2:D2} secs", dateDifference.Hours, dateDifference.Minutes, dateDifference.Seconds);
            Console.WriteLine(formattedTimeSpan);
        }
    }
}

Press TAB and then ENTER key in Selenium WebDriver

Using Java:

WebElement webElement = driver.findElement(By.xpath(""));//You can use xpath, ID or name whatever you like
webElement.sendKeys(Keys.TAB);
webElement.sendKeys(Keys.ENTER);

How do I solve the INSTALL_FAILED_DEXOPT error?

I was getting this issue when trying to install on 2.3 devices (fine on 4.0.3). It ended up being due to a lib project i was using had multiple jars which were for stuff already in android e.g. HttpClient and XML parsers etc. Looking at logcat led me to find this as it was telling me it was skipping classes due to them already being present. Nice unhelpful original error there!

How to convert a pymongo.cursor.Cursor into a dict?

The find method returns a Cursor instance, which allows you to iterate over all matching documents.

To get the first document that matches the given criteria you need to use find_one. The result of find_one is a dictionary.

You can always use the list constructor to return a list of all the documents in the collection but bear in mind that this will load all the data in memory and may not be what you want.

You should do that if you need to reuse the cursor and have a good reason not to use rewind()


Demo using find:

>>> import pymongo
>>> conn = pymongo.MongoClient()
>>> db = conn.test #test is my database
>>> col = db.spam #Here spam is my collection
>>> cur = col.find()  
>>> cur
<pymongo.cursor.Cursor object at 0xb6d447ec>
>>> for doc in cur:
...     print(doc)  # or do something with the document
... 
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}
{'a': 1, 'c': 3, '_id': ObjectId('54ff32a2add8f30feb902690'), 'b': 2}

Demo using find_one:

>>> col.find_one()
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}

Succeeded installing but could not start apache 2.4 on my windows 7 system

Sorry for the belabored question. To solve my problem I just told apache 2.4 to listen to a different port in httpd.conf. Since System was using pid 4 which was listening on port 80, I did not want to explore this any further.

I put the following into httpd.conf. Listen 127.0.0.1:122

How to "EXPIRE" the "HSET" child key in redis?

Redis does not support having TTL on hashes other than the top key, which would expire the whole hash. If you are using a sharded cluster, there is another approach you could use. This approach could not be useful in all scenarios and the performance characteristics might differ from the expected ones. Still worth mentioning:

When having a hash, the structure basically looks like:

hash_top_key
  - child_key_1 -> some_value
  - child_key_2 -> some_value
  ...
  - child_key_n -> some_value

Since we want to add TTL to the child keys, we can move them to top keys. The main point is that the key now should be a combination of hash_top_key and child key:

{hash_top_key}child_key_1 -> some_value
{hash_top_key}child_key_2 -> some_value
...
{hash_top_key}child_key_n -> some_value

We are using the {} notation on purpose. This allows all those keys to fall in the same hash slot. You can read more about it here: https://redis.io/topics/cluster-tutorial

Now if we want to do the same operation of hashes, we could do:

HDEL hash_top_key child_key_1 => DEL {hash_top_key}child_key_1

HGET hash_top_key child_key_1 => GET {hash_top_key}child_key_1

HSET hash_top_key child_key_1 some_value => SET {hash_top_key}child_key_1 some_value [some_TTL]

HGETALL hash_top_key => 
  keyslot = CLUSTER KEYSLOT {hash_top_key}
  keys = CLUSTER GETKEYSINSLOT keyslot n
  MGET keys

The interesting one here is HGETALL. First we get the hash slot for all our children keys. Then we get the keys for that particular hash slot and finally we retrieve the values. We need to be careful here since there could be more than n keys for that hash slot and also there could be keys that we are not interested in but they have the same hash slot. We could actually write a Lua script to do those steps in the server by executing an EVAL or EVALSHA command. Again, you need to take into consideration the performance of this approach for your particular scenario.

Some more references:

react change class name on state change

Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

Explanation

Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

Example

_x000D_
_x000D_
class Container extends React.Component {_x000D_
  state = {_x000D_
    activeIndex: null_x000D_
  }_x000D_
_x000D_
  handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
  render() {_x000D_
    return <div>_x000D_
      <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
      <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
      <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
    </div>_x000D_
  }_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
  handleClick = () => this.props.onClick(this.props.index)_x000D_
  _x000D_
  render() {_x000D_
    return <button_x000D_
      type='button'_x000D_
      className={_x000D_
        this.props.isActive ? 'active' : 'album'_x000D_
      }_x000D_
      onClick={ this.handleClick }_x000D_
    >_x000D_
      <span>{ this.props.name }</span>_x000D_
    </button>_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
  content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
  content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Update: "Loops"

In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

// New render method for `Container`
render() {
  const clickables = [
    { name: "a" },
    { name: "b" },
    { name: "c" },
  ]

  return <div>
      { clickables.map(function(clickable, i) {
          return <MyClickable key={ clickable.name }
            name={ clickable.name }
            index={ i }
            isActive={ this.state.activeIndex === i }
            onClick={ this.handleClick }
          />
        } )
      }
  </div>
}

Force overwrite of local file with what's in origin repo?

Full sync has few tasks:

  • reverting changes
  • removing new files
  • get latest from remote repository

git reset HEAD --hard

git clean -f

git pull origin master

Or else, what I prefer is that, I may create a new branch with the latest from the remote using:

git checkout origin/master -b <new branch name>

origin is my remote repository reference, and master is my considered branch name. These may different from yours.

SQL LEFT-JOIN on 2 fields for MySQL

select a.ip, a.os, a.hostname, a.port, a.protocol,
       b.state
from a
left join b on a.ip = b.ip 
           and a.port = b.port

Reason: no suitable image found

I had the same issue and was able to fix by re-downloading the WWDR (Apple Worldwide Developer Relations Certification Authority). Download from here:

and set to Always Trust in the keychain. Changing to Use System Default

it work for me,I hope this help you

Get current batchfile directory

Here's what I use at the top of all my batch files. I just copy/paste from my template folder.

@echo off
:: --HAS ENDING BACKSLASH
set batdir=%~dp0
:: --MISSING ENDING BACKSLASH
:: set batdir=%CD%
pushd "%batdir%"

Setting current batch file's path to %batdir% allows you to call it in subsequent stmts in current batch file, regardless of where this batch file changes to. Using PUSHD allows you to use POPD to quickly set this batch file's path to original %batdir%. Remember, if using %batdir%ExtraDir or %batdir%\ExtraDir (depending on which version used above, ending backslash or not) you will need to enclose the entire string in double quotes if path has spaces (i.e. "%batdir%ExtraDir"). You can always use PUSHD %~dp0. [https: // ss64.com/ nt/ syntax-args .html] has more on (%~) parameters.

Note that using (::) at beginning of a line makes it a comment line. More importantly, using :: allows you to include redirectors, pipes, special chars (i.e. < > | etc) in that comment.

:: ORIG STMT WAS: dir *.* | find /v "1917" > outfile.txt

Of course, Powershell does this and lots more.

Automated Python to Java translation

It may not be an easy problem. Determining how to map classes defined in Python into types in Java will be a big challange because of differences in each of type binding time. (duck typing vs. compile time binding).

Convert number to month name in PHP

A simple tricks here you can use strtotime() function workable as per your need, a convert number to month name.

1.If you want a result in Jan, Feb and Mar Then try below one with the 'M' as a parameter inside the date.

$month=5;
$nmonth = date('M',strtotime("01-".$month."-".date("Y")));
echo $nmonth;

Output : May

/2. You can try with the 'F' instead of 'M' to get the full month name as an output January February March etc.

$month=1;
$nmonth = date('M',strtotime("01-".$month."-".date("Y")));
echo $nmonth;

Output : January

Find if a textbox is disabled or not using jquery

.prop('disabled') will return a Boolean:

var isDisabled = $('textbox').prop('disabled');

Here's the fiddle: http://jsfiddle.net/unhjM/

How to hide underbar in EditText

If you are using the EditText inside TextInputLayout use app:boxBackgroundMode="none" as following:

<com.google.android.material.textfield.TextInputLayout
    app:boxBackgroundMode="none"
    ...
    >

    <EditText
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</com.google.android.material.textfield.TextInputLayout>

Convert a String In C++ To Upper Case

std::string value;
for (std::string::iterator p = value.begin(); value.end() != p; ++p)
    *p = toupper(*p);

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

If you have access to a linux box with mdbtools installed, you can use this Bash shell script (save as mdbconvert.sh):

#!/bin/bash

TABLES=$(mdb-tables -1 $1)

MUSER="root"
MPASS="yourpassword"
MDB="$2"

MYSQL=$(which mysql)

for t in $TABLES
do
    $MYSQL -u $MUSER -p$MPASS $MDB -e "DROP TABLE IF EXISTS $t"
done

mdb-schema $1 mysql | $MYSQL -u $MUSER -p$MPASS $MDB

for t in $TABLES
do
    mdb-export -D '%Y-%m-%d %H:%M:%S' -I mysql $1 $t | $MYSQL -u $MUSER -p$MPASS $MDB
done

To invoke it simply call it like this:

./mdbconvert.sh accessfile.mdb mysqldatabasename

It will import all tables and all data.

How to center the text in a JLabel?

String text = "In early March, the city of Topeka, Kansas," + "<br>" +
              "temporarily changed its name to Google..." + "<br>" + "<br>" +
              "...in an attempt to capture a spot" + "<br>" +
              "in Google's new broadband/fiber-optics project." + "<br>" + "<br>" +"<br>" +
              "source: http://en.wikipedia.org/wiki/Google_server#Oil_Tanker_Data_Center";
JLabel label = new JLabel("<html><div style='text-align: center;'>" + text + "</div></html>");

List of strings to one string

I would go with option A:

String.Join(String.Empty, los.ToArray());

My reasoning is because the Join method was written for that purpose. In fact if you look at Reflector, you'll see that unsafe code was used to really optimize it. The other two also WORK, but I think the Join function was written for this purpose, and I would guess, the most efficient. I could be wrong though...

As per @Nuri YILMAZ without .ToArray(), but this is .NET 4+:

String.Join(String.Empty, los);

Getting date format m-d-Y H:i:s.u from milliseconds

php.net says:

Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.

So use as simple:

$micro_date = microtime();
$date_array = explode(" ",$micro_date);
$date = date("Y-m-d H:i:s",$date_array[1]);
echo "Date: $date:" . $date_array[0]."<br>";

Recommended and use dateTime() class from referenced:

$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );

print $d->format("Y-m-d H:i:s.u"); // note at point on "u"

Note u is microseconds (1 seconds = 1000000 µs).

Another example from php.net:

$d2=new DateTime("2012-07-08 11:14:15.889342");

Reference of dateTime() on php.net

I've answered on question as short and simplify to author. Please see for more information to author: getting date format m-d-Y H:i:s.u from milliseconds

How to center a navigation bar with CSS or HTML?

#nav ul {
    display: inline-block;
    list-style-type: none;
}

It should work, I tested it in your site.

enter image description here

Vim for Windows - What do I type to save and exit from a file?

:q! will force an unconditional no-save exit

Set a form's action attribute when submitting?

<input type='submit' value='Submit' onclick='this.form.action="somethingelse";' />

Or you can modify it from outside the form, with javascript the normal way:

 document.getElementById('form_id').action = 'somethingelse';

With MySQL, how can I generate a column containing the record index in a table?

I found the original answer incredibly helpful but I also wanted to grab a certain set of rows based on the row numbers I was inserting. As such, I wrapped the entire original answer in a subquery so that I could reference the row number I was inserting.

SELECT * FROM 
( 
    SELECT *, @curRow := @curRow + 1 AS "row_number"
    FROM db.tableName, (SELECT @curRow := 0) r
) as temp
WHERE temp.row_number BETWEEN 1 and 10;

Having a subquery in a subquery is not very efficient, so it would be worth testing whether you get a better result by having your SQL server handle this query, or fetching the entire table and having the application/web server manipulate the rows after the fact.

Personally my SQL server isn't overly busy, so having it handle the nested subqueries was preferable.

Stop absolutely positioned div from overlapping text

Thank you for all your answers, Whilst all were correct, none actually solved my problem. The solution for me was to create a second invisible div at the end of the content of unknown length, this invisible div is the same size as my absolutely positioned div, this ensures that there is always a space at the end of my content for the absolutely positioned div.

This answer was previously provided here: Prevent absolutely-positioned elements from overlapping with text However I didn't see (until now) how to apply it to a bottom right positioned div.

New structure is as follows:

_x000D_
_x000D_
<div id="outer" style="position: relative; width:450px; background-color:yellow;">
        <p>Content of unknown length</p>
        <div>Content of unknown height </div>
        <div id="spacer" style="width: 200px; height: 25px; margin-right:0px;"></div>
        <div style="position: absolute; right: 0; bottom: 0px; width: 200px; height: 20px; background-color:red;">bottom right</div>
    </div>
_x000D_
_x000D_
_x000D_

This seems to solve the issue.

What's the difference between the 'ref' and 'out' keywords?

Below I have shown an example using both Ref and out. Now, you all will be cleared about ref and out.

In below mentioned example when i comment //myRefObj = new myClass { Name = "ref outside called!! " }; line, will get an error saying "Use of unassigned local variable 'myRefObj'", but there is no such error in out.

Where to use Ref: when we are calling a procedure with an in parameter and the same parameter will be used to store the output of that proc.

Where to use Out: when we are calling a procedure with no in parameter and teh same param will be used to return the value from that proc. Also note the output

public partial class refAndOutUse : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        myClass myRefObj;
        myRefObj = new myClass { Name = "ref outside called!!  <br/>" };
        myRefFunction(ref myRefObj);
        Response.Write(myRefObj.Name); //ref inside function

        myClass myOutObj;
        myOutFunction(out myOutObj);
        Response.Write(myOutObj.Name); //out inside function
    }

    void myRefFunction(ref myClass refObj)
    {
        refObj.Name = "ref inside function <br/>";
        Response.Write(refObj.Name); //ref inside function
    }
    void myOutFunction(out myClass outObj)
    {
        outObj = new myClass { Name = "out inside function <br/>" }; 
        Response.Write(outObj.Name); //out inside function
    }
}

public class myClass
{
    public string Name { get; set; }
} 

Suppress Scientific Notation in Numpy When Creating Array From Nested List

Python Force-suppress all exponential notation when printing numpy ndarrays, wrangle text justification, rounding and print options:

What follows is an explanation for what is going on, scroll to bottom for code demos.

Passing parameter suppress=True to function set_printoptions works only for numbers that fit in the default 8 character space allotted to it, like this:

import numpy as np
np.set_printoptions(suppress=True) #prevent numpy exponential 
                                   #notation on print, default False

#            tiny     med  large
a = np.array([1.01e-5, 22, 1.2345678e7])  #notice how index 2 is 8 
                                          #digits wide

print(a)    #prints [ 0.0000101   22.     12345678. ]

However if you pass in a number greater than 8 characters wide, exponential notation is imposed again, like this:

np.set_printoptions(suppress=True)

a = np.array([1.01e-5, 22, 1.2345678e10])    #notice how index 2 is 10
                                             #digits wide, too wide!

#exponential notation where we've told it not to!
print(a)    #prints [1.01000000e-005   2.20000000e+001   1.23456780e+10]

numpy has a choice between chopping your number in half thus misrepresenting it, or forcing exponential notation, it chooses the latter.

Here comes set_printoptions(formatter=...) to the rescue to specify options for printing and rounding. Tell set_printoptions to just print bare a bare float:

np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:f}'.format})

a = np.array([1.01e-5, 22, 1.2345678e30])  #notice how index 2 is 30
                                           #digits wide.  

#Ok good, no exponential notation in the large numbers:
print(a)  #prints [0.000010 22.000000 1234567799999999979944197226496.000000] 

We've force-suppressed the exponential notation, but it is not rounded or justified, so specify extra formatting options:

np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:0.2f}'.format})  #float, 2 units 
                                               #precision right, 0 on left

a = np.array([1.01e-5, 22, 1.2345678e30])   #notice how index 2 is 30
                                            #digits wide

print(a)  #prints [0.00 22.00 1234567799999999979944197226496.00]

The drawback for force-suppressing all exponential notion in ndarrays is that if your ndarray gets a huge float value near infinity in it, and you print it, you're going to get blasted in the face with a page full of numbers.

Full example Demo 1:

from pprint import pprint
import numpy as np
#chaotic python list of lists with very different numeric magnitudes
my_list = [[3.74, 5162, 13683628846.64, 12783387559.86, 1.81],
           [9.55, 116, 189688622.37, 260332262.0, 1.97],
           [2.2, 768, 6004865.13, 5759960.98, 1.21],
           [3.74, 4062, 3263822121.39, 3066869087.9, 1.93],
           [1.91, 474, 44555062.72, 44555062.72, 0.41],
           [5.8, 5006, 8254968918.1, 7446788272.74, 3.25],
           [4.5, 7887, 30078971595.46, 27814989471.31, 2.18],
           [7.03, 116, 66252511.46, 81109291.0, 1.56],
           [6.52, 116, 47674230.76, 57686991.0, 1.43],
           [1.85, 623, 3002631.96, 2899484.08, 0.64],
           [13.76, 1227, 1737874137.5, 1446511574.32, 4.32],
           [13.76, 1227, 1737874137.5, 1446511574.32, 4.32]]

#convert python list of lists to numpy ndarray called my_array
my_array = np.array(my_list)

#This is a little recursive helper function converts all nested 
#ndarrays to python list of lists so that pretty printer knows what to do.
def arrayToList(arr):
    if type(arr) == type(np.array):
        #If the passed type is an ndarray then convert it to a list and
        #recursively convert all nested types
        return arrayToList(arr.tolist())
    else:
        #if item isn't an ndarray leave it as is.
        return arr

#suppress exponential notation, define an appropriate float formatter
#specify stdout line width and let pretty print do the work
np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:16.3f}'.format}, linewidth=130)
pprint(arrayToList(my_array))

Prints:

array([[           3.740,         5162.000,  13683628846.640,  12783387559.860,            1.810],
       [           9.550,          116.000,    189688622.370,    260332262.000,            1.970],
       [           2.200,          768.000,      6004865.130,      5759960.980,            1.210],
       [           3.740,         4062.000,   3263822121.390,   3066869087.900,            1.930],
       [           1.910,          474.000,     44555062.720,     44555062.720,            0.410],
       [           5.800,         5006.000,   8254968918.100,   7446788272.740,            3.250],
       [           4.500,         7887.000,  30078971595.460,  27814989471.310,            2.180],
       [           7.030,          116.000,     66252511.460,     81109291.000,            1.560],
       [           6.520,          116.000,     47674230.760,     57686991.000,            1.430],
       [           1.850,          623.000,      3002631.960,      2899484.080,            0.640],
       [          13.760,         1227.000,   1737874137.500,   1446511574.320,            4.320],
       [          13.760,         1227.000,   1737874137.500,   1446511574.320,            4.320]])

Full example Demo 2:

import numpy as np  
#chaotic python list of lists with very different numeric magnitudes 

#            very tiny      medium size            large sized
#            numbers        numbers                numbers

my_list = [[0.000000000074, 5162, 13683628846.64, 1.01e10, 1.81], 
           [1.000000000055,  116, 189688622.37, 260332262.0, 1.97], 
           [0.010000000022,  768, 6004865.13,   -99e13, 1.21], 
           [1.000000000074, 4062, 3263822121.39, 3066869087.9, 1.93], 
           [2.91,            474, 44555062.72, 44555062.72, 0.41], 
           [5,              5006, 8254968918.1, 7446788272.74, 3.25], 
           [0.01,           7887, 30078971595.46, 27814989471.31, 2.18], 
           [7.03,            116, 66252511.46, 81109291.0, 1.56], 
           [6.52,            116, 47674230.76, 57686991.0, 1.43], 
           [1.85,            623, 3002631.96, 2899484.08, 0.64], 
           [13.76,          1227, 1737874137.5, 1446511574.32, 4.32], 
           [13.76,          1337, 1737874137.5, 1446511574.32, 4.32]] 
import sys 
#convert python list of lists to numpy ndarray called my_array 
my_array = np.array(my_list) 
#following two lines do the same thing, showing that np.savetxt can 
#correctly handle python lists of lists and numpy 2D ndarrays. 
np.savetxt(sys.stdout, my_list, '%19.2f') 
np.savetxt(sys.stdout, my_array, '%19.2f') 

Prints:

 0.00             5162.00      13683628846.64      10100000000.00              1.81
 1.00              116.00        189688622.37        260332262.00              1.97
 0.01              768.00          6004865.13 -990000000000000.00              1.21
 1.00             4062.00       3263822121.39       3066869087.90              1.93
 2.91              474.00         44555062.72         44555062.72              0.41
 5.00             5006.00       8254968918.10       7446788272.74              3.25
 0.01             7887.00      30078971595.46      27814989471.31              2.18
 7.03              116.00         66252511.46         81109291.00              1.56
 6.52              116.00         47674230.76         57686991.00              1.43
 1.85              623.00          3002631.96          2899484.08              0.64
13.76             1227.00       1737874137.50       1446511574.32              4.32
13.76             1337.00       1737874137.50       1446511574.32              4.32
 0.00             5162.00      13683628846.64      10100000000.00              1.81
 1.00              116.00        189688622.37        260332262.00              1.97
 0.01              768.00          6004865.13 -990000000000000.00              1.21
 1.00             4062.00       3263822121.39       3066869087.90              1.93
 2.91              474.00         44555062.72         44555062.72              0.41
 5.00             5006.00       8254968918.10       7446788272.74              3.25
 0.01             7887.00      30078971595.46      27814989471.31              2.18
 7.03              116.00         66252511.46         81109291.00              1.56
 6.52              116.00         47674230.76         57686991.00              1.43
 1.85              623.00          3002631.96          2899484.08              0.64
13.76             1227.00       1737874137.50       1446511574.32              4.32
13.76             1337.00       1737874137.50       1446511574.32              4.32

Notice that rounding is consistent at 2 units precision, and exponential notation is suppressed in both the very large e+x and very small e-x ranges.

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

My issue was similar - I had a new table i was creating that ahd to tie in to the identity users. After reading the above answers, realized it had to do with IsdentityUser and the inherited properites. I already had Identity set up as its own Context, so to avoid inherently tying the two together, rather than using the related user table as a true EF property, I set up a non-mapped property with the query to get the related entities. (DataManager is set up to retrieve the current context in which OtherEntity exists.)

    [Table("UserOtherEntity")]
        public partial class UserOtherEntity
        {
            public Guid UserOtherEntityId { get; set; }
            [Required]
            [StringLength(128)]
            public string UserId { get; set; }
            [Required]
            public Guid OtherEntityId { get; set; }
            public virtual OtherEntity OtherEntity { get; set; }
        }

    public partial class UserOtherEntity : DataManager
        {
            public static IEnumerable<OtherEntity> GetOtherEntitiesByUserId(string userId)
            {
                return Connect2Context.UserOtherEntities.Where(ue => ue.UserId == userId).Select(ue => ue.OtherEntity);
            }
        }

public partial class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

        [NotMapped]
        public IEnumerable<OtherEntity> OtherEntities
        {
            get
            {
                return UserOtherEntities.GetOtherEntitiesByUserId(this.Id);
            }
        }
    }

Oracle SQL Developer: Unable to find a JVM

Version 1.5 is very, very old.

In the latest builds, we support 32 and 64 bit JDKs. In version 4.0, we find the JDK for you on Windows. If the software can't find it, it prompts for that path.

That path would look something like this C:\Java\jdk1.7.0_45

You can read more about this here.

How to overwrite the previous print to stdout in python?

(Python3) This is what worked for me. If you just use the \010 then it will leave characters, so I tweaked it a bit to make sure it's overwriting what was there. This also allows you to have something before the first print item and only removed the length of the item.

print("Here are some strings: ", end="")
items = ["abcd", "abcdef", "defqrs", "lmnop", "xyz"]
for item in items:
    print(item, end="")
    for i in range(len(item)): # only moving back the length of the item
        print("\010 \010", end="") # the trick!
        time.sleep(0.2) # so you can see what it's doing

How can I move a tag on a git branch to a different commit?

I'll leave here just another form of this command that suited my needs.
There was a tag v0.0.1.2 that I wanted to move.

$ git tag -f v0.0.1.2 63eff6a

Updated tag 'v0.0.1.2' (was 8078562)

And then:

$ git push --tags --force

How do I use System.getProperty("line.separator").toString()?

The problem

You must NOT assume that an arbitrary input text file uses the "correct" platform-specific newline separator. This seems to be the source of your problem; it has little to do with regex.

To illustrate, on the Windows platform, System.getProperty("line.separator") is "\r\n" (CR+LF). However, when you run your Java code on this platform, you may very well have to deal with an input file whose line separator is simply "\n" (LF). Maybe this file was originally created in Unix platform, and then transferred in binary (instead of text) mode to Windows. There could be many scenarios where you may run into these kinds of situations, where you must parse a text file as input which does not use the current platform's newline separator.

(Coincidentally, when a Windows text file is transferred to Unix in binary mode, many editors would display ^M which confused some people who didn't understand what was going on).

When you are producing a text file as output, you should probably prefer the platform-specific newline separator, but when you are consuming a text file as input, it's probably not safe to make the assumption that it correctly uses the platform specific newline separator.


The solution

One way to solve the problem is to use e.g. java.util.Scanner. It has a nextLine() method that can return the next line (if one exists), correctly handling any inconsistency between the platform's newline separator and the input text file.

You can also combine 2 Scanner, one to scan the file line by line, and another to scan the tokens of each line. Here's a simple usage example that breaks each line into a List<String>. The entire file therefore becomes a List<List<String>>.

This is probably a better approach than reading the entire file into one huge String and then split into lines (which are then split into parts).

    String text
        = "row1\tblah\tblah\tblah\n"
        + "row2\t1\t2\t3\t4\r\n"
        + "row3\tA\tB\tC\r"
        + "row4";

    System.out.println(text);
    //  row1    blah    blah    blah
    //  row2    1   2   3   4
    //  row3    A   B   C
    //  row4

    List<List<String>> input = new ArrayList<List<String>>();

    Scanner sc = new Scanner(text);
    while (sc.hasNextLine()) {
        Scanner lineSc = new Scanner(sc.nextLine()).useDelimiter("\t");
        List<String> line = new ArrayList<String>();
        while (lineSc.hasNext()) {
            line.add(lineSc.next());
        }
        input.add(line);
    }
    System.out.println(input);
    // [[row1, blah, blah, blah], [row2, 1, 2, 3, 4], [row3, A, B, C], [row4]]

See also

  • Effective Java 2nd Edition, Item 25: Prefer lists to arrays

Related questions

Display all dataframe columns in a Jupyter Python Notebook

Try the display max_columns setting as follows:

import pandas as pd
from IPython.display import display

df = pd.read_csv("some_data.csv")
pd.options.display.max_columns = None
display(df)

Or

pd.set_option('display.max_columns', None)

Edit: Pandas 0.11.0 backwards

This is deprecated but in versions of Pandas older than 0.11.0 the max_columns setting is specified as follows:

pd.set_printoptions(max_columns=500)

jQuery - passing value from one input to another

Assuming you can put ID's on the inputs:

$('#name').change(function() {
    $('#firstname').val($(this).val());
});

JSFiddle Example

Otherwise you'll have to select using the names:

$('input[name="name"]').change(function() {
    $('input[name="firstname"]').val($(this).val());
});

Define the selected option with the old input in Laravel / Blade

<select style="width: 100%;" name="id_driver" id="id_driver" >
  <option value="" @if (old('id_driver') == "")  selected @endif>Select</option>
  @foreach(\App\Driver::all() as $driver)
    <option value="{{$driver->id}}" @if (old('id_driver') == $driver->id)  
        selected  @endif >(#{{$driver->id}}) {{$driver->business_name}}
    </option>
  @endforeach
</select>

Change the "No file chosen":

<div class="field">
    <label class="field-label" for="photo">Your photo</label>
    <input class="field-input" type="file" name="photo"  id="photo" value="photo" />
</div>

and the css

input[type="file"]
{ 
   color: transparent; 
   background-color: #F89406; 
   border: 2px solid #34495e; 
   width: 100%; 
   height: 36px; 
   border-radius: 3px; 
}

ORDER BY the IN value list

To do this, I think you should probably have an additional "ORDER" table which defines the mapping of IDs to order (effectively doing what your response to your own question said), which you can then use as an additional column on your select which you can then sort on.

In that way, you explicitly describe the ordering you desire in the database, where it should be.

How to provide animation when calling another activity in Android?

Wrote a tutorial so that you can animate your activity's in and out,

Enjoy:

http://blog.blundellapps.com/animate-an-activity/

How do I set browser width and height in Selenium WebDriver?

Here is firefox profile default prefs from python selenium 2.31.0 firefox_profile.py

and type "about:config" in firefox address bar to see all prefs

reference to the entries in about:config: http://kb.mozillazine.org/About:config_entries

DEFAULT_PREFERENCES = {
    "app.update.auto": "false",
    "app.update.enabled": "false",
    "browser.download.manager.showWhenStarting": "false",
    "browser.EULA.override": "true",
    "browser.EULA.3.accepted": "true",
    "browser.link.open_external": "2",
    "browser.link.open_newwindow": "2",
    "browser.offline": "false",
    "browser.safebrowsing.enabled": "false",
    "browser.search.update": "false",
    "extensions.blocklist.enabled": "false",
    "browser.sessionstore.resume_from_crash": "false",
    "browser.shell.checkDefaultBrowser": "false",
    "browser.tabs.warnOnClose": "false",
    "browser.tabs.warnOnOpen": "false",
    "browser.startup.page": "0",
    "browser.safebrowsing.malware.enabled": "false",
    "startup.homepage_welcome_url": "\"about:blank\"",
    "devtools.errorconsole.enabled": "true",
    "dom.disable_open_during_load": "false",
    "extensions.autoDisableScopes" : 10,
    "extensions.logging.enabled": "true",
    "extensions.update.enabled": "false",
    "extensions.update.notifyUser": "false",
    "network.manage-offline-status": "false",
    "network.http.max-connections-per-server": "10",
    "network.http.phishy-userpass-length": "255",
    "offline-apps.allow_by_default": "true",
    "prompts.tab_modal.enabled": "false",
    "security.fileuri.origin_policy": "3",
    "security.fileuri.strict_origin_policy": "false",
    "security.warn_entering_secure": "false",
    "security.warn_entering_secure.show_once": "false",
    "security.warn_entering_weak": "false",
    "security.warn_entering_weak.show_once": "false",
    "security.warn_leaving_secure": "false",
    "security.warn_leaving_secure.show_once": "false",
    "security.warn_submit_insecure": "false",
    "security.warn_viewing_mixed": "false",
    "security.warn_viewing_mixed.show_once": "false",
    "signon.rememberSignons": "false",
    "toolkit.networkmanager.disable": "true",
    "toolkit.telemetry.enabled": "false",
    "toolkit.telemetry.prompted": "2",
    "toolkit.telemetry.rejected": "true",
    "javascript.options.showInConsole": "true",
    "browser.dom.window.dump.enabled": "true",
    "webdriver_accept_untrusted_certs": "true",
    "webdriver_enable_native_events": "true",
    "webdriver_assume_untrusted_issuer": "true",
    "dom.max_script_run_time": "30",
    }

How to build and run Maven projects after importing into Eclipse IDE

Just install the m2e plugin for Eclipse. Then a new command in Eclipse's Import statement will be added called "Import existing maven projects".

Basic Ajax send/receive with node.js

I was facing following error with code (nodejs 0.10.13), provided by ampersand:

origin is not allowed by access-control-allow-origin

Issue was resolved changing

response.writeHead(200, {"Content-Type": "text/plain"});

to

response.writeHead(200, {
                 'Content-Type': 'text/html',
                 'Access-Control-Allow-Origin' : '*'});

Android SharedPreferences in Fragment

This did the trick for me

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());

Check here https://developer.android.com/guide/topics/ui/settings.html#ReadingPrefs

Open PDF in new browser full window

I'm going to take a chance here and actually advise against this. I suspect that people wanting to view your PDFs will already have their viewers set up the way they want, and will not take kindly to you taking that choice away from them :-)

Why not just stream down the content with the correct content specifier?

That way, newbies will get whatever their browser developer has a a useful default, and those of us that know how to configure such things will see it as we want to.

How to unapply a migration in ASP.NET Core with EF Core

You should delete migration '20160703192724_MyFirstMigration' record from '_EFMigrationsHistory' table.

otherwise this command will remove migration and delete migrations folder:

PMC Command:

   > remove-migration -force

CLI Command:

   > dotnet ef migrations remove -f

Link About CLI Commands

Link About PMC Commands

Simple dictionary in C++

A table out of char array:

char map[256] = { 0 };
map['T'] = 'A'; 
map['A'] = 'T';
map['C'] = 'G';
map['G'] = 'C';
/* .... */

How to display an error message in an ASP.NET Web Application

The errors in ASP.Net are saved on the Server.GetLastError property,

Or i would put a label on the asp.net page for displaying the error.

try
{
    do something
}
catch (YourException ex)
{
    errorLabel.Text = ex.Message;
    errorLabel.Visible = true;
}

Java: Integer equals vs. ==

Besides these given great answers, What I have learned is that:

NEVER compare objects with == unless you intend to be comparing them by their references.

Tomcat is not running even though JAVA_HOME path is correct

I deleted the Tomcat and unzipped it again and it worked.

How to get the path of current worksheet in VBA?

If you want to get the path of the workbook from where the macro is being executed - use Application.ThisWorkbook.Path.
Application.ActiveWorkbook.Path can sometimes produce unexpected results (e.g. if your macro switches between multiple workbooks).

How to get anchor text/href on click using jQuery?

Alternative

Using the example from Sarfraz above.

<div class="res">
    <a class="info_link" href="~/Resumes/Resumes1271354404687.docx">
        ~/Resumes/Resumes1271354404687.docx
    </a>
</div>

For href:

$(function(){
  $('.res').on('click', '.info_link', function(){
    alert($(this)[0].href);
  });
});

JSON and XML comparison

Faster is not an attribute of JSON or XML or a result that a comparison between those would yield. If any, then it is an attribute of the parsers or the bandwidth with which you transmit the data.

Here is (the beginning of) a list of advantages and disadvantages of JSON and XML:


JSON

Pro:

  • Simple syntax, which results in less "markup" overhead compared to XML.
  • Easy to use with JavaScript as the markup is a subset of JS object literal notation and has the same basic data types as JavaScript.
  • JSON Schema for description and datatype and structure validation
  • JsonPath for extracting information in deeply nested structures

Con:

  • Simple syntax, only a handful of different data types are supported.

  • No support for comments.


XML

Pro:

  • Generalized markup; it is possible to create "dialects" for any kind of purpose
  • XML Schema for datatype, structure validation. Makes it also possible to create new datatypes
  • XSLT for transformation into different output formats
  • XPath/XQuery for extracting information in deeply nested structures
  • built in support for namespaces

Con:

  • Relatively wordy compared to JSON (results in more data for the same amount of information).

So in the end you have to decide what you need. Obviously both formats have their legitimate use cases. If you are mostly going to use JavaScript then you should go with JSON.

Please feel free to add pros and cons. I'm not an XML expert ;)

How to get enum value by string or int

Simply try this

It's another way

public enum CaseOriginCode
{
    Web = 0,
    Email = 1,
    Telefoon = 2
}

public void setCaseOriginCode(string CaseOriginCode)
{
    int caseOriginCode = (int)(CaseOriginCode)Enum.Parse(typeof(CaseOriginCode), CaseOriginCode);
}

Linux command-line call not returning what it should from os.system?

The simplest way is like this:

import os
retvalue = os.popen("ps -p 2993 -o time --no-headers").readlines()
print retvalue

This will be returned as a list

How to suppress scientific notation when printing float values?

As of 3.6 (probably works with slightly older 3.x as well), this is my solution:

import locale
locale.setlocale(locale.LC_ALL, '')

def number_format(n, dec_precision=4):
    precision = len(str(round(n))) + dec_precision
    return format(float(n), f'.{precision}n')

The purpose of the precision calculation is to ensure we have enough precision to keep out of scientific notation (default precision is still 6).

The dec_precision argument adds additional precision to use for decimal points. Since this makes use of the n format, no insignificant zeros will be added (unlike f formats). n also will take care of rendering already-round integers without a decimal.

n does require float input, thus the cast.

Undo working copy modifications of one file in Git?

This answers is for command needed for undoing local changes which are in multiple specific files in same or multiple folders (or directories). This answers specifically addresses question where a user has more than one file but the user doesn't want to undo all local changes:

if you have one or more files you could apply the same command (git checkout -- file ) to each of those files by listing each of their location separated by space as in:

git checkout -- name1/name2/fileOne.ext nameA/subFolder/fileTwo.ext

mind the space above between name1/name2/fileOne.ext nameA/subFolder/fileTwo.ext

For multiple files in the same folder:

If you happen to need to discard changes for all of the files in a certain directory, use the git checkout as follows:

git checkout -- name1/name2/*

The asterisk in the above does the trick of undoing all files at that location under name1/name2.

And, similarly the following can undo changes in all files for multiple folders:

git checkout -- name1/name2/* nameA/subFolder/*

again mind the space between name1/name2/* nameA/subFolder/* in the above.

Note: name1, name2, nameA, subFolder - all of these example folder names indicate the folder or package where the file(s) in question may be residing.

Best Way to do Columns in HTML/CSS

You might also try.

_x000D_
_x000D_
.col{_x000D_
  float: left;_x000D_
}_x000D_
.col + .col{_x000D_
  float: left;_x000D_
  margin-left: 20px;_x000D_
}_x000D_
_x000D_
/* or */_x000D_
_x000D_
.col:not(:nth-child(1)){_x000D_
  float:left;_x000D_
  margin-left: 20px;_x000D_
}_x000D_
_x000D_
 
_x000D_
<div class="row">_x000D_
  <div class="col">column</div>_x000D_
  <div class="col">column</div>_x000D_
  <div class="col">column</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ref: http://codepen.io/co0kie/pen/gPKNWX?editors=1100

Cannot start MongoDB as a service

For mongoDB 3.0, You will have to set the following in the config file.

logpath=E:\mongoDBdata\log\mongoDB.log
dbpath=E:\mongoDBdata\db

the logpath should end with a file and not a folder.

how to set start value as "0" in chartjs?

For Chart.js 2.*, the option for the scale to begin at zero is listed under the configuration options of the linear scale. This is used for numerical data, which should most probably be the case for your y-axis. So, you need to use this:

options: {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
    }
}

A sample line chart is also available here where the option is used for the y-axis. If your numerical data is on the x-axis, use xAxes instead of yAxes. Note that an array (and plural) is used for yAxes (or xAxes), because you may as well have multiple axes.

How to pass a view's onClick event to its parent on Android?

If you want to both OnTouch and OnClick listener to parent and child view both, please use below trick:

  1. User ScrollView as a Parent view and inside that placed your child view inside Relative/LinearLayout.

  2. Make Parent ScrollView android:fillViewport="true" so View not be scrolled.

  3. Then set OnTouch listener to parent and OnClick listener to Child views. And enjoy both listener callbacks.

What is web.xml file and what are all things can I do with it?

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet>
    <description></description>
    <display-name>pdfServlet</display-name>
    <servlet-name>pdfServlet</servlet-name>
    <servlet-class>com.sapta.smartcam.servlet.pdfServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>pdfServlet</servlet-name>
    <url-pattern>/pdfServlet</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

How to add "on delete cascade" constraints?

I'm pretty sure you can't simply add on delete cascade to an existing foreign key constraint. You have to drop the constraint first, then add the correct version. In standard SQL, I believe the easiest way to do this is to

  • start a transaction,
  • drop the foreign key,
  • add a foreign key with on delete cascade, and finally
  • commit the transaction

Repeat for each foreign key you want to change.

But PostgreSQL has a non-standard extension that lets you use multiple constraint clauses in a single SQL statement. For example

alter table public.scores
drop constraint scores_gid_fkey,
add constraint scores_gid_fkey
   foreign key (gid)
   references games(gid)
   on delete cascade;

If you don't know the name of the foreign key constraint you want to drop, you can either look it up in pgAdminIII (just click the table name and look at the DDL, or expand the hierarchy until you see "Constraints"), or you can query the information schema.

select *
from information_schema.key_column_usage
where position_in_unique_constraint is not null

How to tag an older commit in Git?

Use command:

git tag v1.0 ec32d32

Where v1.0 is the tag name and ec32d32 is the commit you want to tag

Once done you can push the tags by:

git push origin --tags

Reference:

Git (revision control): How can I tag a specific previous commit point in GitHub?

Open popup and refresh parent page on close popup

The pop-up window does not have any close event that you can listen to.

On the other hand, there is a closed property that is set to true when the window gets closed.

You can set a timer to check that closed property and do it like this:

var win = window.open('foo.html', 'windowName',"width=200,height=200,scrollbars=no");   
var timer = setInterval(function() {   
    if(win.closed) {  
        clearInterval(timer);  
        alert('closed');  
    }  
}, 1000); 

See this working Fiddle example!

Refresh image with a new one at the same url

I improved the script from AlexMA for showing my webcam on a web page wich periodically uploads a new image with the same name. I had issues that sometimes the image was flickering because of a broken image or not complete (up)loaded image. To prevent flickering I check the natural height of the image because the size of my webcam image did not change. Only if the loaded image height fits the original image height the full image will be shown on page.

  <h3>Webcam</h3>
  <p align="center">
    <img id="webcam" title="Webcam" onload="updateImage();" src="https://www.your-domain.com/webcam/current.jpg" alt="webcam image" width="900" border="0" />

    <script type="text/javascript" language="JavaScript">

    // off-screen image to preload next image
    var newImage = new Image();
    newImage.src = "https://www.your-domain.com/webcam/current.jpg";

    // remember the image height to prevent showing broken images
    var height = newImage.naturalHeight;

    function updateImage()
    {
        // for sure if the first image was a broken image
        if(newImage.naturalHeight > height)
        {
          height = newImage.naturalHeight;
        }

        // off-screen image loaded and the image was not broken
        if(newImage.complete && newImage.naturalHeight == height) 
        {
          // show the preloaded image on page
          document.getElementById("webcam").src = newImage.src;
        }

        // preload next image with cachebreaker
        newImage.src = "https://www.your-domain.com/webcam/current.jpg?time=" + new Date().getTime();

        // refresh image (set the refresh interval to half of webcam refresh, 
        // in my case the webcam refreshes every 5 seconds)
        setTimeout(updateImage, 2500);
    }

    </script>
</p>

List append() in for loop

No need to re-assign.

a=[]
for i in range(5):    
    a.append(i)
a

Eclipse count lines of code

If on OSX or *NIX use

Get all actual lines of java code from *.java files

find . -name "*.java" -exec grep "[a-zA-Z0-9{}]" {} \; | wc -l

Get all lines from the *.java files, which includes empty lines and comments

find . -name "*.java" -exec cat | wc -l

Get information per File, this will give you [ path to file + "," + number of lines ]

find . -name "*.java" -exec wc -l {} \;

How to POST form data with Spring RestTemplate?

The POST method should be sent along the HTTP request object. And the request may contain either of HTTP header or HTTP body or both.

Hence let's create an HTTP entity and send the headers and parameter in body.

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "[email protected]");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#postForObject-java.lang.String-java.lang.Object-java.lang.Class-java.lang.Object...-

How do I remove time part from JavaScript date?

This is probably the easiest way:

new Date(<your-date-object>.toDateString());

Example: To get the Current Date without time component:

new Date(new Date().toDateString());

gives: Thu Jul 11 2019 00:00:00 GMT-0400 (Eastern Daylight Time)

Note this works universally, because toDateString() produces date string with your browser's localization (without the time component), and the new Date() uses the same localization to parse that date string.

Raw SQL Query without DbSet - Entity Framework Core

Building on the other answers I've written this helper that accomplishes the task, including example usage:

public static class Helper
{
    public static List<T> RawSqlQuery<T>(string query, Func<DbDataReader, T> map)
    {
        using (var context = new DbContext())
        {
            using (var command = context.Database.GetDbConnection().CreateCommand())
            {
                command.CommandText = query;
                command.CommandType = CommandType.Text;

                context.Database.OpenConnection();

                using (var result = command.ExecuteReader())
                {
                    var entities = new List<T>();

                    while (result.Read())
                    {
                        entities.Add(map(result));
                    }

                    return entities;
                }
            }
        }
    }

Usage:

public class TopUser
{
    public string Name { get; set; }

    public int Count { get; set; }
}

var result = Helper.RawSqlQuery(
    "SELECT TOP 10 Name, COUNT(*) FROM Users U"
    + " INNER JOIN Signups S ON U.UserId = S.UserId"
    + " GROUP BY U.Name ORDER BY COUNT(*) DESC",
    x => new TopUser { Name = (string)x[0], Count = (int)x[1] });

result.ForEach(x => Console.WriteLine($"{x.Name,-25}{x.Count}"));

I plan to get rid of it as soon as built-in support is added. According to a statement by Arthur Vickers from the EF Core team it is a high priority for post 2.0. The issue is being tracked here.

Is it possible to use the instanceof operator in a switch statement?

there is an even simpler way of emulating a switch structure that uses instanceof, you do this by creating a code block in your method and naming it with a label. Then you use if structures to emulate the case statements. If a case is true then you use the break LABEL_NAME to get out of your makeshift switch structure.

        DEFINE_TYPE:
        {
            if (a instanceof x){
                //do something
                break DEFINE_TYPE;
            }
            if (a instanceof y){
               //do something
                break DEFINE_TYPE;
            }
            if (a instanceof z){
                // do something
                break DEFINE_TYPE;
            }
        }

syntax for creating a dictionary into another dictionary in python

You can declare a dictionary inside a dictionary by nesting the {} containers:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

And then you can access the elements using the [] syntax:

print d['dict1']           # {'foo': 1, 'bar': 2}
print d['dict1']['foo']    # 1
print d['dict2']['quux']   # 4

Given the above, if you want to add another dictionary to the dictionary, it can be done like so:

d['dict3'] = {'spam': 5, 'ham': 6}

or if you prefer to add items to the internal dictionary one by one:

d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8

Why do we have to normalize the input for an artificial neural network?

The reason normalization is needed is because if you look at how an adaptive step proceeds in one place in the domain of the function, and you just simply transport the problem to the equivalent of the same step translated by some large value in some direction in the domain, then you get different results. It boils down to the question of adapting a linear piece to a data point. How much should the piece move without turning and how much should it turn in response to that one training point? It makes no sense to have a changed adaptation procedure in different parts of the domain! So normalization is required to reduce the difference in the training result. I haven't got this written up, but you can just look at the math for a simple linear function and how it is trained by one training point in two different places. This problem may have been corrected in some places, but I am not familiar with them. In ALNs, the problem has been corrected and I can send you a paper if you write to wwarmstrong AT shaw.ca

Algorithm to compare two images

I believe if you're willing to apply the approach to every possible orientation and to negative versions, a good start to image recognition (with good reliability) is to use eigenfaces: http://en.wikipedia.org/wiki/Eigenface

Another idea would be to transform both images into vectors of their components. A good way to do this is to create a vector that operates in x*y dimensions (x being the width of your image and y being the height), with the value for each dimension applying to the (x,y) pixel value. Then run a variant of K-Nearest Neighbours with two categories: match and no match. If it's sufficiently close to the original image it will fit in the match category, if not then it won't.

K Nearest Neighbours(KNN) can be found here, there are other good explanations of it on the web too: http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm

The benefits of KNN is that the more variants you're comparing to the original image, the more accurate the algorithm becomes. The downside is you need a catalogue of images to train the system first.

Why is it important to override GetHashCode when Equals method is overridden?

As of .NET 4.7 the preferred method of overriding GetHashCode() is shown below. If targeting older .NET versions, include the System.ValueTuple nuget package.

// C# 7.0+
public override int GetHashCode() => (FooId, FooName).GetHashCode();

In terms of performance, this method will outperform most composite hash code implementations. The ValueTuple is a struct so there won't be any garbage, and the underlying algorithm is as fast as it gets.

How to parse JSON string in Typescript

There is a great library for it ts-json-object

In your case you would need to run the following code:

import {JSONObject, required} from 'ts-json-object'

class Response extends JSONObject {
    @required
    name: string;

    @required
    error: boolean;
}

let resp = new Response({"name": "Bob", "error": false});

This library will validate the json before parsing

Where is my m2 folder on Mac OS X Mavericks

If you search directly it won't appear so please follow as below steps to see .M2 repository path.

Go-> Find folder ->  type this "~/.m2" and click go

If Maven is already installed and used, the .m2 will be listed.

Source

Fatal error: Call to undefined function pg_connect()

You need to install the php-pgsql package or whatever it's called for your platform. Which I don't think you said by the way.

On Ubuntu and Debian:

sudo apt-get install php5-pgsql

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

To state the obvious, the cup represents outerScopeVar.

Asynchronous functions be like...

asynchronous call for coffee

How to remove only 0 (Zero) values from column in excel 2010

You shouldn't use a space " " instead of "0" because the excel deal with the space as a value.

So, the answer is with the option by (Ctrl + F). Then, click the options and put in the Find with "0". Next, click (Match entire cell contents. Finally, replaced or replaced all up to you.

This solution can give more also. You can use (*) before or after the values to delete any parts you want.

Thanks.

Are querystring parameters secure in HTTPS (HTTP + SSL)?

Yes. The querystring is also encrypted with SSL. Nevertheless, as this article shows, it isn't a good idea to put sensitive information in the URL. For example:

URLs are stored in web server logs - typically the whole URL of each request is stored in a server log. This means that any sensitive data in the URL (e.g. a password) is being saved in clear text on the server

Use jQuery to navigate away from page

window.location = myUrl;

Anyway, this is not jQuery: it's plain javascript

How to retrieve form values from HTTPPOST, dictionary or?

You could have your controller action take an object which would reflect the form input names and the default model binder will automatically create this object for you:

[HttpPost]
public ActionResult SubmitAction(SomeModel model)
{
    var value1 = model.SimpleProp1;
    var value2 = model.SimpleProp2;
    var value3 = model.ComplexProp1.SimpleProp1;
    ...

    ... return something ...
}

Another (obviously uglier) way is:

[HttpPost]
public ActionResult SubmitAction()
{
    var value1 = Request["SimpleProp1"];
    var value2 = Request["SimpleProp2"];
    var value3 = Request["ComplexProp1.SimpleProp1"];
    ...

    ... return something ...
}

Find integer index of rows with NaN in pandas dataframe

Don't know if this is too late but you can use np.where to find the indices of non values as such:

indices = list(np.where(df['b'].isna()[0]))

Fatal error: Class 'PHPMailer' not found

This answers in an extension to what avs099 has given above, for those who are still having problems:

1.Makesure that you have php_openssl.dll installed(else find it online and install it);

2.Go to your php.ini; find extension=php_openssl.dll enable it/uncomment

3.Go to github and downland the latetest version :6.0 at this time.

4.Extract the master copy into the path that works better for you(I recommend the same directory as the calling file)

Now copy this code into your foo-mailer.php and render it with your gmail stmp authentications.

    require("/PHPMailer-master/src/PHPMailer.php");
    require("/PHPMailer-master/src/SMTP.php");
    require("/PHPMailer-master/src/Exception.php");


    $mail = new PHPMailer\PHPMailer\PHPMailer();
    $mail->IsSMTP(); 

    $mail->CharSet="UTF-8";
    $mail->Host = "smtp.gmail.com";
    $mail->SMTPDebug = 1; 
    $mail->Port = 465 ; //465 or 587

     $mail->SMTPSecure = 'ssl';  
    $mail->SMTPAuth = true; 
    $mail->IsHTML(true);

    //Authentication
    $mail->Username = "[email protected]";
    $mail->Password = "*******";

    //Set Params
    $mail->SetFrom("[email protected]");
    $mail->AddAddress("[email protected]");
    $mail->Subject = "Test";
    $mail->Body = "hello";


     if(!$mail->Send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
     } else {
        echo "Message has been sent";
     }

Disclaimer:The original owner of the code above is avs099 with just my little input.

Take note of the additional:

a) (PHPMailer\PHPMailer) namespace:needed for name conflict resolution.

b) The (require("/PHPMailer-master/src/Exception.php");):It was missing in avs099's code thus the problem encountered by aProgger,you need that line to tell the mailer class where the Exception class is located.

Split a large pandas dataframe

Use np.array_split:

Docstring:
Split an array into multiple sub-arrays.

Please refer to the ``split`` documentation.  The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis.

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
   ...:                           'foo', 'bar', 'foo', 'foo'],
   ...:                    'B' : ['one', 'one', 'two', 'three',
   ...:                           'two', 'two', 'one', 'three'],
   ...:                    'C' : randn(8), 'D' : randn(8)})

In [3]: print df
     A      B         C         D
0  foo    one -0.174067 -0.608579
1  bar    one -0.860386 -1.210518
2  foo    two  0.614102  1.689837
3  bar  three -0.284792 -1.071160
4  foo    two  0.843610  0.803712
5  bar    two -1.514722  0.870861
6  foo    one  0.131529 -0.968151
7  foo  three -1.002946 -0.257468

In [4]: import numpy as np
In [5]: np.array_split(df, 3)
Out[5]: 
[     A    B         C         D
0  foo  one -0.174067 -0.608579
1  bar  one -0.860386 -1.210518
2  foo  two  0.614102  1.689837,
      A      B         C         D
3  bar  three -0.284792 -1.071160
4  foo    two  0.843610  0.803712
5  bar    two -1.514722  0.870861,
      A      B         C         D
6  foo    one  0.131529 -0.968151
7  foo  three -1.002946 -0.257468]

Where is SQL Profiler in my SQL Server 2008?

first get the profiler Exe from: http://expressprofiler.codeplex.com

then you can add it simply to the Management studio:

Tools -> External tools... ->

a- locate the exe file on your disk (If installed, it's typically C:\Program Files (x86)\ExpressProfiler\ExpressProfiler.exe)

b- give it a name e.g. Express Profiler

that's it :) you have your Profiler with your sql express edition

enter image description here

How to wait for the 'end' of 'resize' event and only then perform an action?

There is a much simpler method to execute a function at the end of the resize than calculate the delta time between two calls, simply do it like this :

var resizeId;
$(window).resize(function() {
    clearTimeout(resizeId);
    resizeId = setTimeout(resizedEnded, 500);
});

function resizedEnded(){
    ...
}

And the equivalent for Angular2 :

private resizeId;
@HostListener('window:resize', ['$event'])
onResized(event: Event) {
  clearTimeout(this.resizeId);
  this.resizeId = setTimeout(() => {
    // Your callback method here.
  }, 500);
}

For the angular method, use the () => { } notation in the setTimeout to preserve the scope, otherwise you will not be able to make any function calls or use this.

Swing JLabel text change on the running application

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
    private JLabel label;
    private JTextField field;
    public Test()
    {
        super("The title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 90));
        ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
        setLayout(new FlowLayout());
        JButton btn = new JButton("Change");
        btn.setActionCommand("myButton");
        btn.addActionListener(this);
        label = new JLabel("flag");
        field = new JTextField(5);
        add(field);
        add(btn);
        add(label);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals("myButton"))
        {
            label.setText(field.getText());
        }
    }
    public static void main(String[] args)
    {
        new Test();
    }
}

How to set the font size in Emacs?

In AquaMacs CMD + and CMD - adjust the font size for the current buffer.

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

I got this error because I had forgotten to add my username behind the key in the GCE metadata section. For instance, you are meant to add an entry into the metadata section which looks like this:

sshKeys    username:key

I forgot the username: part and thus when I tried to login with that username, I got the no supported auth methods error.

Or, to turn off the ssh key requirement entirely, check out my other answer.

File Upload In Angular?

In Angular 2+, it is very important to leave the Content-Type empty. If you set the 'Content-Type' to 'multipart/form-data' the upload will not work !

upload.component.html

<input type="file" (change)="fileChange($event)" name="file" />

upload.component.ts

export class UploadComponent implements OnInit {
    constructor(public http: Http) {}

    fileChange(event): void {
        const fileList: FileList = event.target.files;
        if (fileList.length > 0) {
            const file = fileList[0];

            const formData = new FormData();
            formData.append('file', file, file.name);

            const headers = new Headers();
            // It is very important to leave the Content-Type empty
            // do not use headers.append('Content-Type', 'multipart/form-data');
            headers.append('Authorization', 'Bearer ' + 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9....');
            const options = new RequestOptions({headers: headers});

            this.http.post('https://api.mysite.com/uploadfile', formData, options)
                 .map(res => res.json())
                 .catch(error => Observable.throw(error))
                 .subscribe(
                     data => console.log('success'),
                     error => console.log(error)
                 );
        }
    }
}

Get safe area inset top and bottom heights

I'm working with CocoaPods frameworks and in case UIApplication.shared is unavailable then I use safeAreaInsets in view's window:

if #available(iOS 11.0, *) {
    let insets = view.window?.safeAreaInsets
    let top = insets.top
    let bottom = insets.bottom
}

Turn off deprecated errors in PHP 5.3

You can do it in code by calling the following functions.

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

or

error_reporting(E_ALL ^ E_DEPRECATED);

What is the best JavaScript code to create an img element

As others pointed out if you are allowed to use a framework like jQuery the best thing to do is use it, as it high likely will do it in the best possible way. If you are not allowed to use a framework then I guess manipulating the DOM is the best way to do it (and in my opinion, the right way to do it).

Uncaught TypeError: data.push is not a function

you can use push method only if the object is an array:

var data = new Array();
data.push({"country": "IN"}).

OR

data['country'] = "IN"

if it's just an object you can use

data.country = "IN";

Maven is not working in Java 8 when Javadoc tags are incomplete

Since it depends on the version of your JRE which is used to run the maven command you propably dont want to disable DocLint per default in your pom.xml

Hence, from command line you can use the switch -Dadditionalparam=-Xdoclint:none.

Example: mvn clean install -Dadditionalparam=-Xdoclint:none

Copy / Put text on the clipboard with FireFox, Safari and Chrome

Use modern document.execCommand("copy") and jQuery. See this stackoverflow answer

var ClipboardHelper = { // as Object

copyElement: function ($element)
{
   this.copyText($element.text())
},
copyText:function(text) // Linebreaks with \n
{
    var $tempInput =  $("<textarea>");
    $("body").append($tempInput);
    $tempInput.val(text).select();
    document.execCommand("copy");
    $tempInput.remove();
}};

How to Call:

 ClipboardHelper.copyText('Hello\nWorld');
 ClipboardHelper.copyElement($('body h1').first());

_x000D_
_x000D_
// JQUERY DOCUMENT_x000D_
;(function ( $, window, document, undefined ) {_x000D_
  _x000D_
  var ClipboardHelper = {_x000D_
_x000D_
    copyElement: function ($element)_x000D_
    {_x000D_
       this.copyText($element.text())_x000D_
    },_x000D_
    copyText:function(text) // Linebreaks with \n_x000D_
    {_x000D_
        var $tempInput =  $("<textarea>");_x000D_
        $("body").append($tempInput);_x000D_
      _x000D_
        //todo prepare Text: remove double whitespaces, trim_x000D_
        _x000D_
        $tempInput.val(text).select();_x000D_
        document.execCommand("copy");_x000D_
        $tempInput.remove();_x000D_
    }_x000D_
};_x000D_
_x000D_
    $(document).ready(function()_x000D_
    {_x000D_
         var $body=$('body');_x000D_
         _x000D_
        $body.on('click', '*[data-copy-text-to-clipboard]', function(event) _x000D_
        {_x000D_
            var $btn=$(this);_x000D_
            var text=$btn.attr('data-copy-text-to-clipboard');_x000D_
            ClipboardHelper.copyText(text);_x000D_
        });_x000D_
      _x000D_
        $body.on('click', '.js-copy-element-to-clipboard', function(event) _x000D_
        {_x000D_
            ClipboardHelper.copyElement($(this));_x000D_
        });_x000D_
_x000D_
    });_x000D_
_x000D_
_x000D_
})( jQuery, window, document );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<span data-copy-text-to-clipboard=_x000D_
"Hello_x000D_
 World">_x000D_
  Copy Text_x000D_
</span>_x000D_
<br><br>_x000D_
<span class="js-copy-element-to-clipboard">_x000D_
Hello_x000D_
World _x000D_
Element_x000D_
</span>
_x000D_
_x000D_
_x000D_

Node.js - EJS - including a partial

_x000D_
_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
_x000D_
 <form method="post" class="mt-3">_x000D_
        <div class="form-group col-md-4">_x000D_
          <input type="text" class="form-control form-control-lg" id="plantName" name="plantName" placeholder="plantName">_x000D_
        </div>_x000D_
        <div class="form-group col-md-4">_x000D_
          <input type="text" class="form-control form-control-lg" id="price" name="price" placeholder="price">_x000D_
        </div>_x000D_
        <div class="form-group col-md-4">_x000D_
            <input type="text" class="form-control form-control-lg" id="harvestTime" name="harvestTime" placeholder="time to harvest">_x000D_
          </div>_x000D_
        <button type="submit" class="btn btn-primary btn-lg col-md-4">Submit</button>_x000D_
      </form>_x000D_
_x000D_
<form method="post">_x000D_
        <table class="table table-striped table-responsive-md">_x000D_
            <thead>_x000D_
            <tr>_x000D_
                <th scope="col">Id</th>_x000D_
                <th scope="col">FarmName</th>_x000D_
                <th scope="col">Player Name</th>_x000D_
                <th scope="col">Birthday Date</th>_x000D_
                <th scope="col">Money</th>_x000D_
                <th scope="col">Day Played</th>_x000D_
                <th scope="col">Actions</th>_x000D_
            </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
            <%for (let i = 0; i < farms.length; i++) {%>_x000D_
                 <tr>_x000D_
                    <td><%= farms[i]['id'] %></td>_x000D_
                    <td><%= farms[i]['farmName'] %></td>_x000D_
                    <td><%= farms[i]['playerName'] %></td>_x000D_
                    <td><%= farms[i]['birthDayDate'] %></td>_x000D_
                    <td><%= farms[i]['money'] %></td>_x000D_
                    <td><%= farms[i]['dayPlayed'] %></td>_x000D_
                    <td><a href="<%=`/farms/${farms[i]['id']}`%>">Look at Farm</a></td>_x000D_
                </tr>_x000D_
            <%}%>_x000D_
        </table>_x000D_
    </form>
_x000D_
_x000D_
_x000D_

How to convert a Collection to List?

I think Paul Tomblin's answer may be wasteful in case coll is already a list, because it will create a new list and copy all elements. If coll contains many elemeents, this may take a long time.

My suggestion is:

List list;
if (coll instanceof List)
  list = (List)coll;
else
  list = new ArrayList(coll);
Collections.sort(list);

How to debug in Android Studio using adb over WiFi

just open settings / plugins / search " Android wifi adb and download it and connect your mobile using usb cabble once and its done

Carousel with Thumbnails in Bootstrap 3.0

Just found out a great plugin for this:

http://flexslider.woothemes.com/

Regards

What is `git push origin master`? Help with git's refs, heads and remotes

Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.

Commands

Make sure you're on your master branch with

1)git checkout master

then create the new branch with

2)git branch --track my_test origin/my_test

and check it out with

3)git checkout my_test.

You can then push and pull without specifying which local and remote.

However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:

git pull -u my_test origin/my_test
git push -u my_test origin/my_test

Config

The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.

[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
    remote = origin
    merge = refs/heads/my_test

This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.

You can find something very similar to this in the config after running the commands above.

Some useful resources:

How to make Git "forget" about a file that was tracked but is now in .gitignore?

Do the following steps for file/folder:

Remove File:

  1. need to add that file to .gitignore.
  2. need to remove that file using the command (git rm --cached file name).
  3. need to run (git add .).
  4. need to (commit -m) "file removed".
  5. and finally, (git push).

For example:

I want to delete test.txt file. I accidentally pushed to GitHub want to remove commands will be followed as:

1st add test.txt in .gitignore

git rm --cached test.txt
git add .
git commit -m "test.txt removed"
git push

Remove Folder:

  1. need to add that folder to .gitignore.
  2. need to remove that folder using the command (git rm -r --cached folder name).
  3. need to run (git add .).
  4. need to (commit -m) "folder removed".
  5. and finally, (git push).

For example:

I want to delete the .idea folder/dir. I accidentally pushed to GitHub want to remove commands will be followed as:

1st add .idea in .gitignore

git rm -r --cached .idea
git add .
git commit -m ".idea removed"
git push

Can I load a UIImage from a URL?

You can try SDWebImage, it provides:

  1. Asynchronous loading
  2. Caching for offline use
  3. Place holder image to appear while loading
  4. Works well with UITableView

Quick example:

    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

Activate a virtualenv with a Python script

You should create all your virtualenvs in one folder, such as virt.

Assuming your virtualenv folder name is virt, if not change it

cd
mkdir custom

Copy the below lines...

#!/usr/bin/env bash
ENV_PATH="$HOME/virt/$1/bin/activate"
bash --rcfile $ENV_PATH -i

Create a shell script file and paste the above lines...

touch custom/vhelper
nano custom/vhelper

Grant executable permission to your file:

sudo chmod +x custom/vhelper

Now export that custom folder path so that you can find it on the command-line by clicking tab...

export PATH=$PATH:"$HOME/custom"

Now you can use it from anywhere by just typing the below command...

vhelper YOUR_VIRTUAL_ENV_FOLDER_NAME

Suppose it is abc then...

vhelper abc

Writing data into CSV file in C#

This is a simple tutorial on creating csv files using C# that you will be able to edit and expand on to fit your own needs.

First you’ll need to create a new Visual Studio C# console application, there are steps to follow to do this.

The example code will create a csv file called MyTest.csv in the location you specify. The contents of the file should be 3 named columns with text in the first 3 rows.

https://tidbytez.com/2018/02/06/how-to-create-a-csv-file-with-c/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace CreateCsv
{
    class Program
    {
        static void Main()
        {
            // Set the path and filename variable "path", filename being MyTest.csv in this example.
            // Change SomeGuy for your username.
            string path = @"C:\Users\SomeGuy\Desktop\MyTest.csv";

            // Set the variable "delimiter" to ", ".
            string delimiter = ", ";

            // This text is added only once to the file.
            if (!File.Exists(path))
            {
                // Create a file to write to.
                string createText = "Column 1 Name" + delimiter + "Column 2 Name" + delimiter + "Column 3 Name" + delimiter + Environment.NewLine;
                File.WriteAllText(path, createText);
            }

            // This text is always added, making the file longer over time
            // if it is not deleted.
            string appendText = "This is text for Column 1" + delimiter + "This is text for Column 2" + delimiter + "This is text for Column 3" + delimiter + Environment.NewLine;
            File.AppendAllText(path, appendText);

            // Open the file to read from.
            string readText = File.ReadAllText(path);
            Console.WriteLine(readText);
        }
    }
}

What is middleware exactly?

Some examples of middleware: CORBA, Remote Method Invocation (RMI),...

The examples mentioned above are all pieces of software allowing you to take care of communication between different processes (either running on the same machine or distributed over e.g. the internet).

repaint() in Java

Simply write :

frame.validate();
frame.repaint();

That will do .

Regards

Convert a float64 to an int in Go

Simply casting to an int truncates the float, which if your system internally represent 2.0 as 1.9999999999, you will not get what you expect. The various printf conversions deal with this and properly round the number when converting. So to get a more accurate value, the conversion is even more complicated than you might first expect:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    floats := []float64{1.9999, 2.0001, 2.0}
    for _, f := range floats {
        t := int(f)
        s := fmt.Sprintf("%.0f", f)
        if i, err := strconv.Atoi(s); err == nil {
            fmt.Println(f, t, i)
        } else {
            fmt.Println(f, t, err)
        }
    }
}

Code on Go Playground

What is the difference between ng-if and ng-show/ng-hide

ng-show and ng-hide work in opposite way. But the difference between ng-hide or ng-show with ng-if is,if we use ng-if then element will created in the dom but with ng-hide/ng-show element will be hidden completely.

ng-show=true/ng-hide=false:
Element will be displayed

ng-show=false/ng-hide=true:
element will be hidden

ng-if =true
element will be created

ng-if= false
element will be created in the dom. 

Setting Custom ActionBar Title from Fragment

In your MainActivity, under onCreate:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

And in your fragment activity under onResume:

getActivity().setTitle(R.string.app_name_science);

Optional:- if they show warning of null reference

Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);


Objects.requireNonNull(getActivity()).setTitle(R.string.app_name_science);

Submitting a form by pressing enter without a submit button

This is my solution, tested in Chrome, Firefox 6 and IE7+:

.hidden{
    height: 1px;
    width: 1px;
    position: absolute;
    z-index: -100;
}

How can I get a channel ID from YouTube?

You can get the channel ID with the username (in your case "klauskkpm") using the filter "forUsername", like this:

https://www.googleapis.com/youtube/v3/channels?key={YOUR_API_KEY}&forUsername=klauskkpm&part=id

More info here: https://developers.google.com/youtube/v3/docs/channels/list

Python Inverse of a Matrix

You should have a look at numpy if you do matrix manipulation. This is a module mainly written in C, which will be much faster than programming in pure python. Here is an example of how to invert a matrix, and do other matrix manipulation.

from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] )                  # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] )                      # Creates a matrix (like a row vector).
print A.T                                    # Transpose of A.
print A*x                                    # Matrix multiplication of A and x.
print A.I                                    # Inverse of A.
print linalg.solve(A, x)     # Solve the linear equation system.

You can also have a look at the array module, which is a much more efficient implementation of lists when you have to deal with only one data type.

Access-Control-Allow-Origin wildcard subdomains, ports and protocols

It looks like the original answer was for pre Apache 2.4. It did not work for me. Here's what I had to change to make it work in 2.4. This will work for any depth of subdomain of yourcompany.com.

SetEnvIf Host ^((?:.+\.)*yourcompany\.com?)$    CORS_ALLOW_ORIGIN=$1
Header append Access-Control-Allow-Origin  %{REQUEST_SCHEME}e://%{CORS_ALLOW_ORIGIN}e    env=CORS_ALLOW_ORIGIN
Header merge  Vary "Origin"

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

For a more generic and extensible way check mergedict. It uses singledispatch and can merge values based on its types.

Example:

from mergedict import MergeDict

class SumDict(MergeDict):
    @MergeDict.dispatch(int)
    def merge_int(this, other):
        return this + other

d2 = SumDict({'a': 1, 'b': 'one'})
d2.merge({'a':2, 'b': 'two'})

assert d2 == {'a': 3, 'b': 'two'}

How to send email to multiple recipients with addresses stored in Excel?

ToAddress = "[email protected]"
ToAddress1 = "[email protected]"
ToAddress2 = "[email protected]"
MessageSubject = "It works!."
Set ol = CreateObject("Outlook.Application")
Set newMail = ol.CreateItem(olMailItem)
newMail.Subject = MessageSubject
newMail.RecipIents.Add(ToAddress)
newMail.RecipIents.Add(ToAddress1)
newMail.RecipIents.Add(ToAddress2)
newMail.Send

What does O(log n) mean exactly?

I cannot understand how to identify a function with a log time.

The most common attributes of logarithmic running-time function are that:

  • the choice of the next element on which to perform some action is one of several possibilities, and
  • only one will need to be chosen.

or

  • the elements on which the action is performed are digits of n

This is why, for example, looking up people in a phone book is O(log n). You don't need to check every person in the phone book to find the right one; instead, you can simply divide-and-conquer by looking based on where their name is alphabetically, and in every section you only need to explore a subset of each section before you eventually find someone's phone number.

Of course, a bigger phone book will still take you a longer time, but it won't grow as quickly as the proportional increase in the additional size.


We can expand the phone book example to compare other kinds of operations and their running time. We will assume our phone book has businesses (the "Yellow Pages") which have unique names and people (the "White Pages") which may not have unique names. A phone number is assigned to at most one person or business. We will also assume that it takes constant time to flip to a specific page.

Here are the running times of some operations we might perform on the phone book, from fastest to slowest:

  • O(1) (in the worst case): Given the page that a business's name is on and the business name, find the phone number.

  • O(1) (in the average case): Given the page that a person's name is on and their name, find the phone number.

  • O(log n): Given a person's name, find the phone number by picking a random point about halfway through the part of the book you haven't searched yet, then checking to see whether the person's name is at that point. Then repeat the process about halfway through the part of the book where the person's name lies. (This is a binary search for a person's name.)

  • O(n): Find all people whose phone numbers contain the digit "5".

  • O(n): Given a phone number, find the person or business with that number.

  • O(n log n): There was a mix-up at the printer's office, and our phone book had all its pages inserted in a random order. Fix the ordering so that it's correct by looking at the first name on each page and then putting that page in the appropriate spot in a new, empty phone book.

For the below examples, we're now at the printer's office. Phone books are waiting to be mailed to each resident or business, and there's a sticker on each phone book identifying where it should be mailed to. Every person or business gets one phone book.

  • O(n log n): We want to personalize the phone book, so we're going to find each person or business's name in their designated copy, then circle their name in the book and write a short thank-you note for their patronage.

  • O(n2): A mistake occurred at the office, and every entry in each of the phone books has an extra "0" at the end of the phone number. Take some white-out and remove each zero.

  • O(n · n!): We're ready to load the phonebooks onto the shipping dock. Unfortunately, the robot that was supposed to load the books has gone haywire: it's putting the books onto the truck in a random order! Even worse, it loads all the books onto the truck, then checks to see if they're in the right order, and if not, it unloads them and starts over. (This is the dreaded bogo sort.)

  • O(nn): You fix the robot so that it's loading things correctly. The next day, one of your co-workers plays a prank on you and wires the loading dock robot to the automated printing systems. Every time the robot goes to load an original book, the factory printer makes a duplicate run of all the phonebooks! Fortunately, the robot's bug-detection systems are sophisticated enough that the robot doesn't try printing even more copies when it encounters a duplicate book for loading, but it still has to load every original and duplicate book that's been printed.

How to automatically generate a stacktrace when my program crashes

The new king in town has arrived https://github.com/bombela/backward-cpp

1 header to place in your code and 1 library to install.

Personally I call it using this function

#include "backward.hpp"
void stacker() {

using namespace backward;
StackTrace st;


st.load_here(99); //Limit the number of trace depth to 99
st.skip_n_firsts(3);//This will skip some backward internal function from the trace

Printer p;
p.snippet = true;
p.object = true;
p.color = true;
p.address = true;
p.print(st, stderr);
}

How to disable scrolling temporarily?

My take on this issue also includes a concern with the body width, as the page seems to dance a little when we hide the scroll bar with overflow = "hidden". The following code works perfectly for me, and is based on an Angular approach.

element.bind('mouseenter', function() {
    var w = document.body.offsetWidth;
    document.body.style.overflow = 'hidden';
    document.body.style.width = w + 'px';
});

element.bind('mouseleave', function() {
    document.body.style.overflow = 'initial';
    document.body.style.width = 'auto';
});

Xcode build failure "Undefined symbols for architecture x86_64"

When updating to Xcode 7.1, you might see this type of error, and it can't be resolved by any of the above answers. One of the symptoms in my case was that the app runs on the device not in the simulator. You'll probably see a huge number of errors related to pretty much all of the frameworks you're using.

The fix is actually quite simple. You just need to delete an entry from the "Framework Search Paths" setting, found in your TARGETS > Build Settings > Search Paths section (make sure the "All" tab is selected)

enter image description here

If you see another entry here (besides $(inherited)) for your main target(s) or your test target, just delete the faulty path from all targets and rebuild.

How to print multiple lines of text with Python

The triple quotes answer is great for ASCII art, but for those wondering - what if my multiple lines are a tuple, list, or other iterable that returns strings (perhaps a list comprehension?), then how about:

print("\n".join(<*iterable*>))

For example:

print("\n".join(["{}={}".format(k, v) for k, v in os.environ.items() if 'PATH' in k]))

Is it safe to expose Firebase apiKey to the public?

It is oky to include them, and special care is required only for Firebase ML or when using Firebase Authentication

API keys for Firebase are different from typical API keys: Unlike how API keys are typically used, API keys for Firebase services are not used to control access to backend resources; that can only be done with Firebase Security Rules. Usually, you need to fastidiously guard API keys (for example, by using a vault service or setting the keys as environment variables); however, API keys for Firebase services are ok to include in code or checked-in config files.

Although API keys for Firebase services are safe to include in code, there are a few specific cases when you should enforce limits for your API key; for example, if you're using Firebase ML or using Firebase Authentication with the email/password sign-in method. Learn more about these cases later on this page.

For more informations, check the offical docs

How to use QTimer

Other way is using of built-in method start timer & event TimerEvent.

Header:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    int timerId;

protected:
    void timerEvent(QTimerEvent *event);
};

#endif // MAINWINDOW_H

Source:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    timerId = startTimer(1000);
}

MainWindow::~MainWindow()
{
    killTimer(timerId);
    delete ui;
}

void MainWindow::timerEvent(QTimerEvent *event)
{
    qDebug() << "Update...";
}

Java replace issues with ' (apostrophe/single quote) and \ (backslash) together

Remember that stringToEdit.replaceAll(String, String) returns the result string. It doesn't modify stringToEdit because Strings are immutable in Java. To get any change to stick, you should use

stringToEdit = stringToEdit.replaceAll("'", "\\'");

Installing SciPy and NumPy using pip

I am assuming Linux experience in my answer; I found that there are three prerequisites to getting pip install scipy to proceed nicely.

Go here: Installing SciPY

Follow the instructions to download, build and export the env variable for BLAS and then LAPACK. Be careful to not just blindly cut'n'paste the shell commands - there will be a few lines you need to select depending on your architecture, etc., and you'll need to fix/add the correct directories that it incorrectly assumes as well.

The third thing you may need is to yum install numpy-f2py or the equivalent.

Oh, yes and lastly, you may need to yum install gcc-gfortran as the libraries above are Fortran source.

Directing print output to a .txt file

One can directly store the returned output of a function in a file.

print(output statement, file=open("filename", "a"))

Make A List Item Clickable (HTML/CSS)

Here is a working solution - http://jsfiddle.net/STTaf/

I used simple jQuery:

$(function() {
    $('li').css('cursor', 'pointer')

    .click(function() {
        window.location = $('a', this).attr('href');
        return false;
    });
});

Spring MVC 4: "application/json" Content Type is not being set correctly

First thing to understand is that the RequestMapping#produces() element in

@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")

serves only to restrict the mapping for your request handlers. It does nothing else.

Then, given that your method has a return type of String and is annotated with @ResponseBody, the return value will be handled by StringHttpMessageConverter which sets the Content-type header to text/plain. If you want to return a JSON string yourself and set the header to application/json, use a return type of ResponseEntity (get rid of @ResponseBody) and add appropriate headers to it.

@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> bar() {
    final HttpHeaders httpHeaders= new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>("{\"test\": \"jsonResponseExample\"}", httpHeaders, HttpStatus.OK);
}

Note that you should probably have

<mvc:annotation-driven /> 

in your servlet context configuration to set up your MVC configuration with the most suitable defaults.

Laravel Eloquent "WHERE NOT IN"

The dynamic way of implement whereNotIn:

 $users = User::where('status',0)->get();
    foreach ($users as $user) {
                $data[] = $user->id;
            }
    $available = User::orderBy('name', 'DEC')->whereNotIn('id', $data)->get();

Create an Oracle function that returns a table

To return the whole table at once you could change the SELECT to:

SELECT  ...
BULK COLLECT INTO T
FROM    ...

This is only advisable for results that aren't excessively large, since they all have to be accumulated in memory before being returned; otherwise consider the pipelined function as suggested by Charles, or returning a REF CURSOR.

How to add hyperlink in JLabel?

You might try using a JEditorPane instead of a JLabel. This understands basic HTML and will send a HyperlinkEvent event to the HyperlinkListener you register with the JEditPane.

Calculating distance between two geographic locations

There is only one user Location, so you can iterate List of nearby places can call the distanceTo() function to get the distance, you can store in an array if you like.

From what I understand, distanceBetween() is for far away places, it's output is a WGS84 ellipsoid.

Django ManyToMany filter()

another way to do this is by going through the intermediate table. I'd express this within the Django ORM like this:

UserZone = User.zones.through

# for a single zone
users_in_zone = User.objects.filter(
  id__in=UserZone.objects.filter(zone=zone1).values('user'))

# for multiple zones
users_in_zones = User.objects.filter(
  id__in=UserZone.objects.filter(zone__in=[zone1, zone2, zone3]).values('user'))

it would be nice if it didn't need the .values('user') specified, but Django (version 3.0.7) seems to need it.

the above code will end up generating SQL that looks something like:

SELECT * FROM users WHERE id IN (SELECT user_id FROM userzones WHERE zone_id IN (1,2,3))

which is nice because it doesn't have any intermediate joins that could cause duplicate users to be returned

Call of overloaded function is ambiguous

replace p.setval(0); with the following.

const unsigned int param = 0;
p.setval(param);

That way it knows for sure which type the constant 0 is.

Find closing HTML tag in Sublime Text

None of the above worked on Sublime Text 3 on Windows 10, Ctrl + Shift + ' with the Emmet Sublime Text 3 plugin works great and was the only working solution for me. Ctrl + Shift + T re-opens the last closed item and to my knowledge of Sublime, has done so since early builds of ST3 or late builds of ST2.

How to close existing connections to a DB

Found it here: http://awesomesql.wordpress.com/2010/02/08/script-to-drop-all-connections-to-a-database/

DECLARE @dbname NVARCHAR(128)
SET @dbname = 'DB name here'
 -- db to drop connections 
DECLARE @processid INT 
SELECT  @processid = MIN(spid)
FROM    master.dbo.sysprocesses
WHERE   dbid = DB_ID(@dbname) 
WHILE @processid IS NOT NULL 
    BEGIN 
        EXEC ('KILL ' + @processid) 
        SELECT  @processid = MIN(spid)
        FROM    master.dbo.sysprocesses
        WHERE   dbid = DB_ID(@dbname) 
    END

php date validation

Instead of the bulky DateTime object .. just use the core date() function

function isValidDate($date, $format= 'Y-m-d'){
    return $date == date($format, strtotime($date));
}

Perl - If string contains text?

If you just need to search for one string within another, use the index function (or rindex if you want to start scanning from the end of the string):

if (index($string, $substring) != -1) {
   print "'$string' contains '$substring'\n";
}

To search a string for a pattern match, use the match operator m//:

if ($string =~ m/pattern/) {
    print "'$string' matches the pattern\n";       
}

What do we mean by Byte array?

From wikipedia:

In computer science, an array data structure or simply array is a data structure consisting of a collection of elements (values or variables), each identified by one or more integer indices, stored so that the address of each element can be computed from its index tuple by a simple mathematical formula.

So when you say byte array, you're referring to an array of some defined length (e.g. number of elements) that contains a collection of byte (8 bits) sized elements.

In C# a byte array could look like:

byte[] bytes = { 3, 10, 8, 25 };

The sample above defines an array of 4 elements, where each element can be up to a Byte in length.

Directory Chooser in HTML page

If you do not have too many folders then I suggest you use if statements to choose an upload folder depending on the user input details. E.g.

String user= request.getParameter("username");
if (user=="Alfred"){
//Path A;
}
if (user=="other"){
//Path B;
}

Fetching data from MySQL database to html dropdown list

To do this you want to loop through each row of your query results and use this info for each of your drop down's options. You should be able to adjust the code below fairly easily to meet your needs.

// Assume $db is a PDO object
$query = $db->query("YOUR QUERY HERE"); // Run your query

echo '<select name="DROP DOWN NAME">'; // Open your drop down box

// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
   echo '<option value="'.$row['something'].'">'.$row['something'].'</option>';
}

echo '</select>';// Close your drop down box

Resolve conflicts using remote changes when pulling from Git remote

You can either use the answer from the duplicate link pointed by nvm.

Or you can resolve conflicts by using their changes (but some of your changes might be kept if they don't conflict with remote version):

git pull -s recursive -X theirs

Using Javascript in CSS

Not in any conventional sense of the phrase "inside CSS."

What is an .axd file?

from Google

An .axd file is a HTTP Handler file. There are two types of .axd files.

  1. ScriptResource.axd
  2. WebResource.axd

These are files which are generated at runtime whenever you use ScriptManager in your Web app. This is being generated only once when you deploy it on the server.

Simply put the ScriptResource.AXD contains all of the clientside javascript routines for Ajax. Just because you include a scriptmanager that loads a script file it will never appear as a ScriptResource.AXD - instead it will be merely passed as the .js file you send if you reference a external script file. If you embed it in code then it may merely appear as part of the html as a tag and code but depending if you code according to how the ToolKit handles it - may or may not appear as as a ScriptResource.axd. ScriptResource.axd is only introduced with AJAX and you will never see it elsewhere

And ofcourse it is necessary

List and kill at jobs on UNIX

You should be able to find your command with a ps variant like:

ps -ef
ps -fubob # if your job's user ID is bob.

Then, once located, it should be a simple matter to use kill to kill the process (permissions permitting).

If you're talking about getting rid of jobs in the at queue (that aren't running yet), you can use atq to list them and atrm to get rid of them.

How to transfer data from JSP to servlet when submitting HTML form

first up on create your jsp file : and write the text field which you want
for ex:

after that create your servlet class:

public class test{

protected void doGet(paramter , paramter){

String name  = request.getparameter("name");
 }

}

EditText onClickListener in Android

Here is what worked for me

Set editable to false

<EditText android:id="@+id/dob"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Date of Birth"
android:inputType="none"
android:editable="false"

/>

Then add an event listener for OnFocusChange

private  View.OnFocusChangeListener onFocusChangeDOB= new View.OnFocusChangeListener() {

@Override
 public void onFocusChange(View v, boolean hasFocus) {
   if (hasFocus){
     showDialog(DATE_DIALOG_ID);
   }
 }
};

Change Twitter Bootstrap Tooltip content on click

Bootstrap 4

$('#topic_1').tooltip('dispose').tooltip({title: 'Goodbye'}).tooltip('show')

https://getbootstrap.com/docs/4.1/components/tooltips/#tooltipdispose

_x000D_
_x000D_
$('#topic_1').tooltip({title: 'Hello'}).tooltip('show');
setTimeout( function() {
  $('#topic_1').tooltip('dispose').tooltip({title: 'Goodbye'}).tooltip('show');
}, 5000);
_x000D_
#topic_1 {
  border: 1px solid red;
  margin: 50px;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>

<div id="topic_1">Topic 1</div>
_x000D_
_x000D_
_x000D_

How can I produce an effect similar to the iOS 7 blur view?

Apple released code at WWDC as a category on UIImage that includes this functionality, if you have a developer account you can grab the UIImage category (and the rest of the sample code) by going to this link: https://developer.apple.com/wwdc/schedule/ and browsing for section 226 and clicking on details. I haven't played around with it yet but I think the effect will be a lot slower on iOS 6, there are some enhancements to iOS 7 that make grabbing the initial screen shot that is used as input to the blur a lot faster.

Direct link: https://developer.apple.com/downloads/download.action?path=wwdc_2013/wwdc_2013_sample_code/ios_uiimageeffects.zip

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

GetDateTimeFormats can parse DateTime to different formats. Example to "yyyy-MM-dd" format.

SomeDate.Value.GetDateTimeFormats()[5]

GetDateTimeFormats

Oracle: how to UPSERT (update or insert into a table?)

An alternative to MERGE (the "old fashioned way"):

begin
   insert into t (mykey, mystuff) 
      values ('X', 123);
exception
   when dup_val_on_index then
      update t 
      set    mystuff = 123 
      where  mykey = 'X';
end;   

How to check if running in Cygwin, Mac or Linux?

Windows Subsystem for Linux did not exist when this question was asked. It gave these results in my test:

uname -s -> Linux
uname -o -> GNU/Linux
uname -r -> 4.4.0-17763-Microsoft

This means that you need uname -r to distinguish it from native Linux.

Ruby on Rails form_for select field with class

You can see in here: http://apidock.com/rails/ActionView/Helpers/FormBuilder/select

Or here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select

Select tag has maximun 4 agrument, and last agrument is html option, it mean you can put class, require, selection option in here.

= f.select :sms_category_id, @sms_category_collect, {}, {class: 'form-control', required: true, selected: @set}

jQuery - Call ajax every 10 seconds

Are you going to want to do a setInterval()?

setInterval(function(){get_fb();}, 10000);

Or:

setInterval(get_fb, 10000);

Or, if you want it to run only after successfully completing the call, you can set it up in your .ajax().success() callback:

function get_fb(){
    var feedback = $.ajax({
        type: "POST",
        url: "feedback.php",
        async: false
    }).success(function(){
        setTimeout(function(){get_fb();}, 10000);
    }).responseText;

    $('div.feedback-box').html(feedback);
}

Or use .ajax().complete() if you want it to run regardless of result:

function get_fb(){
    var feedback = $.ajax({
        type: "POST",
        url: "feedback.php",
        async: false
    }).complete(function(){
        setTimeout(function(){get_fb();}, 10000);
    }).responseText;

    $('div.feedback-box').html(feedback);
}

Here is a demonstration of the two. Note, the success works only once because jsfiddle is returning a 404 error on the ajax call.

http://jsfiddle.net/YXMPn/

How can I get the height and width of an uiimage?

UIImage *img = [UIImage imageNamed:@"logo.png"];

CGFloat width = img.size.width;
CGFloat height = img.size.height;

SSIS Excel Connection Manager failed to Connect to the Source

It seems like the 32-bit version of Excel was not installed. Remember that SSDT is a 32-bit IDE. Therefore, when data is access from SSDT the 32-bit data providers are used. When running the package outside of SSDT it runs in 64-bit mode (not always, but mostly) and uses the 64-bit data providers.

Always keep in mind that if you want to run your package in 64-bit (which you should aim for) you will need both the 32-bit data providers (for development in SSDT) as well as the 64-bit data providers (for executing the package in production).

I downloaded the 32-bit access drivers from:

After installation, I could see the worksheets


Source:

500 Internal Server Error for php file not for html

500 Internal Server Error is shown if your php code has fatal errors but error displaying is switched off. You may try this to see the error itself instead of 500 error page:

In your php file:

ini_set('display_errors', 1);

In .htaccess file:

php_flag display_errors 1

How to properly upgrade node using nvm

Bash alias for updating current active version:

alias nodeupdate='nvm install $(nvm current | sed -rn "s/v([[:digit:]]+).*/\1/p") --reinstall-packages-from=$(nvm current)'

The part sed -rn "s/v([[:digit:]]+).*/\1/p" transforms output from nvm current so that only a major version of node is returned, i.e.: v13.5.0 -> 13.

How to get htaccess to work on MAMP

  1. In httpd.conf on /Applications/MAMP/conf/apache, find:

    <Directory />
        Options Indexes FollowSymLinks
        AllowOverride None
    </Directory>
    
  2. Replace None with All.

  3. Restart MAMP servers.

Use Mockito to mock some methods but not others

What you want is org.mockito.Mockito.CALLS_REAL_METHODS according to the docs:

/**
 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations.
 * <p>
 * This implementation can be helpful when working with legacy code.
 * When this implementation is used, unstubbed methods will delegate to the real implementation.
 * This is a way to create a partial mock object that calls real methods by default.
 * <p>
 * As usual you are going to read <b>the partial mock warning</b>:
 * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
 * How does partial mock fit into this paradigm? Well, it just doesn't... 
 * Partial mock usually means that the complexity has been moved to a different method on the same object.
 * In most cases, this is not the way you want to design your application.
 * <p>
 * However, there are rare cases when partial mocks come handy: 
 * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
 * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
 * <p>
 * Example:
 * <pre class="code"><code class="java">
 * Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
 *
 * // this calls the real implementation of Foo.getSomething()
 * value = mock.getSomething();
 *
 * when(mock.getSomething()).thenReturn(fakeValue);
 *
 * // now fakeValue is returned
 * value = mock.getSomething();
 * </code></pre>
 */

Thus your code should look like:

import org.junit.Test;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

public class StockTest {

    public class Stock {
        private final double price;
        private final int quantity;

        Stock(double price, int quantity) {
            this.price = price;
            this.quantity = quantity;
        }

        public double getPrice() {
            return price;
        }

        public int getQuantity() {
            return quantity;
        }

        public double getValue() {
            return getPrice() * getQuantity();
        }
    }

    @Test
    public void getValueTest() {
        Stock stock = mock(Stock.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
        when(stock.getPrice()).thenReturn(100.00);
        when(stock.getQuantity()).thenReturn(200);
        double value = stock.getValue();

        assertEquals("Stock value not correct", 100.00 * 200, value, .00001);
    }
}

The call to Stock stock = mock(Stock.class); calls org.mockito.Mockito.mock(Class<T>) which looks like this:

 public static <T> T mock(Class<T> classToMock) {
    return mock(classToMock, withSettings().defaultAnswer(RETURNS_DEFAULTS));
}

The docs of the value RETURNS_DEFAULTS tell:

/**
 * The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
 * Typically it just returns some empty value. 
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations. 
 * <p>
 * This implementation first tries the global configuration. 
 * If there is no global configuration then it uses {@link ReturnsEmptyValues} (returns zeros, empty collections, nulls, etc.)
 */

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

Use Rafael's solution: http://social.msdn.microsoft.com/Forums/en/sqlsetupandupgrade/thread/dddf0349-557b-48c7-bf82-6bd1adb5c694..

Added data from link to avoid link rot..

put this at any Console application:

string.Format("{0,3}", CultureInfo.InstalledUICulture.Parent.LCID.ToString("X")).Replace(" ", "0");

Watch the result. At mine it was "016".

Then you go to the registry at this key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib

and create another one with the name you got from the string.Format result.

In my case:

"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\016"

and copy the info that is on any other key in this Perflib to this key you just created. Run the instalation again.

Just run the script and get your 3 digit code. Then follow his simple and quick steps, and you're ready to go!

Cheers

How can I list all tags for a Docker image on a remote registry?

As of Docker Registry V2, a simple GET suffice:

GET /v2/<name>/tags/list

See docs for more.

How can I drop a "not null" constraint in Oracle when I don't know the name of the constraint?

I was facing the same problem trying to get around a custom check constraint that I needed to updated to allow different values. Problem is that ALL_CONSTRAINTS does't have a way to tell which column the constraint(s) are applied to. The way I managed to do it is by querying ALL_CONS_COLUMNS instead, then dropping each of the constraints by their name and recreate it.

select constraint_name from all_cons_columns where table_name = [TABLE_NAME] and column_name = [COLUMN_NAME];

How to generate a QR Code for an Android application?

I used zxing-1.3 jar and I had to make some changes implementing code from other answers, so I will leave my solution for others. I did the following:

1) find zxing-1.3.jar, download it and add in properties (add external jar).

2) in my activity layout add ImageView and name it (in my example it was tnsd_iv_qr).

3) include code in my activity to create qr image (in this example I was creating QR for bitcoin payments):

    QRCodeWriter writer = new QRCodeWriter();
    ImageView tnsd_iv_qr = (ImageView)findViewById(R.id.tnsd_iv_qr);
    try {
        ByteMatrix bitMatrix = writer.encode("bitcoin:"+btc_acc_adress+"?amount="+amountBTC, BarcodeFormat.QR_CODE, 512, 512);
        int width = 512;
        int height = 512;
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                if (bitMatrix.get(x, y)==0)
                    bmp.setPixel(x, y, Color.BLACK);
                else
                    bmp.setPixel(x, y, Color.WHITE);
            }
        }
        tnsd_iv_qr.setImageBitmap(bmp);
    } catch (WriterException e) {
        //Log.e("QR ERROR", ""+e);

    }

If someone is wondering, variable "btc_acc_adress" is a String (with BTC adress), amountBTC is a double, with, of course, transaction amount.

Javascript: How to remove the last character from a div or a string?

$('#mainn').text(function (_,txt) {
    return txt.slice(0, -1);
});

demo --> http://jsfiddle.net/d72ML/8/

Find all files with a filename beginning with a specified string?

ls | grep "^abc"  

will give you all files beginning (which is what the OP specifically required) with the substringabc.
It operates only on the current directory whereas find operates recursively into sub folders.

To use find for only files starting with your string try

find . -name 'abc'*

Best way to add Gradle support to IntelliJ Project

Add:

build.gradle 

in your root project folder, and use plugin for example:

apply plugin: 'idea'
//and standard one
apply plugin: 'java'

and with this fire from command line:

gradle cleanIdea 

and after that:

gradle idea

After that everything should work

How do you determine what technology a website is built on?

Examining the cookies the site gives can reveal the underlying framework. CodeIgniter, for example defaults to a telltale ci_sessions cookie. Sites using PEAR Auth will do something similar.

Send values from one form to another form

How about using a public Event

I would do it like this.

public class Form2
{
   public event Action<string> SomethingCompleted;

   private void Submit_Click(object sender, EventArgs e)
   {
       SomethingCompleted?.Invoke(txtData.Text);
       this.Close();
   }
}

and call it from Form1 like this.

private void btnOpenForm2_Click(object sender, EventArgs e)
{
    using (var frm = new Form2())
    {
        frm.SomethingCompleted += text => {
            this.txtData.Text = text;
        };

        frm.ShowDialog();
    }
}

Then, Form1 could get a text from Form2 when Form2 is closed

Thank you.

Maven build debug in Eclipse

Easiest way I find is to:

  1. Right click project

  2. Debug as -> Maven build ...

  3. In the goals field put -Dmaven.surefire.debug test

  4. In the parameters put a new parameter called forkCount with a value of 0 (previously was forkMode=never but it is deprecated and doesn't work anymore)

Set your breakpoints down and run this configuration and it should hit the breakpoint.

Android button with icon and text

For anyone looking to do this dynamically then setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) on the buttons object will assist.

Sample

Button search = (Button) findViewById(R.id.yoursearchbutton);
search.setCompoundDrawables('your_drawable',null,null,null);

Update TextView Every Second

You can also use TimerTask for that.

Here is an method

private void setTimerTask() {
    long delay = 3000;
    long periodToRepeat = 60 * 1000; /* 1 mint */
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                 //   do your stuff here.
                }
            });
        }
    }, 3000, 3000);
}

C/C++ maximum stack size of program

Yes, there is a possibility of stack overflow. The C and C++ standard do not dictate things like stack depth, those are generally an environmental issue.

Most decent development environments and/or operating systems will let you tailor the stack size of a process, either at link or load time.

You should specify which OS and development environment you're using for more targeted assistance.

For example, under Ubuntu Karmic Koala, the default for gcc is 2M reserved and 4K committed but this can be changed when you link the program. Use the --stack option of ld to do that.

How to escape comma and double quote at same time for CSV file?

Thanks to both Tony and Paul for the quick feedback, its very helpful. I actually figure out a solution through POJO. Here it is:

if (cell_value.indexOf("\"") != -1 || cell_value.indexOf(",") != -1) {
    cell_value = cell_value.replaceAll("\"", "\"\"");
    row.append("\"");
    row.append(cell_value);
    row.append("\"");
} else {
    row.append(cell_value);
}

in short if there is special character like comma or double quote within the string in side the cell, then first escape the double quote("\"") by adding additional double quote (like "\"\""), then put the whole thing into a double quote (like "\""+theWholeThing+"\"" )

How can I sort a std::map first by value, then by key?

As explained in Nawaz's answer, you cannot sort your map by itself as you need it, because std::map sorts its elements based on the keys only. So, you need a different container, but if you have to stick to your map, then you can still copy its content (temporarily) into another data structure.

I think, the best solution is to use a std::set storing flipped key-value pairs as presented in ks1322's answer. The std::set is sorted by default and the order of the pairs is exactly as you need it:

3) If lhs.first<rhs.first, returns true. Otherwise, if rhs.first<lhs.first, returns false. Otherwise, if lhs.second<rhs.second, returns true. Otherwise, returns false.

This way you don't need an additional sorting step and the resulting code is quite short:

std::map<std::string, int> m;  // Your original map.
m["realistically"] = 1;
m["really"]        = 8;
m["reason"]        = 4;
m["reasonable"]    = 3;
m["reasonably"]    = 1;
m["reassemble"]    = 1;
m["reassembled"]   = 1;
m["recognize"]     = 2;
m["record"]        = 92;
m["records"]       = 48;
m["recs"]          = 7;

std::set<std::pair<int, std::string>> s;  // The new (temporary) container.

for (auto const &kv : m)
    s.emplace(kv.second, kv.first);  // Flip the pairs.

for (auto const &vk : s)
    std::cout << std::setw(3) << vk.first << std::setw(15) << vk.second << std::endl;

Output:

  1  realistically
  1     reasonably
  1     reassemble
  1    reassembled
  2      recognize
  3     reasonable
  4         reason
  7           recs
  8         really
 48        records
 92         record

Code on Ideone

Note: Since C++17 you can use range-based for loops together with structured bindings for iterating over a map. As a result, the code for copying your map becomes even shorter and more readable:

for (auto const &[k, v] : m)
    s.emplace(v, k);  // Flip the pairs.

pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message

Use the valgrind option --track-origins=yes to have it track the origin of uninitialized values. This will make it slower and take more memory, but can be very helpful if you need to track down the origin of an uninitialized value.

Update: Regarding the point at which the uninitialized value is reported, the valgrind manual states:

It is important to understand that your program can copy around junk (uninitialised) data as much as it likes. Memcheck observes this and keeps track of the data, but does not complain. A complaint is issued only when your program attempts to make use of uninitialised data in a way that might affect your program's externally-visible behaviour.

From the Valgrind FAQ:

As for eager reporting of copies of uninitialised memory values, this has been suggested multiple times. Unfortunately, almost all programs legitimately copy uninitialised memory values around (because compilers pad structs to preserve alignment) and eager checking leads to hundreds of false positives. Therefore Memcheck does not support eager checking at this time.

How can I access global variable inside class in Python

class flag:
    ## Store pseudo-global variables here

    keys=False

    sword=True

    torch=False


## test the flag class

print('______________________')

print(flag.keys)
print(flag.sword)
print (flag.torch)


## now change the variables

flag.keys=True
flag.sword= not flag.sword
flag.torch=True

print('______________________')

print(flag.keys)
print(flag.sword)
print (flag.torch)

How to check whether a given string is valid JSON in Java

A wild idea, try parsing it and catch the exception:

import org.json.*;

public boolean isJSONValid(String test) {
    try {
        new JSONObject(test);
    } catch (JSONException ex) {
        // edited, to include @Arthur's comment
        // e.g. in case JSONArray is valid as well...
        try {
            new JSONArray(test);
        } catch (JSONException ex1) {
            return false;
        }
    }
    return true;
}

This code uses org.json JSON API implementation that is available on github, in maven and partially on Android.

The calling thread must be STA, because many UI components require this

Try to invoke your code from the dispatcher:

Application.Current.Dispatcher.Invoke((Action)delegate{
      // your code
});

TypeError: 'function' object is not subscriptable - Python

It is so simple, you have 2 objects with the same name and when you say: bank_holiday[month] python thinks you wanna run your function and got ERROR.

Just rename your array to bank_holidays <--- add a 's' at the end! like this:

bank_holidays= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   if month <1 or month > 12:
       print("Error: Out of range")
       return
   print(bank_holidays[month-1],"holiday(s) in this month ")

bank_holiday(int(input("Which month would you like to check out: ")))

"query function not defined for Select2 undefined error"

This issue boiled down to how I was building my select2 select box. In one javascript file I had...

$(function(){
  $(".select2").select2();
});

And in another js file an override...

$(function(){
    var employerStateSelector = 
                $("#registration_employer_state").select2("destroy");
    employerStateSelector.select2({
    placeholder: 'Select a State...'
    });
});

Moving the second override into a window load event resolved the issue.

$( window ).load(function() {
  var employerStateSelector = 
              $("#registration_employer_state").select2("destroy");
  employerStateSelector.select2({
    placeholder: 'Select a State...'
  });
});

This issue blossomed inside a Rails application

How to set a:link height/width with css?

Your problem is probably that a elements are display: inline by nature. You can't set the width and height of inline elements.

You would have to set display: block on the a, but that will bring other problems because the links start behaving like block elements. The most common cure to that is giving them float: left so they line up side by side anyway.

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

IllegalStateException is encountered if you commit any fragment transaction after the activity has lost its state- Activity is not in foreground. This is commonly encountered when you try to commit any fragment in AsyncTask or after a network request.

To avoid this crash you just need to delay any fragment transaction untill the state of activity is restored. Following is how it is done

Declare two private boolean variables

public class MainActivity extends AppCompatActivity {

    //Boolean variable to mark if the transaction is safe
    private boolean isTransactionSafe;

    //Boolean variable to mark if there is any transaction pending
    private boolean isTransactionPending;

Now in onPostResume() and onPause we set and unset our boolean variable isTransactionSafe. Idea is to mark trasnsaction safe only when the activity is in foreground so there is no chance of stateloss.

/*
onPostResume is called only when the activity's state is completely restored. In this we will
set our boolean variable to true. Indicating that transaction is safe now
 */
public void onPostResume(){
    super.onPostResume();
    isTransactionSafe=true;
}
/*
onPause is called just before the activity moves to background and also before onSaveInstanceState. In this
we will mark the transaction as unsafe
 */

public void onPause(){
    super.onPause();
    isTransactionSafe=false;

}

private void commitFragment(){
    if(isTransactionSafe) {
        MyFragment myFragment = new MyFragment();
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.frame, myFragment);
        fragmentTransaction.commit();
    }
}

What we have done so far will save from IllegalStateException but our transactions will be lost if they are done after the activity moves to background, kind of like commitAllowStateloss(). To help with that we have isTransactionPending boolean variable

public void onPostResume(){
   super.onPostResume();
   isTransactionSafe=true;
/* Here after the activity is restored we check if there is any transaction pending from
the last restoration
*/
   if (isTransactionPending) {
      commitFragment();
   }
}


private void commitFragment(){

 if(isTransactionSafe) {
     MyFragment myFragment = new MyFragment();
     FragmentManager fragmentManager = getFragmentManager();
     FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
     fragmentTransaction.add(R.id.frame, myFragment);
     fragmentTransaction.commit();
     isTransactionPending=false;
 }else {
     /*
     If any transaction is not done because the activity is in background. We set the
     isTransactionPending variable to true so that we can pick this up when we come back to
foreground
     */
     isTransactionPending=true;
 }
}

This article explains quite in detail of why this exception is encountered and compares various methods to resolve it . Highly recommended

java: use StringBuilder to insert at the beginning

This thread is quite old, but you could also think about a recursive solution passing the StringBuilder to fill. This allows to prevent any reverse processing etc. Just need to design your iteration with a recursion and carefully decide for an exit condition.

public class Test {

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        doRecursive(sb, 100, 0);
        System.out.println(sb.toString());
    }

    public static void doRecursive(StringBuilder sb, int limit, int index) {
        if (index < limit) {
            doRecursive(sb, limit, index + 1);
            sb.append(Integer.toString(index));
        }
    }
}

Adding Multiple Values in ArrayList at a single index

ArrayList<ArrayList> arrObjList = new ArrayList<ArrayList>();
ArrayList<Double> arrObjInner1= new ArrayList<Double>();
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);

arrObjList.add(arrObjInner1);

You can have as many ArrayList inside the arrObjList. I hope this will help you.

"And" and "Or" troubles within an IF statement

This is not an answer, but too long for a comment.

In reply to JP's answers / comments, I have run the following test to compare the performance of the 2 methods. The Profiler object is a custom class - but in summary, it uses a kernel32 function which is fairly accurate (Private Declare Sub GetLocalTime Lib "kernel32" (lpSystemTime As SYSTEMTIME)).

Sub test()

  Dim origNum As String
  Dim creditOrDebit As String
  Dim b As Boolean
  Dim p As Profiler
  Dim i As Long

  Set p = New_Profiler

  origNum = "30062600006"
  creditOrDebit = "D"

  p.startTimer ("nested_ifs")

  For i = 1 To 1000000

    If creditOrDebit = "D" Then
      If origNum = "006260006" Then
        b = True
      ElseIf origNum = "30062600006" Then
        b = True
      End If
    End If

  Next i

  p.stopTimer ("nested_ifs")
  p.startTimer ("or_and")

  For i = 1 To 1000000

    If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
      b = True
    End If

  Next i

  p.stopTimer ("or_and")

  p.printReport

End Sub

The results of 5 runs (in ms for 1m loops):

20-Jun-2012 19:28:25
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125

20-Jun-2012 19:28:26
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125

20-Jun-2012 19:28:27
nested_ifs (x1): 140 - Last Run: 140 - Average Run: 140
or_and (x1): 125 - Last Run: 125 - Average Run: 125

20-Jun-2012 19:28:28
nested_ifs (x1): 140 - Last Run: 140 - Average Run: 140
or_and (x1): 141 - Last Run: 141 - Average Run: 141

20-Jun-2012 19:28:29
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125

Note

If creditOrDebit is not "D", JP's code runs faster (around 60ms vs. 125ms for the or/and code).

store and retrieve a class object in shared preference

I had the same problem, here's my solution:

I have class MyClass and ArrayList< MyClass > that I want to save to Shared Preferences. At first I've added a method to MyClass that converts it to JSON object:

public JSONObject getJSONObject() {
    JSONObject obj = new JSONObject();
    try {
        obj.put("id", this.id);
        obj.put("name", this.name);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return obj;
}

Then here's the method for saving object "ArrayList< MyClass > items":

SharedPreferences mPrefs = context.getSharedPreferences("some_name", 0);
    SharedPreferences.Editor editor = mPrefs.edit();

    Set<String> set= new HashSet<String>();
    for (int i = 0; i < items.size(); i++) {
        set.add(items.get(i).getJSONObject().toString());
    }

    editor.putStringSet("some_name", set);
    editor.commit();

And here's the method for retrieving the object:

public static ArrayList<MyClass> loadFromStorage() {
    SharedPreferences mPrefs = context.getSharedPreferences("some_name", 0);

    ArrayList<MyClass> items = new ArrayList<MyClass>();

    Set<String> set = mPrefs.getStringSet("some_name", null);
    if (set != null) {
        for (String s : set) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                Long id = jsonObject.getLong("id"));
                String name = jsonObject.getString("name");
                MyClass myclass = new MyClass(id, name);

                items.add(myclass);

            } catch (JSONException e) {
                e.printStackTrace();
         }
    }
    return items;
}

Note that StringSet in Shared Preferences is available since API 11.

Combining COUNT IF AND VLOOK UP EXCEL

You can combine this all into one formula, but you need to use a regular IF first to find out if the VLOOKUP came back with something, then use your COUNTIF if it did.

=IF(ISERROR(VLOOKUP(B1,Sheet2!A1:A9,1,FALSE)),"Not there",COUNTIF(Sheet2!A1:A9,B1))

In this case, Sheet2-A1:A9 is the range I was searching, and Sheet1-B1 had the value I was looking for ("To retire" in your case).

What is "runtime"?

If my understanding from reading the above answers is correct, Runtime is basically 'background processes' such as garbage collection, memory-allocation, basically any processes that are invoked indirectly, by the libraries / frameworks that your code is written in, and specifically those processes that occur after compilation, while the application is running.

Spring Data and Native Query with pagination

For me below worked in MS SQL

 @Query(value="SELECT * FROM ABC r where r.type in :type  ORDER BY RAND() \n-- #pageable\n ",nativeQuery = true)
List<ABC> findByBinUseFAndRgtnType(@Param("type") List<Byte>type,Pageable pageable);

How can I find matching values in two arrays?

With some ES6:

let sortedArray = [];
firstArr.map((first) => {
  sortedArray[defaultArray.findIndex(def => def === first)] = first;
});
sortedArray = sortedArray.filter(v => v);

This snippet also sorts the firstArr based on the order of the defaultArray

like:

let firstArr = ['apple', 'kiwi', 'banana'];
let defaultArray = ['kiwi', 'apple', 'pear'];
...
console.log(sortedArray);
// ['kiwi', 'apple'];

Different class for the last element in ng-repeat

The answer given by Fabian Perez worked for me, with a little change

Edited html is here:

<div ng-repeat="file in files" ng-class="!$last ? 'other' : 'class-for-last'"> {{file.name}} </div>

Get generic type of java.util.List

For finding generic type of one field:

((Class)((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0]).getSimpleName()

C#: How do you edit items and subitems in a listview?

If you're looking for "in-place" editing of a ListView's contents (specifically the subitems of a ListView in details view mode), you'll need to implement this yourself, or use a third-party control.

By default, the best you can achieve with a "standard" ListView is to set it's LabelEdit property to true to allow the user to edit the text of the first column of the ListView (assuming you want to allow a free-format text edit).

Some examples (including full source-code) of customized ListView's that allow "in-place" editing of sub-items are:

C# Editable ListView
In-place editing of ListView subitems

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

I'm not sure, but I think the string stores its info as an array of Chars, which is inefficient with bytes. Specifically, the definition of a Char is "Represents a Unicode character".

take this example sample:

String str = "asdf éß";
String str2 = "asdf gh";
EncodingInfo[] info =  Encoding.GetEncodings();
foreach (EncodingInfo enc in info)
{
    System.Console.WriteLine(enc.Name + " - " 
      + enc.GetEncoding().GetByteCount(str)
      + enc.GetEncoding().GetByteCount(str2));
}

Take note that the Unicode answer is 14 bytes in both instances, whereas the UTF-8 answer is only 9 bytes for the first, and only 7 for the second.

So if you just want the bytes used by the string, simply use Encoding.Unicode, but it will be inefficient with storage space.