Programs & Examples On #Docking

A user interface design in which panels are arranged inside a container. Each docked panel is attached to another panel or a side of the container.

How to execute a command prompt command from python

Taking some inspiration from Daren Thomas's answer (and edit), try this:

proc = subprocess.Popen('dir C:\\', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = proc.communicate()

out will now contain the text output.

They key nugget here is that the subprocess module already provides you shell integration with shell=True, so you don't need to call cmd.exe directly.

As a reminder, if you're in Python 3, this is going to be bytes, so you may want to do out.decode() to convert to a string.

\r\n, \r and \n what is the difference between them?

They are normal symbols as 'a' or '?' or any other. Just (invisible) entries in a string. \r moves cursor to the beginning of the line. \n goes one line down.

As for your replacement, you haven't specified what language you're using, so here's the sketch:

someString.replace("\r\n", "\n").replace("\r", "\n")

Good Free Alternative To MS Access

for sqlite, check out the firefox extension. It offers a serviceable GUI.

multiple conditions for filter in spark data frames

Instead of:

df2 = df1.filter("Status=2" || "Status =3")

Try:

df2 = df1.filter($"Status" === 2 || $"Status" === 3)

How to display custom view in ActionBar?

There is an example in the launcher app of Android (that I've made a library out of it, here), inside the class that handles wallpapers-picking ("WallpaperPickerActivity") .

The example shows that you need to set a customized theme for this to work. Sadly, this worked for me only using the normal framework, and not the one of the support library.

Here're the themes:

styles.xml

 <style name="Theme.WallpaperPicker" parent="Theme.WallpaperCropper">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
    <item name="android:windowShowWallpaper">true</item>
  </style>

  <style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
    <item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowActionBarOverlay">true</item>
  </style>

  <style name="WallpaperCropperActionBar" parent="@android:style/Widget.DeviceDefault.ActionBar">
    <item name="android:displayOptions">showCustom</item>
    <item name="android:background">#88000000</item>
  </style>

value-v19/styles.xml

 <style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
    <item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowActionBarOverlay">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
  </style>

  <style name="Theme" parent="@android:style/Theme.DeviceDefault.Wallpaper.NoTitleBar">
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
  </style>

EDIT: there is a better way to do it, which works on the support library too. Just add this line of code instead of what I've written above:

getSupportActionBar().setDisplayShowCustomEnabled(true);

Remove ALL styling/formatting from hyperlinks

You can just use an a selector in your stylesheet to define all states of an anchor/hyperlink. For example:

a {
    color: blue;
}

Would override all link styles and make all the states the colour blue.

Install tkinter for Python

Fedora release 25 (Twenty Five)

dnf install python3-tkinter

This worked for me.

Git clone particular version of remote repository

Use git log to find the revision you want to rollback to, and take note of the commit hash. After that, you have 2 options:

  1. If you plan to commit anything after that revision, I recommend you to checkout to a new branch: git checkout -b <new_branch_name> <hash>

  2. If you don't plan to commit anything after that revision, you can simply checkout without a branch: git checkout <hash> - NOTE: This will put your repository in a 'detached HEAD' state, which means its currently not attached to any branch - then you'll have some extra work to merge new commits to an actual branch.

Example:

$ git log
commit 89915b4cc0810a9c9e67b3706a2850c58120cf75
Author: Jardel Weyrich <suppressed>
Date:   Wed Aug 18 20:15:01 2010 -0300

    Added a custom extension.

commit 4553c1466c437bdd0b4e7bb35ed238cb5b39d7e7
Author: Jardel Weyrich <suppressed>
Date:   Wed Aug 18 20:13:48 2010 -0300

    Missing constness.

$ git checkout 4553c1466c437bdd0b4e7bb35ed238cb5b39d7e7
Note: moving to '4553c1466c437bdd0b4e7bb35ed238cb5b39d7e7'
which isn't a local branch
If you want to create a new branch from this checkout, you may do so
(now or later) by using -b with the checkout command again. Example:
  git checkout -b <new_branch_name>
HEAD is now at 4553c14... Missing constness.

That way you don't lose any informations, thus you can move to a newer revision when it becomes stable.

How do I disable directory browsing?

This is not an answer, just my experience:

On my Ubuntu 12.04 apache2, didn't find Indexes in either apache2.conf or httpd.conf, luckily I found it in sites-available/default. After removing it, now it doesn't see directory listing. May have to do it for sites-available/default-ssl.

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

How to include file in a bash shell script

In my situation, in order to include color.sh from the same directory in init.sh, I had to do something as follows.

. ./color.sh

Not sure why the ./ and not color.sh directly. The content of color.sh is as follows.

RED=`tput setaf 1`
GREEN=`tput setaf 2`
BLUE=`tput setaf 4`
BOLD=`tput bold`
RESET=`tput sgr0`

Making use of File color.sh does not error but, the color do not display. I have tested this in Ubuntu 18.04 and the Bash version is:

GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)

Why does 'git commit' not save my changes?

You didn't add the changes. Either specifically add them via

git add filename1 filename2

or add all changes (from root path of the project)

git add .

or use the shorthand -a while commiting:

git commit -a -m "message".

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

check the property endorsed.dir tag in your pom.xml.
I also had this problem and I fixed by modifying the property.

Example:

<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>  

Populate unique values into a VBA array from Excel

Sub GetUniqueAndCount()

    Dim d As Object, c As Range, k, tmp As String

    Set d = CreateObject("scripting.dictionary")
    For Each c In Selection
        tmp = Trim(c.Value)
        If Len(tmp) > 0 Then d(tmp) = d(tmp) + 1
    Next c

    For Each k In d.keys
        Debug.Print k, d(k)
    Next k

End Sub

Prevent flicker on webkit-transition of webkit-transform

I had to use:

-webkit-perspective: 1000;
-webkit-backface-visibility: hidden;    

on the element, or I would still get a flickr the first time a transition occurred after page load

Subtracting 2 lists in Python

I'd have to recommend NumPy as well

Not only is it faster for doing vector math, but it also has a ton of convenience functions.

If you want something even faster for 1d vectors, try vop

It's similar to MatLab, but free and stuff. Here's an example of what you'd do

from numpy import matrix
a = matrix((2,2,2))
b = matrix((1,1,1))
ret = a - b
print ret
>> [[1 1 1]]

Boom.

HQL "is null" And "!= null" on an Oracle column

If you do want to use null values with '=' or '<>' operators you may find the

answer from @egallardo hier

very useful.

Short example for '=': The expression

WHERE t.field = :param

you refactor like this

WHERE ((:param is null and t.field is null) or t.field = :param)

Now you can set the parameter param either to some non-null value or to null:

query.setParameter("param", "Hello World"); // Works
query.setParameter("param", null);          // Works also

Regex AND operator

Example of a Boolean (AND) plus Wildcard search, which I'm using inside a javascript Autocomplete plugin:

String to match: "my word"

String to search: "I'm searching for my funny words inside this text"

You need the following regex: /^(?=.*my)(?=.*word).*$/im

Explaining:

^ assert position at start of a line

?= Positive Lookahead

.* matches any character (except newline)

() Groups

$ assert position at end of a line

i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

Test the Regex here: https://regex101.com/r/iS5jJ3/1

So, you can create a javascript function that:

  1. Replace regex reserved characters to avoid errors
  2. Split your string at spaces
  3. Encapsulate your words inside regex groups
  4. Create a regex pattern
  5. Execute the regex match

Example:

_x000D_
_x000D_
function fullTextCompare(myWords, toMatch){_x000D_
    //Replace regex reserved characters_x000D_
    myWords=myWords.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');_x000D_
    //Split your string at spaces_x000D_
    arrWords = myWords.split(" ");_x000D_
    //Encapsulate your words inside regex groups_x000D_
    arrWords = arrWords.map(function( n ) {_x000D_
        return ["(?=.*"+n+")"];_x000D_
    });_x000D_
    //Create a regex pattern_x000D_
    sRegex = new RegExp("^"+arrWords.join("")+".*$","im");_x000D_
    //Execute the regex match_x000D_
    return(toMatch.match(sRegex)===null?false:true);_x000D_
}_x000D_
_x000D_
//Using it:_x000D_
console.log(_x000D_
    fullTextCompare("my word","I'm searching for my funny words inside this text")_x000D_
);_x000D_
_x000D_
//Wildcards:_x000D_
console.log(_x000D_
    fullTextCompare("y wo","I'm searching for my funny words inside this text")_x000D_
);
_x000D_
_x000D_
_x000D_

java.lang.IllegalStateException: The specified child already has a parent

When you override OnCreateView in your RouteSearchFragment class, do you have the

if(view != null) {
    return view; 
}

code segment?

If so, removing the return statement should solve your problem.

You can keep the code and return the view if you don't want to regenerate view data, and onDestroyView() method you remove this view from its parent like so:

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (view != null) {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeAllViews();
            }
        }
    }

Directly export a query to CSV using SQL Developer

After Ctrl+End, you can do the Ctrl+A to select all in the buffer and then paste into Excel. Excel even put each Oracle column into its own column instead of squishing the whole row into one column. Nice..

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Typical Java programs compile into .jar files, which can be executed like .exe files provided the target machine has Java installed and that Java is in its PATH. From Eclipse you use the Export menu item from the File menu.

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

Redirect non-www to www in .htaccess

Add the following code in .htaccess file.

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

URLs redirect tutorial can be found from here - Redirect non-www to www & HTTP to HTTPS using .htaccess file

How do I set up the database.yml file in Rails?

At first I would use http://ruby.railstutorial.org/.

And database.yml is place where you put setup for database your application use - username, password, host - for each database. With new application you dont need to change anything - simply use default sqlite setup.

update listview dynamically with adapter

Use a ArrayAdapter backed by an ArrayList. To change the data, just update the data in the list and call adapter.notifyDataSetChanged().

Force “landscape” orientation mode

I had the same problem, it was a missing manifest.json file, if not found the browser decide with orientation is best fit, if you don't specify the file or use a wrong path.

I fixed just calling the manifest.json correctly on html headers.

My html headers:

<meta name="application-name" content="App Name">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="manifest" href="manifest.json">
<meta name="msapplication-starturl" content="/">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#">
<meta name="msapplication-TileColor" content="#">
<meta name="msapplication-config" content="browserconfig.xml">
<link rel="icon" type="image/png" sizes="192x192" href="android-chrome-192x192.png">
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png">
<link rel="mask-icon" href="safari-pinned-tab.svg" color="#ffffff">
<link rel="shortcut icon" href="favicon.ico">

And the manifest.json file content:

{
  "display": "standalone",
  "orientation": "portrait",
  "start_url": "/",
  "theme_color": "#000000",
  "background_color": "#ffffff",
  "icons": [
  {
    "src": "android-chrome-192x192.png",
    "sizes": "192x192",
    "type": "image/png"
  }
}

To generate your favicons and icons use this webtool: https://realfavicongenerator.net/

To generate your manifest file use: https://tomitm.github.io/appmanifest/

My PWA Works great, hope it helps!

"The page has expired due to inactivity" - Laravel 5.5

Some information is stored in the cookie which is related to previous versions of laravel in development. So it's conflicting with csrf generated tokens which are generated by another's versions. Just Clear the cookie and give a try.

Simple argparse example wanted: 1 argument, 3 results

The simplest answer!

P.S. the one who wrote the document of argparse is foolish

python code:

import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('--o_dct_fname',type=str)
parser.add_argument('--tp',type=str)
parser.add_argument('--new_res_set',type=int)
args = parser.parse_args()
o_dct_fname = args.o_dct_fname
tp = args.tp
new_res_set = args.new_res_set

running code

python produce_result.py --o_dct_fname o_dct --tp father_child --new_res_set 1

IE 8: background-size fix

As pointed by @RSK IE8 doesn't support background-size. To figure out a way to deal with this, I used some IE specific hacks as showed here:

//IE8.0 Hack!
@media \0screen {
    .brand {
        background-image: url("./images/logo1.png");
        margin-top: 8px;
    }

    .navbar .brand {
        margin-left: -2px;
        padding-bottom: 2px;
    }
}

//IE7.0 Hack!
*+html .brand {
    background-image: url("./images/logo1.png");
    margin-top: 8px;
}

*+html .navbar .brand {
    margin-left: -2px;
    padding-bottom: 2px;
}

Using this I was able to change my logo image to a ugly resided picture. But the final result is fine. I suggest u try something like this.

How to write a comment in a Razor view?

Note that in general, IDE's like Visual Studio will markup a comment in the context of the current language, by selecting the text you wish to turn into a comment, and then using the Ctrl+K Ctrl+C shortcut, or if you are using Resharper / Intelli-J style shortcuts, then Ctrl+/.

Server side Comments:

Razor .cshtml

Like so:

@* Comment goes here *@

.aspx
For those looking for the older .aspx view (and Asp.Net WebForms) server side comment syntax:

<%-- Comment goes here --%>

Client Side Comments

HTML Comment

<!-- Comment goes here -->

Javascript Comment

// One line Comment goes Here
/* Multiline comment
   goes here */

As OP mentions, although not displayed on the browser, client side comments will still be generated for the page / script file on the server and downloaded by the page over HTTP, which unless removed (e.g. minification), will waste I/O, and, since the comment can be viewed by the user by viewing the page source or intercepting the traffic with the browser's Dev Tools or a tool like Fiddler or Wireshark, can also pose a security risk, hence the preference to use server side comments on server generated code (like MVC views or .aspx pages).

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

You can not. You will / do break a lot of things. Like relationships. WHich rely on the number being pulled back which EF can not do in the way you set it up. THe price for breaking every pattern there is.

Generate the GUID in the C# layer, so that relationships can continue working.

Warning :-Presenting view controllers on detached view controllers is discouraged

In Swift 4.1 and Xcode 9.4.1

The solution is

DispatchQueue.main.async(execute: {
    self.present(alert, animated: true)
})

If write like this i'm getting same error

let alert = UIAlertController(title: "title", message: "message", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in
    })
alert.addAction(defaultAction)

present(alert, animated: true, completion: nil) 

I'm getting same error

Presenting view controllers on detached view controllers is discouraged <MyAppName.ViewController: 0x7fa95560Z070>.

Complete solution is

let alert = UIAlertController(title: "title", message: "message", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in
     })
alert.addAction(defaultAction)
//Made Changes here    
DispatchQueue.main.async(execute: {
    self.present(alert, animated: true)
})

postgresql duplicate key violates unique constraint

This article explains that your sequence might be out of sync and that you have to manually bring it back in sync.

An excerpt from the article in case the URL changes:

If you get this message when trying to insert data into a PostgreSQL database:

ERROR:  duplicate key violates unique constraint

That likely means that the primary key sequence in the table you're working with has somehow become out of sync, likely because of a mass import process (or something along those lines). Call it a "bug by design", but it seems that you have to manually reset the a primary key index after restoring from a dump file. At any rate, to see if your values are out of sync, run these two commands:

SELECT MAX(the_primary_key) FROM the_table;   
SELECT nextval('the_primary_key_sequence');

If the first value is higher than the second value, your sequence is out of sync. Back up your PG database (just in case), then run thisL

SELECT setval('the_primary_key_sequence', (SELECT MAX(the_primary_key) FROM the_table)+1);

That will set the sequence to the next available value that's higher than any existing primary key in the sequence.

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

The following works for me. Add the following method to the entity that is not the owner of the relationship (Group)

@PreRemove
private void removeGroupsFromUsers() {
    for (User u : users) {
        u.getGroups().remove(this);
    }
}

Keep in mind that for this to work, the Group must have an updated list of Users (which is not done automatically). so everytime you add a Group to the group list in User entity, you should also add a User to the user list in the Group entity.

Git: "Corrupt loose object"

I followed many of the other steps here; Linus' description of how to look at the git tree/objects and find what's missing was especially helpful. git-git recover corrupted blob

But in the end, for me, I had loose/corrupt tree objects caused by a partial disk failure, and tree objects are not so easily recovered/not covered by that doc.

In the end, I moved the conflicting objects/<ha>/<hash> out of the way, and used git unpack-objects with a pack file from a reasonably up to date clone. It was able to restore the missing tree objects.

Still left me with a lot of dangling blobs, which can be a side effect of unpacking previously archived stuff, and addressed in other questions here

Best way to Bulk Insert from a C# DataTable

string connectionString= ServerName + DatabaseName + SecurityType;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) {
    connection.Open();
    bulkCopy.DestinationTableName = "TableName";
    try {
        bulkCopy.WriteToServer(dataTableName);
    } catch (Exception e) {
        Console.Write(e.Message);
    }
}

Please note that the structure of the database table and the table name should be the same or it will throw an exception.

How to install pip for Python 3.6 on Ubuntu 16.10?

This answer assumes that you have python3.6 installed. For python3.7, replace 3.6 with 3.7. For python3.8, replace 3.6 with 3.8, but it may also first require the python3.8-distutils package.

Installation with sudo

With regard to installing pip, using curl (instead of wget) avoids writing the file to disk.

curl https://bootstrap.pypa.io/get-pip.py | sudo -H python3.6

The -H flag is evidently necessary with sudo in order to prevent errors such as the following when installing pip for an updated python interpreter:

The directory '/home/someuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

The directory '/home/someuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

Installation without sudo

curl https://bootstrap.pypa.io/get-pip.py | python3.6 - --user

This may sometimes give a warning such as:

WARNING: The script wheel is installed in '/home/ubuntu/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

Verification

After this, pip, pip3, and pip3.6 can all be expected to point to the same target:

$ (pip -V && pip3 -V && pip3.6 -V) | uniq
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Of course you can alternatively use python3.6 -m pip as well.

$ python3.6 -m pip -V
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

how to resolve DTS_E_OLEDBERROR. in ssis

I had a similar issue with my OLE DB Command and I resolved it by setting the ValidateExternalMetadata property within the component to False.

SVG fill color transparency / alpha?

fill="#044B9466"

This is an RGBA color in hex notation inside the SVG, defined with hex values. This is valid, but not all programs can display it properly...

You can find the browser support for this syntax here: https://caniuse.com/#feat=css-rrggbbaa

As of August 2017: RGBA fill colors will display properly on Mozilla Firefox (54), Apple Safari (10.1) and Mac OS X Finder's "Quick View". However Google Chrome did not support this syntax until version 62 (was previously supported from version 54 with the Experimental Platform Features flag enabled).

How do you clear Apache Maven's cache?

This works on the Spring Tool Suite v 3.1.0.RELEASE, but I'm guessing it's also available on Eclipse as well.

After deleting the artifacts by hand (as stated by palacsint above) in the /username/.m2 directory, re-index the files by doing the following:

Go to:

  • Windows->Preferences->Maven->User Settings menu.

Click the Reindex button next to the Local Repository text box. Click "Apply" then "OK" and you're done.

How to keep a Python script output window open?

On Python 3

input('Press Enter to Exit...')

Will do the trick.

How to parse JSON Array (Not Json Object) in Android

Create a class to hold the objects.

public class Person{
   private String name;
   private String url;
   //Get & Set methods for each field
}

Then deserialize as follows:

Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String

Reference Article: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/

How to get unique device hardware id in Android?

I use following code to get Android id.

String android_id = Secure.getString(this.getContentResolver(),
            Secure.ANDROID_ID);

Log.d("Android","Android ID : "+android_id);

enter image description here

How to change XML Attribute

Mike; Everytime I need to modify an XML document I work it this way:

//Here is the variable with which you assign a new value to the attribute
string newValue = string.Empty;
XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(xmlFile);

XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element");
node.Attributes[0].Value = newValue;

xmlDoc.Save(xmlFile);

//xmlFile is the path of your file to be modified

I hope you find it useful

Where could I buy a valid SSL certificate?

You are really asking a couple of questions here:

1) Why does the price of SSL certificates vary so much

2) Where can I get good, cheap SSL certificates?

The first question is a good one. For example, the type of SSL certificate you buy is important. Many SSL certificates are domain verified only - that is, the company issuing the certificate only validate that you own the domain. They don't validate your identity, so people visiting your site might know that the domain has a SSL certificate, but that doesn't mean the person behing the website isn't a scammer or phisher, for example. This is why the Verisign solution is much more expensive - you are getting a cert that not only secures your site, but validates the identity of the owner of the site (well, that's the claim).

You can read more on this subject here

For your second question, I can personally recommend RapidSSL. I've bought several certificates from them in the past and they are, well, rapid. However, you should always do your research first. A company based in France might be better for you to deal with as you can get support in your local hours, etc.

How to empty a Heroku database

To drop the database:

$ heroku pg:reset SHARED_DATABASE --confirm NAME_OF_THE_APP

To recreate the database:

$ heroku run rake db:migrate

To seed the database:

$ heroku run rake db:seed

**Final step

$ heroku restart

Html table tr inside td

Put another table inside the td element like this.

<table>
    <tr>
        ...
    </tr>
    <tr>
        <td>ABC</td>
        <td>ABC</td>
        <td>
            <table>
                <tr>
                    <td>name1</td>
                    <td>price1</td>
                </tr>
...
            </table>
        </td>
        <td>ABC</td>
    </tr>
...
</table>

How do I reference tables in Excel using VBA?

Converting a range to a table as described in this answer:

Sub CreateTable()
    ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$1:$D$16"), , xlYes).Name = _
        "Table1"
        'No go in 2003
    ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight2"
End Sub

Vertical divider CSS

.headerDivider {
     border-left:1px solid #38546d; 
     border-right:1px solid #16222c; 
     height:80px;
     position:absolute;
     right:249px;
     top:10px; 
}

<div class="headerDivider"></div>

Replace a string in a file with nodejs

<p>Please click in the following {{link}} to verify the account</p>


function renderHTML(templatePath: string, object) {
    const template = fileSystem.readFileSync(path.join(Application.staticDirectory, templatePath + '.html'), 'utf8');
    return template.match(/\{{(.*?)\}}/ig).reduce((acc, binding) => {
        const property = binding.substring(2, binding.length - 2);
        return `${acc}${template.replace(/\{{(.*?)\}}/, object[property])}`;
    }, '');
}
renderHTML(templateName, { link: 'SomeLink' })

for sure you can improve the reading template function to read as stream and compose the bytes by line to make it more efficient

How can I get the line number which threw exception?

If you don't have the .PBO file:

C#

public int GetLineNumber(Exception ex)
{
    var lineNumber = 0;
    const string lineSearch = ":line ";
    var index = ex.StackTrace.LastIndexOf(lineSearch);
    if (index != -1)
    {
        var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
        if (int.TryParse(lineNumberText, out lineNumber))
        {
        }
    }
    return lineNumber;
}

Vb.net

Public Function GetLineNumber(ByVal ex As Exception)
    Dim lineNumber As Int32 = 0
    Const lineSearch As String = ":line "
    Dim index = ex.StackTrace.LastIndexOf(lineSearch)
    If index <> -1 Then
        Dim lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length)
        If Int32.TryParse(lineNumberText, lineNumber) Then
        End If
    End If
    Return lineNumber
End Function

Or as an extentions on the Exception class

public static class MyExtensions
{
    public static int LineNumber(this Exception ex)
    {
        var lineNumber = 0;
        const string lineSearch = ":line ";
        var index = ex.StackTrace.LastIndexOf(lineSearch);
        if (index != -1)
        {
            var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
            if (int.TryParse(lineNumberText, out lineNumber))
            {
            }
        }
        return lineNumber;
    }
}   

problem with <select> and :after with CSS in WebKit

This post may help http://bavotasan.com/2011/style-select-box-using-only-css/

He is using a outside div with a class for resolving this issue.

<div class="styled-select">
  <select>
    <option>Here is the first option</option>
    <option>The second option</option>
  </select>
</div>

How to Select Top 100 rows in Oracle?

As Moneer Kamal said, you can do that simply:

SELECT id, client_id FROM order 
WHERE rownum <= 100
ORDER BY create_time DESC;

Notice that the ordering is done after getting the 100 row. This might be useful for who does not want ordering.

Add timestamp column with default NOW() for new rows only

You could add the default rule with the alter table,

ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP DEFAULT NOW()

then immediately set to null all the current existing rows:

UPDATE mytable SET created_at = NULL

Then from this point on the DEFAULT will take effect.

finding the type of an element using jQuery

The following will return true if the element is an input:

$("#elementId").is("input") 

or you can use the following to get the name of the tag:

$("#elementId").get(0).tagName

Xcode - Warning: Implicit declaration of function is invalid in C99

I have the same warning (it's make my app cannot build). When I add C function in Objective-C's .m file, But forgot to declared it at .h file.

How to read first N lines of a file?

Starting at Python 2.6, you can take advantage of more sophisticated functions in the IO base clase. So the top rated answer above can be rewritten as:

    with open("datafile") as myfile:
       head = myfile.readlines(N)
    print head

(You don't have to worry about your file having less than N lines since no StopIteration exception is thrown.)

How to read file from relative path in Java project? java.io.File cannot find the path specified

InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
} catch (Exception e) {
    e.printStackTrace();
}

Fixing Segmentation faults in C++

Sometimes the crash itself isn't the real cause of the problem-- perhaps the memory got smashed at an earlier point but it took a while for the corruption to show itself. Check out valgrind, which has lots of checks for pointer problems (including array bounds checking). It'll tell you where the problem starts, not just the line where the crash occurs.

Yarn: How to upgrade yarn version using terminal?

Not remembering how i've installed yarn the command that worked for me was:

yarn policies set-version

This command updates the current yarn version to the latest stable.

From the documentation:

Note that this command also is the preferred way to upgrade Yarn - it will work no matter how you originally installed it, which might sometimes prove difficult to figure out otherwise.

Reference

How to change the DataTable Column Name?

Use this

dataTable.Columns["OldColumnName"].ColumnName = "NewColumnName";

Change color when hover a font awesome icon?

if you want to change only the colour of the flag on hover use this:

http://jsfiddle.net/uvamhedx/

_x000D_
_x000D_
.fa-flag:hover {_x000D_
    color: red;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<i class="fa fa-flag fa-3x"></i>
_x000D_
_x000D_
_x000D_

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

It appears that IntelliJ 11 has changed the method, and the checked answer no longer works for me. In case anyone else arrives here via a search engine, here's how I solved it in IntelliJ 11:

  1. Go to the Project Structure, click on Modules, and click on your Module
  2. Choose the "Dependencies" tab
  3. Click the "+" button on the right-hand side and select "Jars or directories..."
  4. Add the directory(ies) you want (note you can multi-select) and click OK
  5. In the dialog that comes up, select "classes" and NOT "jar directory"
  6. Make sure you're using that Module in your run target

Note that step 5 seems to be the key difference. If you select "jar directory" it will look exactly the same in the IDE but won't include the path at runtime. There appears to be no way to determine whether you've previously selected "classes" or "jar directory" after the fact.

HTML Drag And Drop On Mobile Devices

Jquery Touch Punch is great but what it also does is disable all the controls on the draggable div so to prevent this you have to alter the lines... (at the time of writing - line 75)

change

if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])){

to read

if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0]) || event.originalEvent.target.localName === 'textarea'
        || event.originalEvent.target.localName === 'input' || event.originalEvent.target.localName === 'button' || event.originalEvent.target.localName === 'li'
        || event.originalEvent.target.localName === 'a'
        || event.originalEvent.target.localName === 'select' || event.originalEvent.target.localName === 'img') {

add as many ors as you want for each of the elements you want to 'unlock'

Hope that helps someone

Make JQuery UI Dialog automatically grow or shrink to fit its contents

Height is supported to auto.

Width is not!

To do some sort of auto get the size of the div you are showing and then set the window with.

In the C# code..

TheDiv.Style["width"] = "200px";

    private void setWindowSize(int width, int height)
    {
        string widthScript =    "$('.dialogDiv').dialog('option', 'width', "    +   width   +");";
        string heightScript =   "$('.dialogDiv').dialog('option', 'height', "   +   height  + ");";

        ScriptManager.RegisterStartupScript(this.Page, this.GetType(),
            "scriptDOWINDOWSIZE",
            "<script type='text/javascript'>"
            + widthScript
            + heightScript +
            "</script>", false);
    }

Using parameters in batch files at Windows command line

Use variables i.e. the .BAT variables and called %0 to %9

Converting String Array to an Integer Array

For Java 8 and higher:

    String[] test = {"1", "2", "3", "4", "5"};
    int[] ints = Arrays.stream(test).mapToInt(Integer::parseInt).toArray();

Set style for TextView programmatically

I met the problem too, and I found the way to set style programatically. Maybe you all need it, So I update there.

The third param of View constructor accepts a type of attr in your theme as the source code below:

public TextView(Context context, AttributeSet attrs) {
    this(context, attrs, com.android.internal.R.attr.textViewStyle);
}

So you must pass a type of R.attr.** rather than R.style.**

In my codes, I did following steps:

First, customize a customized attr to be used by themes in attr.xml.

<attr name="radio_button_style" format="reference" />

Second, specific your style in your used theme in style.xml.

 <style name="AppTheme" parent="android:Theme.Translucent">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    <item name="radio_button_style">@style/radioButtonStyle</item>
</style>
<style name="radioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">64dp</item>
    <item name="android:background">#000</item>
    <item name="android:button">@null</item>
    <item name="android:gravity">center</item>
    <item name="android:saveEnabled">false</item>
    <item name="android:textColor">@drawable/option_text_color</item>
    <item name="android:textSize">9sp</item>
</style>

At the end, use it!

            RadioButton radioButton = new RadioButton(mContext, null, R.attr.radio_button_style);

the view created programatically will use the specified style in your theme.

You can have a try, and hope it can work for you perfectly.

Python SQLite: database is locked

One possible reason for the database being locked that I ran into with SQLite is when I tried to access a row that was being written by one app, and read by another at the same time. You may want to set a busy timeout in your SQLite wrapper that will spin and wait for the database to become free (in the original c++ api the function is sqlite3_busy_timeout). I found that 300ms was sufficient in most cases.

But I doubt this is the problem, based on your post. Try other recommendations first.

Sending email with PHP from an SMTP server

In cases where you are hosting a Wordpress site on Linux and have server access you can save some headaches by installing msmtp which allows you to send via smtp from the standard php mail() function. msmtp is a simpler alternative to postfix which requires a bit more configuration.

Here are the steps:

Install msmtp

sudo apt-get install msmtp-mta ca-certificates

Create a new configuration file:

sudo nano /etc/msmtprc

...with the following configuration information:

# Set defaults.    
defaults

# Enable or disable TLS/SSL encryption.
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt

# Set up a default account's settings.
account default
host <smtp.example.net>
port 587
auth on
user <[email protected]>
password <password>
from <[email protected]>
syslog LOG_MAIL

You need to replace the configuration data represented by everything within "<" and ">" (inclusive, remove these). For host/username/password, use your normal credentials for sending mail through your mail provider.

Tell PHP to use it

sudo nano /etc/php5/apache2/php.ini

Add this single line:

sendmail_path = /usr/bin/msmtp -t

Complete documention can be found here:

https://marlam.de/msmtp/

Regular Expression Validation For Indian Phone Number and Mobile number

For Indian Mobile Numbers

Regular Expression to validate 11 or 12 (starting with 0 or 91) digit number

String regx = "(0/91)?[7-9][0-9]{9}";

String mobileNumber = "09756432848";

check 

if(mobileNumber.matches(regx)){
   "VALID MOBILE NUMBER"
}else{
   "INVALID MOBILE NUMBER"
}

You can check for 10 digit mobile number by removing "(0/91)?" from the regular expression i.e. regx

How to write to the Output window in Visual Studio?

Use the OutputDebugString function or the TRACE macro (MFC) which lets you do printf-style formatting:

int x = 1;
int y = 16;
float z = 32.0;
TRACE( "This is a TRACE statement\n" );    
TRACE( "The value of x is %d\n", x );
TRACE( "x = %d and y = %d\n", x, y );
TRACE( "x = %d and y = %x and z = %f\n", x, y, z );

Stacking DIVs on top of each other?

I know that this post is a little old but I had the same problem and tried to fix it several hours. Finally I found the solution:

if we have 2 boxes positioned absolue

<div style='left: 100px; top: 100px; position: absolute; width: 200px; height: 200px;'></div>
<div style='left: 100px; top: 100px; position: absolute; width: 200px; height: 200px;'></div>

we do expect that there will be one box on the screen. To do that we must set margin-bottom equal to -height, so doing like this:

<div style='left: 100px; top: 100px; position: absolute; width: 200px; height: 200px; margin-bottom: -200px;'></div>
<div style='left: 100px; top: 100px; position: absolute; width: 200px; height: 200px; margin-bottom: -200px;'></div>

works fine for me.

How to generate a random string of a fixed length in Go?

/*
    korzhao
*/

package rand

import (
    crand "crypto/rand"
    "math/rand"
    "sync"
    "time"
    "unsafe"
)

// Doesn't share the rand library globally, reducing lock contention
type Rand struct {
    Seed int64
    Pool *sync.Pool
}

var (
    MRand    = NewRand()
    randlist = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
)

// init random number generator
func NewRand() *Rand {
    p := &sync.Pool{New: func() interface{} {
        return rand.New(rand.NewSource(getSeed()))
    },
    }
    mrand := &Rand{
        Pool: p,
    }
    return mrand
}

// get the seed
func getSeed() int64 {
    return time.Now().UnixNano()
}

func (s *Rand) getrand() *rand.Rand {
    return s.Pool.Get().(*rand.Rand)
}
func (s *Rand) putrand(r *rand.Rand) {
    s.Pool.Put(r)
}

// get a random number
func (s *Rand) Intn(n int) int {
    r := s.getrand()
    defer s.putrand(r)

    return r.Intn(n)
}

//  bulk get random numbers
func (s *Rand) Read(p []byte) (int, error) {
    r := s.getrand()
    defer s.putrand(r)

    return r.Read(p)
}

func CreateRandomString(len int) string {
    b := make([]byte, len)
    _, err := MRand.Read(b)
    if err != nil {
        return ""
    }
    for i := 0; i < len; i++ {
        b[i] = randlist[b[i]%(62)]
    }
    return *(*string)(unsafe.Pointer(&b))
}

24.0 ns/op 16 B/op 1 allocs/

How to reload page every 5 seconds?

There's an automatic refresh-on-change tool for IE. It's called ReloadIt, and is available at http://reloadit.codeplex.com . Free.

You choose a URL that you'd like to auto-reload, and specify one or more directory paths to monitor for changes. Press F12 to start monitoring.

enter image description here

After you set it, minimize it. Then edit your content files. When you save any change, the page gets reloaded. like this:

enter image description here

Simple. easy.

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

You are not getting value of $id=$_GET['id'];

And you are using it (before it gets initialised).

Use php's in built isset() function to check whether the variable is defied or not.

So, please update the line to:

$id = isset($_GET['id']) ? $_GET['id'] : '';

Usage of unicode() and encode() functions in Python

Make sure you've set your locale settings right before running the script from the shell, e.g.

$ locale -a | grep "^en_.\+UTF-8"
en_GB.UTF-8
en_US.UTF-8
$ export LC_ALL=en_GB.UTF-8
$ export LANG=en_GB.UTF-8

Docs: man locale, man setlocale.

JavaScript - Replace all commas in a string

Just for fun:

var mystring = "this,is,a,test"  
var newchar = '|'
mystring = mystring.split(',').join(newchar);

How do you change library location in R?

You can edit Rprofile in the base library (in 'C:/Program Files/R.Files/library/base/R' by default) to include code to be run on startup. Append

########        User code        ########
.libPaths('C:/my/dir')

to Rprofile using any text editor (like Notepad) to cause R to add 'C:/my/dir' to the list of libraries it knows about.

(Notepad can't save to Program Files, so save your edited Rprofile somewhere else and then copy it in using Windows Explorer.)

Convert string to date then format the date

In one line:

String date=new SimpleDateFormat("MM-dd-yyyy").format(new SimpleDateFormat("yyyy-MM-dd").parse("2011-01-01"));

Where:

String date=new SimpleDateFormat("FinalFormat").format(new SimpleDateFormat("InitialFormat").parse("StringDate"));

sql like operator to get the numbers only

With SQL 2012 and later, you could use TRY_CAST/TRY_CONVERT to try converting to a numeric type, e.g. TRY_CAST(answer AS float) IS NOT NULL -- note though that this will match scientific notation too (1+E34). (If you use decimal, then scientific notation won't match)

Print string to text file

If you are using Python3.

then you can use Print Function :

your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data,  file=open('D:\log.txt', 'w'))

For python2

this is the example of Python Print String To Text File

def my_func():
    """
    this function return some value
    :return:
    """
    return 25.256


def write_file(data):
    """
    this function write data to file
    :param data:
    :return:
    """
    file_name = r'D:\log.txt'
    with open(file_name, 'w') as x_file:
        x_file.write('{} TotalAmount'.format(data))


def run():
    data = my_func()
    write_file(data)


run()

MongoDB: How to find the exact version of installed MongoDB

Option1:

Start the console and execute this:

db.version()

Option2:

Open a shell console and do:

$ mongod --version

It will show you something like

$ mongod --version
db version v3.0.2

When is a CDATA section necessary within a script tag?

Do not use CDATA in HTML4 but you should use CDATA in XHTML and must use CDATA in XML if you have unescaped symbols like < and >.

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

NSDate *date         = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"]
NSString *dateString  = [df stringFromDate:date];
[df setDateFormat:@"hh:mm:ss"];
NSString *hoursString = [df stringFromDate:date];

Thats it, you got it all you want.

Open link in new tab or window

set the target attribute of your <a> element to "_tab"

EDIT: It works, however W3Schools says there is no such target attribute: http://www.w3schools.com/tags/att_a_target.asp

EDIT2: From what I've figured out from the comments. setting target to _blank will take you to a new tab or window (depending on your browser settings). Typing anything except one of the ones below will create a new tab group (I'm not sure how these work):

_blank  Opens the linked document in a new window or tab
_self   Opens the linked document in the same frame as it was clicked (this is default)
_parent Opens the linked document in the parent frame
_top    Opens the linked document in the full body of the window
framename   Opens the linked document in a named frame

List Git commits not pushed to the origin yet

git log origin/master..master

or, more generally:

git log <since>..<until>

You can use this with grep to check for a specific, known commit:

git log <since>..<until> | grep <commit-hash>

Or you can also use git-rev-list to search for a specific commit:

git rev-list origin/master | grep <commit-hash>

Convert a hexadecimal string to an integer efficiently in C?

For larger Hex strings like in the example I needed to use strtoul.

Windows 7 environment variable not working in path

If there is any error at all in the PATH windows will silently disregard it. Things like having %PATH% or spaces between items in your path will break it. Be warned

select and echo a single field from mysql db using PHP

Try this:

echo mysql_result($result, 0);

This is enough because you are only fetching one field of one row.

How to search by key=>value in a multidimensional array in PHP

<?php
$arr = array(0 => array("id"=>1,"name"=>"cat 1"),
             1 => array("id"=>2,"name"=>"cat 2"),
             2 => array("id"=>3,"name"=>"cat 1")
);
$arr = array_filter($arr, function($ar) {
   return ($ar['name'] == 'cat 1');
   //return ($ar['name'] == 'cat 1' AND $ar['id'] == '3');// you can add multiple conditions
});

echo "<pre>";
print_r($arr);

?>

Ref: http://php.net/manual/en/function.array-filter.php

How to get the focused element with jQuery?

$( document.activeElement )

Will retrieve it without having to search the whole DOM tree as recommended on the jQuery documentation

How to set a value of a variable inside a template code?

Perhaps the default template filter wasn't an option back in 2009...

<html>
<div>Hello {{name|default:"World"}}!</div>
</html>

Stop executing further code in Java

return to come out of the method execution, break to come out of a loop execution and continue to skip the rest of the current loop. In your case, just return, but if you are in a for loop, for example, do break to stop the loop or continue to skip to next step in the loop

Network tools that simulate slow network connection

You can use dummynet ofcourse, There is extension of dummynet called KauNet. which can provide even more precise control of network conditions. It can drop/delay/re-order specific packets (that way you can perform more in-depth analysis of dropping key packets like TCP handshake to see how your web pages digest it). It also works in time domain. Usually most the emulators are tuned to work in data domain. In time domain you can specify from what time to what time you can alter the network conditions.

Convert INT to VARCHAR SQL

CONVERT(DATA_TYPE , Your_Column) is the syntax for CONVERT method in SQL. From this convert function we can convert the data of the Column which is on the right side of the comma (,) to the data type in the left side of the comma (,) Please see below example.

SELECT CONVERT (VARCHAR(10), ColumnName) FROM TableName

ASP.NET MVC Razor render without encoding

Since ASP.NET MVC 3, you can use:

@Html.Raw(myString)

How to make code wait while calling asynchronous calls like Ajax

Why didn't it work for you using Deferred Objects? Unless I misunderstood something this may work for you.

/* AJAX success handler */
var echo = function() {
    console.log('Pass1');
};

var pass = function() {
  $.when(
    /* AJAX requests */
    $.post("/echo/json/", { delay: 1 }, echo),
    $.post("/echo/json/", { delay: 2 }, echo),
    $.post("/echo/json/", { delay: 3 }, echo)
  ).then(function() {
    /* Run after all AJAX */
    console.log('Pass2');
  });
};?

See it here.


UPDATE

Based on your input it seems what your quickest alternative is to use synchronous requests. You can set the property async to false in your $.ajax requests to make them blocking. This will hang your browser until the request is finished though.

Notice I don't recommend this and I still consider you should fix your code in an event-based workflow to not depend on it.

StringIO in Python3

In order to make examples from here work with Python 3.5.2, you can rewrite as follows :

import io
data =io.BytesIO(b"1, 2, 3\n4, 5, 6") 
import numpy
numpy.genfromtxt(data, delimiter=",")

The reason for the change may be that the content of a file is in data (bytes) which do not make text until being decoded somehow. genfrombytes may be a better name than genfromtxt.

What does Docker add to lxc-tools (the userspace LXC tools)?

Let's take a look at the list of Docker's technical features, and check which ones are provided by LXC and which ones aren't.

Features:

1) Filesystem isolation: each process container runs in a completely separate root filesystem.

Provided with plain LXC.

2) Resource isolation: system resources like cpu and memory can be allocated differently to each process container, using cgroups.

Provided with plain LXC.

3) Network isolation: each process container runs in its own network namespace, with a virtual interface and IP address of its own.

Provided with plain LXC.

4) Copy-on-write: root filesystems are created using copy-on-write, which makes deployment extremely fast, memory-cheap and disk-cheap.

This is provided by AUFS, a union filesystem that Docker depends on. You could set up AUFS yourself manually with LXC, but Docker uses it as a standard.

5) Logging: the standard streams (stdout/stderr/stdin) of each process container is collected and logged for real-time or batch retrieval.

Docker provides this.

6) Change management: changes to a container's filesystem can be committed into a new image and re-used to create more containers. No templating or manual configuration required.

"Templating or manual configuration" is a reference to LXC, where you would need to learn about both of these things. Docker allows you to treat containers in the way that you're used to treating virtual machines, without learning about LXC configuration.

7) Interactive shell: docker can allocate a pseudo-tty and attach to the standard input of any container, for example to run a throwaway interactive shell.

LXC already provides this.


I only just started learning about LXC and Docker, so I'd welcome any corrections or better answers.

Append text using StreamWriter

using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
  writer.WriteLine("whatever you text is");
}

The second "true" parameter tells it to append.

http://msdn.microsoft.com/en-us/library/36b035cb.aspx

Could not load file or assembly 'System.Web.Mvc'

I just wrote a blog post addressing this. You could install ASP.NET MVC on your server OR you can follow the steps here.


EDIT: (by jcolebrand) I went through this link, then had the same issue as Victor below, so I suggest you also add these:

* Microsoft.Web.Infrastructure
* System.Web.Razor
* System.Web.WebPages.Deployment
* System.Web.WebPages.Razor

Force table column widths to always be fixed regardless of contents

Specify the width of the table:

table
{
    table-layout: fixed;
    width: 100px;
}

See jsFiddle

Get host domain from URL?

You can use Request object or Uri object to get host of url.

Using Request.Url

string host = Request.Url.Host;

Using Uri

Uri myUri = new Uri("http://www.contoso.com:8080/");   
string host = myUri.Host;  // host is "www.contoso.com"

Differences between strong and weak in Objective-C

To understand Strong and Weak reference consider below example, suppose we have method named as displayLocalVariable.

 -(void)displayLocalVariable
  {
     UIView* myView = [[UIView alloc] init];
     NSLog(@"myView tag is = %ld", myView.tag);
  }

In above method scope of myView variable is limited to displayLocalVariable method, once the method gets finished myView variable which is holding the UIView object will get deallocated from the memory.

Now what if we want to hold the myView variable throughout our view controller's life cycle. For this we can create the property named as usernameView which will have Strong reference to the variable myView(see @property(nonatomic,strong) UIView* usernameView; and self.usernameView = myView; in below code), as below,

@interface LoginViewController ()

@property(nonatomic,strong) UIView* usernameView;
@property(nonatomic,weak) UIView* dummyNameView;

- (void)displayLocalVariable;

@end

@implementation LoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

}

-(void)viewWillAppear:(BOOL)animated
{
     [self displayLocalVariable];
}

- (void)displayLocalVariable
{
   UIView* myView = [[UIView alloc] init];
   NSLog(@"myView tag is = %ld", myView.tag);
   self.usernameView = myView;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end

Now in above code you can see myView has been assigned to self.usernameView and self.usernameView is having a strong reference(as we declared in interface using @property) to myView. Hence myView will not get deallocated from memory till self.usernameView is alive.

  • Weak reference

Now consider assigning myName to dummyNameView which is a Weak reference, self.dummyNameView = myView; Unlike Strong reference Weak will hold the myView only till there is Strong reference to myView. See below code to understand Weak reference,

-(void)displayLocalVariable
  {
     UIView* myView = [[UIView alloc] init];
     NSLog(@"myView tag is = %ld", myView.tag);
     self.dummyNameView = myView;
  }

In above code there is Weak reference to myView(i.e. self.dummyNameView is having Weak reference to myView) but there is no Strong reference to myView, hence self.dummyNameView will not be able to hold the myView value.

Now again consider the below code,

-(void)displayLocalVariable
      {
         UIView* myView = [[UIView alloc] init];
         NSLog(@"myView tag is = %ld", myView.tag);
         self.usernameView = myView;
         self.dummyNameView = myView;
      } 

In above code self.usernameView has a Strong reference to myView, hence self.dummyNameView will now have a value of myView even after method ends since myView has a Strong reference associated with it.

Now whenever we make a Strong reference to a variable it's retain count get increased by one and the variable will not get deallocated till it's retain count reaches to 0.

Hope this helps.

Iterate through a HashMap

If you're only interested in the keys, you can iterate through the keySet() of the map:

Map<String, Object> map = ...;

for (String key : map.keySet()) {
    // ...
}

If you only need the values, use values():

for (Object value : map.values()) {
    // ...
}

Finally, if you want both the key and value, use entrySet():

for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}

One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see karim79's answer). However, changing item values is OK (see Map.Entry).

Utils to read resource text file to String (Java)

public static byte[] readResoureStream(String resourcePath) throws IOException {
    ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
    InputStream in = CreateBffFile.class.getResourceAsStream(resourcePath);

    //Create buffer
    byte[] buffer = new byte[4096];
    for (;;) {
        int nread = in.read(buffer);
        if (nread <= 0) {
            break;
        }
        byteArray.write(buffer, 0, nread);
    }
    return byteArray.toByteArray();
}

Charset charset = StandardCharsets.UTF_8;
String content = new   String(FileReader.readResoureStream("/resource/...*.txt"), charset);
String lines[] = content.split("\\n");

When does socket.recv(recv_size) return?

I think you conclusions are correct but not accurate.

As the docs indicates, socket.recv is majorly focused on the network buffers.

When socket is blocking, socket.recv will return as long as the network buffers have bytes. If bytes in the network buffers are more than socket.recv can handle, it will return the maximum number of bytes it can handle. If bytes in the network buffers are less than socket.recv can handle, it will return all the bytes in the network buffers.

Android camera intent

It took me some hours to get this working. The code it's almost a copy-paste from developer.android.com, with a minor difference.

Request this permission on the AndroidManifest.xml:

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

On your Activity, start by defining this:

static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;

Then fire this Intent in an onClick:

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
    // Create the File where the photo should go
    File photoFile = null;
    try {
        photoFile = createImageFile();
    } catch (IOException ex) {
        // Error occurred while creating the File
        Log.i(TAG, "IOException");
    }
    // Continue only if the File was successfully created
    if (photoFile != null) {
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
    }
}

Add the following support method:

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  // prefix
            ".jpg",         // suffix
            storageDir      // directory
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}

Then receive the result:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        try {
            mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
            mImageView.setImageBitmap(mImageBitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

What made it work is the MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath)), which is different from the code from developer.android.com. The original code gave me a FileNotFoundException.

How to annotate MYSQL autoincrement field with JPA annotations

If you are using MariaDB this will work

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;

For more, you can check https://thorben-janssen.com/hibernate-tips-use-auto-incremented-column-primary-key/

Sequelize.js delete query?

Sequelize methods return promises, and there is no delete() method. Sequelize uses destroy() instead.

Example

Model.destroy({
  where: {
    some_field: {
      //any selection operation
      // for example [Op.lte]:new Date()
    }
  }
}).then(result => {
  //some operation
}).catch(error => {
  console.log(error)
})

Documentation for more details: https://www.codota.com/code/javascript/functions/sequelize/Model/destroy

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

I can't be satisfied by the answers calling for a English-only solution based on manual formats. I've been looking for a proper solution for a while now and I finally found it.

You should be using RuleBasedNumberFormat. It works perfectly and it's respectful of the Locale.

Best way to check if a URL is valid

Given issues with filter_var() needing http://, I use:

$is_url = filter_var($filename, FILTER_VALIDATE_URL) || array_key_exists('scheme', parse_url($filename));

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

Instead of

return new ResponseEntity<JSONObject>(entities, HttpStatus.OK);

try

return new ResponseEntity<List<JSONObject>>(entities, HttpStatus.OK);

Convert Data URI to File then append to FormData

This one works in iOS and Safari.

You need to use Stoive's ArrayBuffer solution but you can't use BlobBuilder, as vava720 indicates, so here's the mashup of both.

function dataURItoBlob(dataURI) {
    var byteString = atob(dataURI.split(',')[1]);
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ab], { type: 'image/jpeg' });
}

Creating a list of pairs in java

just fixing some small mistakes in Mark Elliot's code:

public class Pair<L,R> {
    private L l;
    private R r;
    public Pair(L l, R r){
        this.l = l;
        this.r = r;
    }
    public L getL(){ return l; }
    public R getR(){ return r; }
    public void setL(L l){ this.l = l; }
    public void setR(R r){ this.r = r; }
}

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Declare the Start and End date DECLARE @SDATE AS DATETIME

TART_DATE  AS DATETIME
DECLARE @END_-- Set Start and End date
SET @START_DATE = GETDATE()
SET @END_DATE    = DATEADD(SECOND, 3910, GETDATE())

-- Get the Result in HH:MI:SS:MMM(24H) format SELECT CONVERT(VARCHAR(12), DATEADD(MS, DATEDIFF(MS, @START_DATE, @END_DATE), 0), 114) AS TimeDiff

/bin/sh: apt-get: not found

If you are looking inside dockerfile while creating image, add this line:

RUN apk add --update yourPackageName

Bash scripting, multiple conditions in while loop

Try:

while [ $stats -gt 300 -o $stats -eq 0 ]

[ is a call to test. It is not just for grouping, like parentheses in other languages. Check man [ or man test for more information.

How do I rename a column in a SQLite database table?

Digging around, I found this multiplatform (Linux | Mac | Windows) graphical tool called DB Browser for SQLite that actually allows one to rename columns in a very user friendly way!

Edit | Modify Table | Select Table | Edit Field. Click click! Voila!

However, if someone want to share a programmatic way of doing this, I'd be happy to know!

How do you copy the contents of an array to a std::vector in C++ without looping?

Since I can only edit my own answer, I'm going to make a composite answer from the other answers to my question. Thanks to all of you who answered.

Using std::copy, this still iterates in the background, but you don't have to type out the code.

int foo(int* data, int size)
{
   static std::vector<int> my_data; //normally a class variable
   std::copy(data, data + size, std::back_inserter(my_data));
   return 0;
}

Using regular memcpy. This is probably best used for basic data types (i.e. int) but not for more complex arrays of structs or classes.

vector<int> x(size);
memcpy(&x[0], source, size*sizeof(int));

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

Its because of the new DbContext T4 template that is used for generating the EntityFramework entities. In order to be able to perform the change tracking, this templates uses the Proxy pattern, by wrapping your nice POCOs with them. This then causes the issues when serializing with the JavaScriptSerializer.

So then the 2 solutions are:

  1. Either you just serialize and return the properties you need on the client
  2. You may switch off the automatic generation of proxies by setting it on the context's configuration

    context.Configuration.ProxyCreationEnabled = false;

Very well explained in the below article.

http://juristr.com/blog/2011/08/javascriptserializer-circular-reference/

Importing json file in TypeScript

In your TS Definition file, e.g. typings.d.ts`, you can add this line:

declare module "*.json" {
const value: any;
export default value;
}

Then add this in your typescript(.ts) file:-

import * as data from './colors.json';
const word = (<any>data).name;

How to save CSS changes of Styles panel of Chrome Developer Tools?

New versions of Chrome have a feature called workspaces which addresses this issue. You can define which paths on your webserver correspond to which paths on your system, then edit and save with just ctrl-s.

See: http://www.html5rocks.com/en/tutorials/developertools/revolutions2013/

Maximum execution time in phpMyadmin

Your change should work. However, there are potentially few php.ini configuration files with the 'xampp' stack. Try to identify whether or not there's an 'apache' specific php.ini. One potential location is:

C:\xampp\apache\bin\php.ini

TSQL Default Minimum DateTime

I think your only option here is a constant. With that said - don't use it - stick with nulls instead of bogus dates.

create table atable
(
  atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Modified datetime DEFAULT '1/1/1753'
)

varbinary to string on SQL Server

"Converting a varbinary to a varchar" can mean different things.

If the varbinary is the binary representation of a string in SQL Server (for example returned by casting to varbinary directly or from the DecryptByPassPhrase or DECOMPRESS functions) you can just CAST it

declare @b varbinary(max)
set @b = 0x5468697320697320612074657374

select cast(@b as varchar(max)) /*Returns "This is a test"*/

This is the equivalent of using CONVERT with a style parameter of 0.

CONVERT(varchar(max), @b, 0)

Other style parameters are available with CONVERT for different requirements as noted in other answers.

newline in <td title="">

This should be OK, but is Internet Explorer specific:

<td title="lineone
linetwo 
etc...">

As others have mentioned, the only other way is to use an HTML + JavaScript based tooltip if you're only interested in the tooltip. If this is for accessibility then you will probably need to stick to just single lines for consistency.

C++ wait for user input

You can try

#include <iostream>
#include <conio.h>

int main() {

    //some codes

    getch();
    return 0;
}

jQuery UI Sortable, then write order into a database

The jQuery UI sortable feature includes a serialize method to do this. It's quite simple, really. Here's a quick example that sends the data to the specified URL as soon as an element has changes position.

$('#element').sortable({
    axis: 'y',
    update: function (event, ui) {
        var data = $(this).sortable('serialize');

        // POST to server using $.post or $.ajax
        $.ajax({
            data: data,
            type: 'POST',
            url: '/your/url/here'
        });
    }
});

What this does is that it creates an array of the elements using the elements id. So, I usually do something like this:

<ul id="sortable">
   <li id="item-1"></li>
   <li id="item-2"></li>
   ...
</ul>

When you use the serialize option, it will create a POST query string like this: item[]=1&item[]=2 etc. So if you make use - for example - your database IDs in the id attribute, you can then simply iterate through the POSTed array and update the elements' positions accordingly.

For example, in PHP:

$i = 0;

foreach ($_POST['item'] as $value) {
    // Execute statement:
    // UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
    $i++;
}

Example on jsFiddle.

How to use Switch in SQL Server

Actually i am getting return value from a another sp into @temp and then it @temp =1 then i want to inc the count of @SelectoneCount by 1 and so on. Please let me know what is the correct syntax.

What's wrong with:

IF @Temp = 1 --Or @Temp = 2 also?
BEGIN
    SET @SelectoneCount = @SelectoneCount + 1
END

(Although this does reek of being procedural code - not usually the best way to use SQL)

List all kafka topics

Kafka uses ZooKeeper so you need to first start a ZooKeeper server if you don't already have one.

If you do not want to install and have a separate zookeeper server, you can use the convenience script packaged with kafka to get a quick-and-dirty single-node ZooKeeper instance.

Starting the single-node Zookeeper instance:

bin/zookeeper-server-start.sh config/zookeeper.properties

Starting the Kafka Server:

bin/kafka-server-start.sh config/server.properties

Listing the Topics available in Kafka:

bin/kafka-topics.sh --list --zookeeper localhost:2181

How to change mysql to mysqli?

I would tentatively recommend using PDO for your SQL access.

Then it is only a case of changing the driver and ensuring the SQL works on the new backend. In theory. Data migration is a different issue.

Abstract database access is great.

Improve INSERT-per-second performance of SQLite

After reading this tutorial, I tried to implement it to my program.

I have 4-5 files that contain addresses. Each file has approx 30 million records. I am using the same configuration that you are suggesting but my number of INSERTs per second is way low (~10.000 records per sec).

Here is where your suggestion fails. You use a single transaction for all the records and a single insert with no errors/fails. Let's say that you are splitting each record into multiple inserts on different tables. What happens if the record is broken?

The ON CONFLICT command does not apply, cause if you have 10 elements in a record and you need each element inserted to a different table, if element 5 gets a CONSTRAINT error, then all previous 4 inserts need to go too.

So here is where the rollback comes. The only issue with the rollback is that you lose all your inserts and start from the top. How can you solve this?

My solution was to use multiple transactions. I begin and end a transaction every 10.000 records (Don't ask why that number, it was the fastest one I tested). I created an array sized 10.000 and insert the successful records there. When the error occurs, I do a rollback, begin a transaction, insert the records from my array, commit and then begin a new transaction after the broken record.

This solution helped me bypass the issues I have when dealing with files containing bad/duplicate records (I had almost 4% bad records).

The algorithm I created helped me reduce my process by 2 hours. Final loading process of file 1hr 30m which is still slow but not compared to the 4hrs that it initially took. I managed to speed the inserts from 10.000/s to ~14.000/s

If anyone has any other ideas on how to speed it up, I am open to suggestions.

UPDATE:

In Addition to my answer above, you should keep in mind that inserts per second depending on the hard drive you are using too. I tested it on 3 different PCs with different hard drives and got massive differences in times. PC1 (1hr 30m), PC2 (6hrs) PC3 (14hrs), so I started wondering why would that be.

After two weeks of research and checking multiple resources: Hard Drive, Ram, Cache, I found out that some settings on your hard drive can affect the I/O rate. By clicking properties on your desired output drive you can see two options in the general tab. Opt1: Compress this drive, Opt2: Allow files of this drive to have contents indexed.

By disabling these two options all 3 PCs now take approximately the same time to finish (1hr and 20 to 40min). If you encounter slow inserts check whether your hard drive is configured with these options. It will save you lots of time and headaches trying to find the solution

Can I stop 100% Width Text Boxes from extending beyond their containers?

Just style the input to offset for the extra padding. In the following example the padding on the input would be 10px on the left and right for a total padding offset of 20px:

input[type=text]{
   width: calc(100% - 20px);
}

Convert columns to string in Pandas

Using .apply() with a lambda conversion function also works in this case:

total_rows['ColumnID'] = total_rows['ColumnID'].apply(lambda x: str(x))

For entire dataframes you can use .applymap(). (but in any case probably .astype() is faster)

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

if you open localhost/phpmyadmin you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.

How to implement infinity in Java?

Only Double and Float type support POSITIVE_INFINITY constant.

Check if a div does NOT exist with javascript

I do below and check if id exist and execute function if exist.

var divIDVar = $('#divID').length;
if (divIDVar === 0){ 
    console.log('No DIV Exist'); 
} else{  
    FNCsomefunction(); 
}   

Incrementing a variable inside a Bash loop

minimalist

counter=0
((counter++))
echo $counter

"Uncaught TypeError: Illegal invocation" in Chrome

In your code you are assigning a native method to a property of custom object. When you call support.animationFrame(function () {}) , it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window.

So the correct usage here is support.animationFrame.call(window, function() {});.

The same happens with alert too:

var myObj = {
  myAlert : alert //copying native alert to an object
};

myObj.myAlert('this is an alert'); //is illegal
myObj.myAlert.call(window, 'this is an alert'); // executing in context of window 

Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.

var _raf = window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame;

var support = {
   animationFrame: _raf ? _raf.bind(window) : null
};

Where to declare variable in react js

Using ES6 syntax in React does not bind this to user-defined functions however it will bind this to the component lifecycle methods.

So the function that you declared will not have the same context as the class and trying to access this will not give you what you are expecting.

For getting the context of class you have to bind the context of class to the function or use arrow functions.

Method 1 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.onMove = this.onMove.bind(this);
        this.testVarible= "this is a test";
    }

    onMove() {
        console.log(this.testVarible);
    }
}

Method 2 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.testVarible= "this is a test";
    }

    onMove = () => {
        console.log(this.testVarible);
    }
}

Method 2 is my preferred way but you are free to choose your own.

Update: You can also create the properties on class without constructor:

class MyContainer extends Component {

    testVarible= "this is a test";

    onMove = () => {
        console.log(this.testVarible);
    }
}

Note If you want to update the view as well, you should use state and setState method when you set or change the value.

Example:

class MyContainer extends Component {

    state = { testVarible: "this is a test" };

    onMove = () => {
        console.log(this.state.testVarible);
        this.setState({ testVarible: "new value" });
    }
}

I want to truncate a text or line with ellipsis using JavaScript

HTML with JavaScript:

<p id="myid">My long long looooong text cut cut cut cut cut</p>

<script type="text/javascript">
var myid=document.getElementById('myid');
myid.innerHTML=myid.innerHTML.substring(0,10)+'...';
</script>

The result will be:

My long lo...

Cheers

G.

Removing double quotes from a string in Java

You can just go for String replace method.-

line1 = line1.replace("\"", "");

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

after studying above that package name in manifest file and application id in gradle build file should be same. my issue didn't resolved.

Actually your application id in gradle build file should be same as your package name in google-services.json file. if your google-services.json file has different package name. delete that app from google analytics or firebase console. and get a new file.

How to deploy a Java Web Application (.war) on tomcat?

As others pointed out, the most straightforward way to deploy a WAR is to copy it to the webapps of the Tomcat install. Another option would be to use the manager application if it is installed (this is not always the case), if it's properly configured (i.e. if you have the credentials of a user assigned to the appropriate group) and if it you can access it over an insecure network like Internet (but this is very unlikely and you didn't mention any VPN access). So this leaves you with the webappdirectory.

Now, if Tomcat is installed and running on bilgin.ath.cx (as this is the machine where you uploaded the files), I noticed that Apache is listening to port 80 on that machien so I would bet that Tomcat is not directly exposed and that requests have to go through Apache. In that case, I think that deploying a new webapp and making it visible to the Internet will involve the edit of Apache configuration files (mod_jk?, mod_proxy?). You should either give us more details or discuss this with your hosting provider.

Update: As expected, the bilgin.ath.cx is using Apache Tomcat + Apache HTTPD + mod_jk. The configuration usually involves two files: the worker.properties file to configure the workers and the httpd.conf for Apache. Now, without seeing the current configuration, it's not easy to give a definitive answer but, basically, you may have to add a JkMount directive in Apache httpd.conf for your new webapp1. Refer to the mod_jk documentation, it has a simple configuration example. Note that modifying httpd.conf will require access to (obviously) and proper rights and that you'll have to restart Apache after the modifications.

1 I don't think you'll need to define a new worker if you are deploying to an already used Tomcat instance, especially if this sounds like Chinese for you :)

How to change indentation mode in Atom?

OS X:

  1. Go to Atom -> prefrences or CMD + ,

  2. Scroll down and select "Tab Length" that you prefer.

enter image description here

How can I check what version/edition of Visual Studio is installed programmatically?

All the information in this thread is now out of date with the recent release of vswhere. Download that and use it.

How to extract the decision rules from scikit-learn decision-tree?

Here is a function, printing rules of a scikit-learn decision tree under python 3 and with offsets for conditional blocks to make the structure more readable:

def print_decision_tree(tree, feature_names=None, offset_unit='    '):
    '''Plots textual representation of rules of a decision tree
    tree: scikit-learn representation of tree
    feature_names: list of feature names. They are set to f1,f2,f3,... if not specified
    offset_unit: a string of offset of the conditional block'''

    left      = tree.tree_.children_left
    right     = tree.tree_.children_right
    threshold = tree.tree_.threshold
    value = tree.tree_.value
    if feature_names is None:
        features  = ['f%d'%i for i in tree.tree_.feature]
    else:
        features  = [feature_names[i] for i in tree.tree_.feature]        

    def recurse(left, right, threshold, features, node, depth=0):
            offset = offset_unit*depth
            if (threshold[node] != -2):
                    print(offset+"if ( " + features[node] + " <= " + str(threshold[node]) + " ) {")
                    if left[node] != -1:
                            recurse (left, right, threshold, features,left[node],depth+1)
                    print(offset+"} else {")
                    if right[node] != -1:
                            recurse (left, right, threshold, features,right[node],depth+1)
                    print(offset+"}")
            else:
                    print(offset+"return " + str(value[node]))

    recurse(left, right, threshold, features, 0,0)

Enforcing the type of the indexed members of a Typescript object?

interface AccountSelectParams {
  ...
}
const params = { ... };

const tmpParams: { [key in keyof AccountSelectParams]: any } | undefined = {};
  for (const key of Object.keys(params)) {
    const customKey = (key as keyof typeof params);
    if (key in params && params[customKey] && !this.state[customKey]) {
      tmpParams[customKey] = params[customKey];
    }
  }

please commented if you get the idea of this concept

What does it mean to have an index to scalar variable error? python

In my case, I was getting this error because I had an input named x and I was creating (without realizing it) a local variable called x. I thought I was trying to access an element of the input x (which was an array), while I was actually trying to access an element of the local variable x (which was a scalar).

Variably modified array at file scope

If you're going to use the preprocessor anyway, as per the other answers, then you can make the compiler determine the value of NUM_TYPES automagically:

#define NUM_TYPES (sizeof types / sizeof types[0])
static int types[] = { 
  1,
  2, 
  3, 
  4 };

Python/Json:Expecting property name enclosed in double quotes

In my case, double quotes was not a problem.

Last comma gave me same error message.

{'a':{'b':c,}}
           ^

To remove this comma, I wrote some simple code.

import json

with open('a.json','r') as f:
    s = f.read()
    s = s.replace('\t','')
    s = s.replace('\n','')
    s = s.replace(',}','}')
    s = s.replace(',]',']')
    data = json.loads(s)

And this worked for me.

How do you read from stdin?

Read from sys.stdin, but to read binary data on Windows, you need to be extra careful, because sys.stdin there is opened in text mode and it will corrupt \r\n replacing them with \n.

The solution is to set mode to binary if Windows + Python 2 is detected, and on Python 3 use sys.stdin.buffer.

import sys

PY3K = sys.version_info >= (3, 0)

if PY3K:
    source = sys.stdin.buffer
else:
    # Python 2 on Windows opens sys.stdin in text mode, and
    # binary data that read from it becomes corrupted on \r\n
    if sys.platform == "win32":
        # set sys.stdin to binary mode
        import os, msvcrt
        msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
    source = sys.stdin

b = source.read()

Checking if a list is empty with LINQ

I just wrote up a quick test, try this:

 IEnumerable<Object> myList = new List<Object>();

 Stopwatch watch = new Stopwatch();

 int x;

 watch.Start();
 for (var i = 0; i <= 1000000; i++)
 {
    if (myList.Count() == 0) x = i; 
 }
 watch.Stop();

 Stopwatch watch2 = new Stopwatch();

 watch2.Start();
 for (var i = 0; i <= 1000000; i++)
 {
     if (!myList.Any()) x = i;
 }
 watch2.Stop();

 Console.WriteLine("myList.Count() = " + watch.ElapsedMilliseconds.ToString());
 Console.WriteLine("myList.Any() = " + watch2.ElapsedMilliseconds.ToString());
 Console.ReadLine();

The second is almost three times slower :)

Trying the stopwatch test again with a Stack or array or other scenarios it really depends on the type of list it seems - because they prove Count to be slower.

So I guess it depends on the type of list you're using!

(Just to point out, I put 2000+ objects in the List and count was still faster, opposite with other types)

Declare an empty two-dimensional array in Javascript?

An empty array is defined by omitting values, like so:

v=[[],[]]
a=[]
b=[1,2]
a.push(b)
b==a[0]

To add server using sp_addlinkedserver

I got it. It worked fine

Thank you for your help:

EXEC sp_addlinkedserver @server='Servername'

EXEC sp_addlinkedsrvlogin 'Servername', 'false', NULL, 'username', 'password@123'

How to change to an older version of Node.js

*NIX (Linux, OS X, ...)

Use n, an extremely simple Node version manager that can be installed via npm.

Say you want Node.js v0.10.x to build Atom.

npm install -g n   # Install n globally
n 0.10.33          # Install and use v0.10.33
Usage:
n                            # Output versions installed
n latest                     # Install or activate the latest node release
n stable                     # Install or activate the latest stable node release
n <version>                  # Install node <version>
n use <version> [args ...]   # Execute node <version> with [args ...]
n bin <version>              # Output bin path for <version>
n rm <version ...>           # Remove the given version(s)
n --latest                   # Output the latest node version available
n --stable                   # Output the latest stable node version available
n ls                         # Output the versions of node available

 

Windows

Use nvm-windows, it's like nvm but for Windows. Download and run the installer, then:

nvm install v0.10.33         # Install v0.10.33
nvm use v0.10.33             # Use v0.10.33
Usage:
nvm install [version]        # Download and install [version]
nvm uninstall [version]      # Uninstall [version]
nvm use [version]            # Switch to use [version]
nvm list                     # List installed versions

PHP: date function to get month of the current date

See http://php.net/date

date('m') or date('n') or date('F') ...

Update

m Numeric representation of a month, with leading zeros 01 through 12

n Numeric representation of a month, without leading zeros 1 through 12

F Alphabetic representation of a month January through December

....see the docs link for even more options.

Nullable property to entity field, Entity Framework through Code First

Just omit the [Required] attribute from the string somefield property. This will make it create a NULLable column in the db.

To make int types allow NULLs in the database, they must be declared as nullable ints in the model:

// an int can never be null, so it will be created as NOT NULL in db
public int someintfield { get; set; }

// to have a nullable int, you need to declare it as an int?
// or as a System.Nullable<int>
public int? somenullableintfield { get; set; }
public System.Nullable<int> someothernullableintfield { get; set; }

Show diff between commits

If you want to see the changes introduced with each commit, try "git log -p"

How to upsert (update or insert) in SQL Server 2005

Here is a useful article by Michael J. Swart on the matter, which covers different patterns and antipatterns for implementing UPSERT in SQL Server:
https://michaeljswart.com/2017/07/sql-server-upsert-patterns-and-antipatterns/

It addresses associated concurrency issues (primary key violations, deadlocks) - all of the answers provided here yet are considered antipatterns in the article (except for the @Bridge solution using triggers, which is not covered there).

Here is an extract from the article with the solution preferred by the author:

Inside a serializable transaction with lock hints:

CREATE PROCEDURE s_AccountDetails_Upsert ( @Email nvarchar(4000), @Etc nvarchar(max) )
AS 
  SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
  BEGIN TRAN

    IF EXISTS ( SELECT * FROM dbo.AccountDetails WITH (UPDLOCK) WHERE Email = @Email )

      UPDATE dbo.AccountDetails
         SET Etc = @Etc
       WHERE Email = @Email;

    ELSE 

      INSERT dbo.AccountDetails ( Email, Etc )
      VALUES ( @Email, @Etc );

  COMMIT

There is also related question with answers here on stackoverflow: Insert Update stored proc on SQL Server

How do I make a Mac Terminal pop-up/alert? Applescript?

Use this command to trigger the notification center notification from the terminal.

osascript -e 'display notification "Lorem ipsum dolor sit amet" with title "Title"'

Extract a substring from a string in Ruby using a regular expression

"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"

No need to use scan, if we need only one result.
No need to use Python's match, when we have Ruby's String[regexp,#].

See: http://ruby-doc.org/core/String.html#method-i-5B-5D

Note: str[regexp, capture] ? new_str or nil

How to configure encoding in Maven?

It seems people mix a content encoding with a built files/resources encoding. Having only maven properties is not enough. Having -Dfile.encoding=UTF8 not effective. To avoid having issues with encoding you should follow the following simple rules

  1. Set maven encoding, as described above:
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  1. Always set encoding explicitly, when work with files, strings, IO in your code. If you do not follow this rule, your application depend on the environment. The -Dfile.encoding=UTF8 exactly is responsible for run-time environment configuration, but we should not depend on it. If you have thousands of clients, it takes more effort to configure systems and to find issues because of it. You just have an additional dependency on it which you can avoid by setting it explicitly. Most methods in Java that use a default encoding are marked as deprecated because of it.

  2. Make sure the content, you are working with, also is in the same encoding, that you expect. If it is not, the previous steps do not matter! For instance a file will not be processed correctly, if its encoding is not UTF8 but you expect it. To check file encoding on Linux:

$ file --mime F_PRDAUFT.dsv

  1. Force clients/server set encoding explicitly in requests/responses, here are examples:
@Produces("application/json; charset=UTF-8")
@Consumes("application/json; charset=UTF-8")

Hope this will be useful to someone.

What is the difference between prefix and postfix operators?

i++ is post increment. The increment takes place after the value is returned.

how to move elasticsearch data from one server to another

If you can add the second server to cluster, you may do this:

  1. Add Server B to cluster with Server A
  2. Increment number of replicas for indices
  3. ES will automatically copy indices to server B
  4. Close server A
  5. Decrement number of replicas for indices

This will only work if number of replaces equal to number of nodes.

ubuntu "No space left on device" but there is tons of space

It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.

Try unmounting the overflow partition:

umount /tmp

or

umount overflow

How do I change column default value in PostgreSQL?

If you want to remove the default value constraint, you can do:

ALTER TABLE <table> ALTER COLUMN <column> DROP DEFAULT;

How do I call a specific Java method on a click/submit event of a specific button in JSP?

If you have web.xml then

HTML/JSP

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <input type="submit" name="button1" value="Button 1" />
</form>

web.xml

<servlet>
        <display-name>Servlet Name</display-name>
        <servlet-name>myservlet</servlet-name>
        <servlet-class>package.SomeController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>myservlet</servlet-name>
    <url-pattern>/myservlet</url-pattern>
</servlet-mapping>

Java SomeController.java

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Write your code below");
}

Quickest way to clear all sheet contents VBA

Technically, and from Comintern's accepted workaround, I believe you actually want to Delete all the Cells in the Sheet. Which removes Formatting (See footnote for exceptions), etc. as well as the Cells Contents. I.e. Sheets("Zeroes").Cells.Delete

Combined also with UsedRange, ScreenUpdating and Calculation skipping it should be nearly intantaneous:

Sub DeleteCells ()
    Application.Calculation = XlManual
    Application.ScreenUpdating = False
    Sheets("Zeroes").UsedRange.Delete
    Application.ScreenUpdating = True
    Application.Calculation = xlAutomatic
End Sub

Or if you prefer to respect the Calculation State Excel is currently in:

Sub DeleteCells ()
    Dim SaveCalcState
    SaveCalcState = Application.Calculation
    Application.Calculation = XlManual
    Application.ScreenUpdating = False
    Sheets("Zeroes").UsedRange.Delete
    Application.ScreenUpdating = True
    Application.Calculation = SaveCalcState
End Sub

Footnote: If formatting was applied for an Entire Column, then it is not deleted. This includes Font Colour, Fill Colour and Borders, the Format Category (like General, Date, Text, Etc.) and perhaps other properties too, but

Conditional formatting IS deleted, as is Entire Row formatting.

(Entire Column formatting is quite useful if you are importing raw data repeatedly to a sheet as it will conform to the Formats originally applied if a simple Paste-Values-Only type import is done.)

What is a simple command line program or script to backup SQL server databases?

You could use a VB Script I wrote exactly for this purpose: https://github.com/ezrarieben/mssql-backup-vbs/

Schedule a task in the "Task Scheduler" to execute the script as you like and it'll backup the entire DB to a BAK file and save it wherever you specify.

The I/O operation has been aborted because of either a thread exit or an application request

995 is an error reported by the IO Completion Port. The error comes since you try to continue read from the socket when it has most likely been closed.

Receiving 0 bytes from EndRecieve means that the socket has been closed, as does most exceptions that EndRecieve will throw.

You need to start dealing with those situations.

Never ever ignore exceptions, they are thrown for a reason.

Update

There is nothing that says that the server does anything wrong. A connection can be lost for a lot of reasons such as idle connection being closed by a switch/router/firewall, shaky network, bad cables etc.

What I'm saying is that you MUST handle disconnections. The proper way of doing so is to dispose the socket and try to connect a new one at certain intervals.

As for the receive callback a more proper way of handling it is something like this (semi pseudo code):

public void OnDataReceived(IAsyncResult asyn)
{
    BLCommonFunctions.WriteLogger(0, "In :- OnDataReceived", ref swReceivedLogWriter, strLogPath, 0);

    try
    {
        SocketPacket client = (SocketPacket)asyn.AsyncState;

        int bytesReceived = client.thisSocket.EndReceive(asyn); //Here error is coming
        if (bytesReceived == 0)
        {
          HandleDisconnect(client);
          return;
        }
    }
    catch (Exception err)
    {
       HandleDisconnect(client);
    }

    try
    {
        string strHEX = BLCommonFunctions.ByteArrToHex(theSockId.dataBuffer);                    

        //do your handling here
    }
    catch (Exception err)
    {
        // Your logic threw an exception. handle it accordinhly
    }

    try
    {
       client.thisSocket.BeginRecieve(.. all parameters ..);
    }
    catch (Exception err)
    {
       HandleDisconnect(client);
    }
}

the reason to why I'm using three catch blocks is simply because the logic for the middle one is different from the other two. Exceptions from BeginReceive/EndReceive usually indicates socket disconnection while exceptions from your logic should not stop the socket receiving.

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,

Another possibile solution is

$sContent = htmlspecialchars($sHTML);
$oDom = new DOMDocument();
$oDom->loadHTML($sContent);
echo html_entity_decode($oDom->saveHTML());

How do I abort/cancel TPL Tasks?

Aborting a Task is easily possible if you capture the thread in which the task is running in. Here is an example code to demonstrate this:

void Main()
{
    Thread thread = null;

    Task t = Task.Run(() => 
    {
        //Capture the thread
        thread = Thread.CurrentThread;

        //Simulate work (usually from 3rd party code)
        Thread.Sleep(1000);

        //If you comment out thread.Abort(), then this will be displayed
        Console.WriteLine("Task finished!");
    });

    //This is needed in the example to avoid thread being still NULL
    Thread.Sleep(10);

    //Cancel the task by aborting the thread
    thread.Abort();
}

I used Task.Run() to show the most common use-case for this - using the comfort of Tasks with old single-threaded code, which does not use the CancellationTokenSource class to determine if it should be canceled or not.

Retrieve filename from file descriptor in C

You can use readlink on /proc/self/fd/NNN where NNN is the file descriptor. This will give you the name of the file as it was when it was opened — however, if the file was moved or deleted since then, it may no longer be accurate (although Linux can track renames in some cases). To verify, stat the filename given and fstat the fd you have, and make sure st_dev and st_ino are the same.

Of course, not all file descriptors refer to files, and for those you'll see some odd text strings, such as pipe:[1538488]. Since all of the real filenames will be absolute paths, you can determine which these are easily enough. Further, as others have noted, files can have multiple hardlinks pointing to them - this will only report the one it was opened with. If you want to find all names for a given file, you'll just have to traverse the entire filesystem.

Evaluate a string with a switch in C++

You can't. Full stop.

switch is only for integral types, if you want to branch depending on a string you need to use if/else.

TypeLoadException says 'no implementation', but it is implemented

I encountered this error in a context where I was using Autofac and a lot of dynamic assembly loading.

While performing an Autofac resolution operation, the runtime would fail to load one of the assemblies. The error message complained that Method 'MyMethod' in type 'MyType' from assembly 'ImplementationAssembly' does not have an implementation. The symptoms occurred when running on a Windows Server 2012 R2 VM, but did not occur on Windows 10 or Windows Server 2016 VMs.

ImplementationAssembly referenced System.Collections.Immutable 1.1.37, and contained implementations of a IMyInterface<T1,T2> interface, which was defined in a separate DefinitionAssembly. DefinitionAssembly referenced System.Collections.Immutable 1.1.36.

The methods from IMyInterface<T1,T2> which were "not implemented" had parameters of type IImmutableDictionary<TKey, TRow>, which is defined in System.Collections.Immutable.

The actual copy of System.Collections.Immutable found in the program directory was version 1.1.37. On my Windows Server 2012 R2 VM, the GAC contained a copy of System.Collections.Immutable 1.1.36. On Windows 10 and Windows Server 2016, the GAC contained a copy of System.Collections.Immutable 1.1.37. The loading error only occurred when the GAC contained the older version of the DLL.

So, the root cause of the assembly load failure was the mismatching references to System.Collections.Immutable. The interface definition and implementation had identical-looking method signatures, but actually depended on different versions of System.Collections.Immutable, which meant that the runtime did not consider the implementation class to match the interface definition.

Adding the following binding redirect to my application config file fixed the issue:

<dependentAssembly>
        <assemblyIdentity name="System.Collections.Immutable" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.1.37.0" newVersion="1.1.37.0" />
</dependentAssembly>

How to get the day of week and the month of the year?

  function currentDate() {
      var monthNames = [ "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
                     "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" ];
      var days = ['SUNDAY','MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY'];                       
      var today = new Date();
      var dd   = today.getDate();
      var mm   = monthNames[today.getMonth()]; 
      var yyyy = today.getFullYear();
      var day  = days[today.getDay()];
      today = 'Date is :' + dd + '-' + mm + '-' + yyyy;
      document.write(today +"<br>");
      document.write('Day is : ' + day );
  }
  currentDate();

Are there dictionaries in php?

Normal array can serve as a dictionary data structure. In general it has multipurpose usage: array, list (vector), hash table, dictionary, collection, stack, queue etc.

$names = [
    'bob' => 27,
    'billy' => 43,
    'sam' => 76,
];

$names['bob'];

And because of wide design it gains no full benefits of specific data structure. You can implement your own dictionary by extending an ArrayObject or you can use SplObjectStorage class which is map (dictionary) implementation allowing objects to be assigned as keys.

Default value to a parameter while passing by reference in C++

void f(const double& v = *(double*) NULL)
{
  if (&v == NULL)
    cout << "default" << endl;
  else
    cout << "other " << v << endl;
}

React Checkbox not sending onChange

onChange will not call handleChange on mobile when using defaultChecked. As an alternative you can can use onClick and onTouchEnd.

<input onClick={this.handleChange} onTouchEnd={this.handleChange} type="checkbox" defaultChecked={!!this.state.complete} />;

Chrome - ERR_CACHE_MISS

This is an issue distinct to Chrome, but there are two paths you can take to fix it.

I noticed the error once I added this specific header to my PHP script.

header('Content-Type: application/json');

The error appears to be related to PHP sessions when sending response headers. So according to chromium bug report 424599, this was fixed and you can just update to a newer version of Chrome. But if for some reason you can't or don't want to update, the workaround would be to remove these response headers from your PHP script if possible (that's what I did because it wasn't required).

How to select a directory and store the location using tkinter in Python

This code may be helpful for you.

from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

It depends on the kind of test double you want to interact with:

  • If you don't use doNothing and you mock an object, the real method is not called
  • If you don't use doNothing and you spy an object, the real method is called

In other words, with mocking the only useful interactions with a collaborator are the ones that you provide. By default functions will return null, void methods do nothing.

RESTful Authentication via Spring

We managed to get this working exactly as described in the OP, and hopefully someone else can make use of the solution. Here's what we did:

Set up the security context like so:

<security:http realm="Protected API" use-expressions="true" auto-config="false" create-session="stateless" entry-point-ref="CustomAuthenticationEntryPoint">
    <security:custom-filter ref="authenticationTokenProcessingFilter" position="FORM_LOGIN_FILTER" />
    <security:intercept-url pattern="/authenticate" access="permitAll"/>
    <security:intercept-url pattern="/**" access="isAuthenticated()" />
</security:http>

<bean id="CustomAuthenticationEntryPoint"
    class="com.demo.api.support.spring.CustomAuthenticationEntryPoint" />

<bean id="authenticationTokenProcessingFilter"
    class="com.demo.api.support.spring.AuthenticationTokenProcessingFilter" >
    <constructor-arg ref="authenticationManager" />
</bean>

As you can see, we've created a custom AuthenticationEntryPoint, which basically just returns a 401 Unauthorized if the request wasn't authenticated in the filter chain by our AuthenticationTokenProcessingFilter.

CustomAuthenticationEntryPoint:

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException, ServletException {
        response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized: Authentication token was either missing or invalid." );
    }
}

AuthenticationTokenProcessingFilter:

public class AuthenticationTokenProcessingFilter extends GenericFilterBean {

    @Autowired UserService userService;
    @Autowired TokenUtils tokenUtils;
    AuthenticationManager authManager;

    public AuthenticationTokenProcessingFilter(AuthenticationManager authManager) {
        this.authManager = authManager;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        @SuppressWarnings("unchecked")
        Map<String, String[]> parms = request.getParameterMap();

        if(parms.containsKey("token")) {
            String token = parms.get("token")[0]; // grab the first "token" parameter

            // validate the token
            if (tokenUtils.validate(token)) {
                // determine the user based on the (already validated) token
                UserDetails userDetails = tokenUtils.getUserFromToken(token);
                // build an Authentication object with the user's info
                UsernamePasswordAuthenticationToken authentication = 
                        new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
                // set the authentication into the SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authManager.authenticate(authentication));         
            }
        }
        // continue thru the filter chain
        chain.doFilter(request, response);
    }
}

Obviously, TokenUtils contains some privy (and very case-specific) code and can't be readily shared. Here's its interface:

public interface TokenUtils {
    String getToken(UserDetails userDetails);
    String getToken(UserDetails userDetails, Long expiration);
    boolean validate(String token);
    UserDetails getUserFromToken(String token);
}

That ought to get you off to a good start. Happy coding. :)

How to cast from List<Double> to double[] in Java?

You can use primitive collections from Eclipse Collections and avoid boxing altogether.

DoubleList frameList = DoubleLists.mutable.empty();
double[] arr = frameList.toArray();

If you can't or don't want to initialize a DoubleList:

List<Double> frames = new ArrayList<>();
double[] arr = ListAdapter.adapt(frames).asLazy().collectDouble(each -> each).toArray();

Note: I am a contributor to Eclipse Collections.

How to execute a Ruby script in Terminal?

Just call: ruby your_program.rb

or

  • start your program with #!/usr/bin/env ruby,
  • make your file executable by running chmod +x your_program.rb
  • and do ./your_program.rb some_param

How do I update pip itself from inside my virtual environment?

In my case this worked from the terminal command line in Debian Stable

python3 -m pip install --upgrade pip

Auto start node.js server on boot

Copied directly from this answer:

You could write a script in any language you want to automate this (even using nodejs) and then just install a shortcut to that script in the user's %appdata%\Microsoft\Windows\Start Menu\Programs\Startup folder

Eclipse will not open due to environment variables

Eclipse and Java JDK (or JRE) must match regarding the BIT Version

For example:

32 Bit Eclipse won't work with 64 Bit Java!

32 Bit Eclipse needs 32 Bit Java!

Press Enter to move to next control

In a KeyPress event, if the user pressed Enter, call

SendKeys.Send("{TAB}")

Nicest way to implement automatically selecting the text on receiving focus is to create a subclass of TextBox in your project with the following override:

Protected Overrides Sub OnGotFocus(ByVal e As System.EventArgs)
    SelectionStart = 0
    SelectionLength = Text.Length
    MyBase.OnGotFocus(e)
End Sub

Then use this custom TextBox in place of the WinForms standard TextBox on all your Forms.

How to convert a Title to a URL slug in jQuery?

Combining a variety of elements from the answers here with normalize provides good coverage. Keep the order of operations to incrementally clean the url.

function clean_url(s) {
    return s.toString().normalize('NFD').replace(/[\u0300-\u036f]/g, "") //remove diacritics
            .toLowerCase()
            .replace(/\s+/g, '-') //spaces to dashes
            .replace(/&/g, '-and-') //ampersand to and
            .replace(/[^\w\-]+/g, '') //remove non-words
            .replace(/\-\-+/g, '-') //collapse multiple dashes
            .replace(/^-+/, '') //trim starting dash
            .replace(/-+$/, ''); //trim ending dash
}

normlize('NFD') breaks accented characters into their components, which are basic letters plus diacritics (the accent part). replace(/[\u0300-\u036f]/g, "") purges all the diacritics, leaving the basic letters by themselves. The rest is explained with inline comments.

Maven not found in Mac OSX mavericks

if you don't want to install homebrew (or any other package manager) just for installing maven, you can grab the binary from their site:

http://maven.apache.org/download.cgi

extract the content to a folder (e.g. /Applications/apache-maven-3.1.1) with

$ tar -xvf apache-maven-3.1.1-bin.tar.gz

and finally adjust your ~/.bash_profile with any texteditor you like to include

export M2_HOME=/Applications/apache-maven-3.1.1
export PATH=$PATH:$M2_HOME/bin

restart the terminal and test it with

$ mvn -version

Apache Maven 3.1.1 (0728685237757ffbf44136acec0402957f723d9a; 2013-09-17 17:22:22+0200)
Maven home: /Applications/apache-maven-3.1.1
Java version: 1.6.0_65, vendor: Apple Inc.
Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: de_DE, platform encoding: MacRoman
OS name: "mac os x", version: "10.9", arch: "x86_64", family: "mac"

npm not working after clearing cache

Try npm cache clean --force if it doesn't work then manually delete %appdata%\npm-cache folder.

It worked for me.