Programs & Examples On #Diagrams

Class Diagrams in VS 2017

Woo-hoo! It works with some hack!

According to this comment you need to:

  1. Manually edit Microsoft.CSharp.DesignTime.targets located in C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\Managed (for VS Community edition, modify path for other editions), append ClassDesigner value to ProjectCapability (right pane):File diff

  2. Restart VS.

  3. Manually create text file, say MyClasses.cd with following content: <?xml version="1.0" encoding="utf-8"?> <ClassDiagram MajorVersion="1" MinorVersion="1"> <Font Name="Segoe UI" Size="9" /> </ClassDiagram>

Bingo. Now you may open this file in VS. You will see error message "Object reference not set to an instance of object" once after VS starts, but diagram works.

Checked on VS 2017 Community Edition, v15.3.0 with .NETCore 2.0 app/project:

enter image description here

GitHub issue expected to fix in v15.5

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

From Object Explorer in SQL Server Management Studio, find your database and expand the node (click on the + sign beside your database). The first item from that expanded tree is Database Diagrams. Right-click on that and you'll see various tasks including creating a new database diagram. If you've never created one before, it'll ask if you want to install the components for creating diagrams. Click yes then proceed.

How to set ChartJS Y axis title?

chart.js supports this by defaul check the link. chartjs

you can set the label in the options attribute.

options object looks like this.

options = {
            scales: {
                yAxes: [
                    {
                        id: 'y-axis-1',
                        display: true,
                        position: 'left',
                        ticks: {
                            callback: function(value, index, values) {
                                return value + "%";
                            }
                        },
                        scaleLabel:{
                            display: true,
                            labelString: 'Average Personal Income',
                            fontColor: "#546372"
                        }
                    }   
                ]
            }
        };

The backend version is not supported to design database diagrams or tables

You only get that message if you try to use Designer or diagrams. If you use t-SQL it works fine:

Select * 

into newdb.dbo.newtable
from olddb.dbo.yourtable

where olddb.dbo.yourtable has been created in 2008 exactly as you want the table to be in 2012

git with development, staging and production branches

We do it differently. IMHO we do it in an easier way: in master we are working on the next major version.

Each larger feature gets its own branch (derived from master) and will be rebased (+ force pushed) on top of master regularly by the developer. Rebasing only works fine if a single developer works on this feature. If the feature is finished, it will be freshly rebased onto master and then the master fast-forwarded to the latest feature commit.

To avoid the rebasing/forced push one also can merge master changes regularly to the feature branch and if it's finished merge the feature branch into master (normal merge or squash merge). But IMHO this makes the feature branch less clear and makes it much more difficult to reorder/cleanup the commits.

If a new release is coming, we create a side-branch out of master, e.g. release-5 where only bugs get fixed.

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

Foreign key constraints: When to use ON UPDATE and ON DELETE

Addition to @MarkR answer - one thing to note would be that many PHP frameworks with ORMs would not recognize or use advanced DB setup (foreign keys, cascading delete, unique constraints), and this may result in unexpected behaviour.

For example if you delete a record using ORM, and your DELETE CASCADE will delete records in related tables, ORM's attempt to delete these related records (often automatic) will result in error.

How to use doxygen to create UML class diagrams from C++ source

Enterprise Architect will build a UML diagram from imported source code.

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

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

Tools to generate database tables diagram with Postgresql?

Quick solution I found was inside the pgAdmin program for windows. Under Tools menu there is a "Query Tool". Inside the Query Tool there is a Graphical Query Builder that can quickly show the database tables details. Good for a basic view

SQLite table constraint - unique on multiple columns

If you already have a table and can't/don't want to recreate it for whatever reason, use indexes:

CREATE UNIQUE INDEX my_index ON my_table(col_1, col_2);

Explanation of the UML arrows

Here is simplified tutorial:

Practical UML

For more I recommend to get some literature.

How do I calculate the normal vector of a line segment?

Another way to think of it is to calculate the unit vector for a given direction and then apply a 90 degree counterclockwise rotation to get the normal vector.

The matrix representation of the general 2D transformation looks like this:

x' = x cos(t) - y sin(t)
y' = x sin(t) + y cos(t)

where (x,y) are the components of the original vector and (x', y') are the transformed components.

If t = 90 degrees, then cos(90) = 0 and sin(90) = 1. Substituting and multiplying it out gives:

x' = -y
y' = +x

Same result as given earlier, but with a little more explanation as to where it comes from.

Tools for creating Class Diagrams

I use StarUML. It works quite good.

How do I change the owner of a SQL Server database?

to change the object owner try the following

EXEC sp_changedbowner 'sa'

that however is not your problem, to see diagrams the Da Vinci Tools objects have to be created (you will see tables and procs that start with dt_) after that

What is the difference between a data flow diagram and a flow chart?

Other answers have gone over the basics of what each thing is. At the higher level, a flowchart is a design level tool, while DFDs are more analysis.

DFDs have some nice features. Since they show the flow of data, some things become more obvious when charted this way: some data is only used by a few routines, some routines use only some bits of data, some routines touch everything. Seeing that up front helps organize, restructuring, and planning.

A follow-on worth exploring is the Event-Response Diagram, which is basically a DFD only showing process and data needed to process an "event", meaning something triggered externally (customer makes payment, etc.).

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

These are class stereotypes used in analysis.

  • boundary classes are ones at the boundary of the system - the classes that you or other systems interact with

  • entity classes classes are your typical business entities like "person" and "bank account"

  • control classes implement some business logic or other

What's the best way to generate a UML diagram from Python source code?

The SPE IDE has built-in UML creator. Just open the files in SPE and click on the UML tab.

I don't know how comprhensive it is for your needs, but it doesn't require any additional downloads or configurations to use.

How to generate UML diagrams (especially sequence diagrams) from Java code?

Using IntelliJ IDEA. To generate class diagram select package and press Ctrl + Alt + U:enter image description here

By default, it displays only class names and not all dependencies. To change it: right click -> Show Categories... and Show dependencies: enter image description here

To genarate dependencies diagram (UML Deployment diagram) and you use maven go View -> Tool Windows -> Maven Projects and press Ctrl + Alt + U: enter image description here

The result: enter image description here

Also it is possible to generate more others diagrams. See documentation.

Where can I find decent visio templates/diagrams for software architecture?

There should be templates already included in Visio 2007 for software architecture but you might want to check out Visio 2007 templates.

What's the best UML diagramming tool?

I advice to use Pacestar UML Diagrammer. It helps you generate UML 2.0 diagrams quickly, easily, flexible AND commonly understood notation.

I used it in many projects and I'm very satisfied. And too it doesn't use much of memory and space just 6 Mo of Hard Disk.

And the most feature that I like it very much is that I can copy diagrams from the editor and paste them in MS Word... so when I need to edit a specific diagram, just I click on and it will be opened in the editor and by closing it, the updates had been done in MS Word document.

back button callback in navigationController in iOS

In my opinion the best solution.

- (void)didMoveToParentViewController:(UIViewController *)parent
{
    if (![parent isEqual:self.parentViewController]) {
         NSLog(@"Back pressed");
    }
}

But it only works with iOS5+

Remove HTML tags from a String

You might want to replace <br/> and </p> tags with newlines before stripping the HTML to prevent it becoming an illegible mess as Tim suggests.

The only way I can think of removing HTML tags but leaving non-HTML between angle brackets would be check against a list of HTML tags. Something along these lines...

replaceAll("\\<[\s]*tag[^>]*>","")

Then HTML-decode special characters such as &amp;. The result should not be considered to be sanitized.

What is sys.maxint in Python 3?

Python 3 ints do not have a maximum.

If your purpose is to determine the maximum size of an int in C when compiled the same way Python was, you can use the struct module to find out:

>>> import struct
>>> platform_c_maxint = 2 ** (struct.Struct('i').size * 8 - 1) - 1

If you are curious about the internal implementation details of Python 3 int objects, Look at sys.int_info for bits per digit and digit size details. No normal program should care about these.

"SDK Platform Tools component is missing!"

Here is another alternative. Download it directly here: http://androidsdkoffline.blogspot.com.ng/p/android-sdk-tools.html.

The present version as of this writing is Android SDK Tools 25.1.7. Unzip it when the download is done and place it in your sdk folder. You can then download other missing files directly from the SDK Manager.

Python: How to convert datetime format?

@Tim's answer only does half the work -- that gets it into a datetime.datetime object.

To get it into the string format you require, you use datetime.strftime:

print(datetime.strftime('%b %d,%Y'))

How can I get the intersection, union, and subset of arrays in Ruby?

Utilizing the fact that you can do set operations on arrays by doing &(intersection), -(difference), and |(union).

Obviously I didn't implement the MultiSet to spec, but this should get you started:

class MultiSet
  attr_accessor :set
  def initialize(set)
    @set = set
  end
  # intersection
  def &(other)
    @set & other.set
  end
  # difference
  def -(other)
    @set - other.set
  end
  # union
  def |(other)
    @set | other.set
  end
end

x = MultiSet.new([1,1,2,2,3,4,5,6])
y = MultiSet.new([1,3,5,6])

p x - y # [2,2,4]
p x & y # [1,3,5,6]
p x | y # [1,2,3,4,5,6]

CSS rounded corners in IE8

As Internet Explorer doesn't natively support rounded corners. So a better cross-browser way to handle it would be to use rounded-corner images at the corners. Many famous websites use this approach.

You can also find rounded image generators around the web. One such link is http://www.generateit.net/rounded-corner/

jQuery checkbox change and click event

get radio value by name

 $('input').on('className', function(event){
        console.log($(this).attr('name'));
        if($(this).attr('name') == "worker")
            {
                resetAll();                 
            }
    });

How to pull specific directory with git

  1. cd into the top of your repo copy
  2. git fetch
  3. git checkout HEAD path/to/your/dir/or/file

    • Where "path/..." in (3) starts at the directory just below the repo root containing your ".../file"

    • NOTE that instead of "HEAD", the hash code of a specific commit may be used, and then you will get the revision (file) or revisions (dir) specific to that commit.

How to set my phpmyadmin user session to not time out so quickly?

Once you're logged into phpmyadmin look on the top navigation for "Settings" and click that then:

"Features" >

...and you'll find "Login cookie validity" which is typically set to 1440.

Unfortunately changing it through the UI means that the changes don't persist between logins.

How to make a char string from a C macro's value?

He who is Shy* gave you the germ of an answer, but only the germ. The basic technique for converting a value into a string in the C pre-processor is indeed via the '#' operator, but a simple transliteration of the proposed solution gets a compilation error:

#define TEST_FUNC test_func
#define TEST_FUNC_NAME #TEST_FUNC

#include <stdio.h>
int main(void)
{
    puts(TEST_FUNC_NAME);
    return(0);
}

The syntax error is on the 'puts()' line - the problem is a 'stray #' in the source.

In section 6.10.3.2 of the C standard, 'The # operator', it says:

Each # preprocessing token in the replacement list for a function-like macro shall be followed by a parameter as the next preprocessing token in the replacement list.

The trouble is that you can convert macro arguments to strings -- but you can't convert random items that are not macro arguments.

So, to achieve the effect you are after, you most certainly have to do some extra work.

#define FUNCTION_NAME(name) #name
#define TEST_FUNC_NAME  FUNCTION_NAME(test_func)

#include <stdio.h>

int main(void)
{
    puts(TEST_FUNC_NAME);
    return(0);
}

I'm not completely clear on how you plan to use the macros, and how you plan to avoid repetition altogether. This slightly more elaborate example might be more informative. The use of a macro equivalent to STR_VALUE is an idiom that is necessary to get the desired result.

#define STR_VALUE(arg)      #arg
#define FUNCTION_NAME(name) STR_VALUE(name)

#define TEST_FUNC      test_func
#define TEST_FUNC_NAME FUNCTION_NAME(TEST_FUNC)

#include <stdio.h>

static void TEST_FUNC(void)
{
    printf("In function %s\n", TEST_FUNC_NAME);
}

int main(void)
{
    puts(TEST_FUNC_NAME);
    TEST_FUNC();
    return(0);
}

* At the time when this answer was first written, shoosh's name used 'Shy' as part of the name.

Can anyone explain IEnumerable and IEnumerator to me?

An understanding of the Iterator pattern will be helpful for you. I recommend reading the same.

Iterator Pattern

At a high level the iterator pattern can be used to provide a standard way of iterating through collections of any type. We have 3 participants in the iterator pattern, the actual collection (client), the aggregator and the iterator. The aggregate is an interface/abstract class that has a method that returns an iterator. Iterator is an interface/abstract class that has methods allowing us to iterate through a collection.

In order to implement the pattern we first need to implement an iterator to produce a concrete that can iterate over the concerned collection (client) Then the collection (client) implements the aggregator to return an instance of the above iterator.

Here is the UML diagram Iterator Pattern

So basically in c#, IEnumerable is the abstract aggregate and IEnumerator is the abstract Iterator. IEnumerable has a single method GetEnumerator that is responsible for creating an instance of IEnumerator of the desired type. Collections like Lists implement the IEnumerable.

Example. Lets suppose that we have a method getPermutations(inputString) that returns all the permutations of a string and that the method returns an instance of IEnumerable<string>

In order to count the number of permutations we could do something like the below.

 int count = 0;
        var permutations = perm.getPermutations(inputString);
        foreach (string permutation in permutations)
        {
            count++;
        }

The c# compiler more or less converts the above to

using (var permutationIterator = perm.getPermutations(input).GetEnumerator())
        {
            while (permutationIterator.MoveNext())
            {
                count++;
            }
        }

If you have any questions please don't hesitate to ask.

"401 Unauthorized" on a directory

  • Open IIS
  • select site where you are facing the problem

  • Select Below

enter image description here

- Right click on Anonymous Authentication and click on edit and follow below

enter image description here

Join a list of items with different types as string in Python

Maybe you do not need numbers as strings, just do:

functaulu = [munfunc(arg) for arg in range(loppu)]

Later if you need it as string you can do it with string or with format string:

print "Vastaus5 = %s" % functaulu[5]

Using jq to parse and display multiple fields in a json serially

I recommend using String Interpolation:

jq '.users[] | "\(.first) \(.last)"'

reference

The easiest way to replace white spaces with (underscores) _ in bash

You can do it using only the shell, no need for tr or sed

$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test

Activity transition in Android

Before Starting your Intent:

ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(AlbumListActivity.this);
startActivity(intent, options.toBundle());

This gives Default Animation to your Activity Transition.

Is it possible to validate the size and type of input=file in html5

if your using php for the backend maybe you can use this code.

// Validate image file size
if (($_FILES["file-input"]["size"] > 2000000)) {
    $msg = "Image File Size is Greater than 2MB.";
    header("Location: ../product.php?error=$msg");
    exit();
}  

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

Hope this will help someone... Here's a little PHP script I wrote in case you need to copy some columns but not others, and/or the columns are not in the same order on both tables. As long as the columns are named the same, this will work. So if table A has [userid, handle, something] and tableB has [userID, handle, timestamp], then you'd "SELECT userID, handle, NOW() as timestamp FROM tableA", then get the result of that, and pass the result as the first parameter to this function ($z). $toTable is a string name for the table you're copying to, and $link_identifier is the db you're copying to. This is relatively fast for small sets of data. Not suggested that you try to move more than a few thousand rows at a time this way in a production setting. I use this primarily to back up data collected during a session when a user logs out, and then immediately clear the data from the live db to keep it slim.

 function mysql_multirow_copy($z,$toTable,$link_identifier) {
            $fields = "";
            for ($i=0;$i<mysql_num_fields($z);$i++) {
                if ($i>0) {
                    $fields .= ",";
                }
                $fields .= mysql_field_name($z,$i);
            }
            $q = "INSERT INTO $toTable ($fields) VALUES";
            $c = 0;
            mysql_data_seek($z,0); //critical reset in case $z has been parsed beforehand. !
            while ($a = mysql_fetch_assoc($z)) {
                foreach ($a as $key=>$as) {
                    $a[$key] = addslashes($as);
                    next ($a);
                }
                if ($c>0) {
                    $q .= ",";
                }
                $q .= "('".implode(array_values($a),"','")."')";
                $c++;
            }
            $q .= ";";
            $z = mysql_query($q,$link_identifier);
            return ($q);
        }

Change Bootstrap input focus blue glow

Here are the changes if you want Chrome to show the platform default "yellow" outline.

textarea:focus, input[type="text"]:focus, input[type="password"]:focus, input[type="datetime"]:focus, input[type="datetime-local"]:focus, input[type="date"]:focus, input[type="month"]:focus, input[type="time"]:focus, input[type="week"]:focus, input[type="number"]:focus, input[type="email"]:focus, input[type="url"]:focus, input[type="search"]:focus, input[type="tel"]:focus, input[type="color"]:focus, .uneditable-    input:focus {
    border-color: none;
    box-shadow: none;
    -webkit-box-shadow: none;
    outline: -webkit-focus-ring-color auto 5px;
}

Firebase (FCM) how to get token

Settings.Secure.getString(getContentResolver(),
                     Settings.Secure.ANDROID_ID);

Number of days between two dates in Joda-Time

you can use LocalDate:

Days.daysBetween(new LocalDate(start), new LocalDate(end)).getDays() 

Memcache Vs. Memcached

(PartlyStolen from ServerFault)

I think that both are functionally the same, but they simply have different authors, and the one is simply named more appropriately than the other.


Here is a quick backgrounder in naming conventions (for those unfamiliar), which explains the frustration by the question asker: For many *nix applications, the piece that does the backend work is called a "daemon" (think "service" in Windows-land), while the interface or client application is what you use to control or access the daemon. The daemon is most often named the same as the client, with the letter "d" appended to it. For example "imap" would be a client that connects to the "imapd" daemon.

This naming convention is clearly being adhered to by memcache when you read the introduction to the memcache module (notice the distinction between memcache and memcached in this excerpt):

Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

The Memcache module also provides a session handler (memcache).

More information about memcached can be found at » http://www.danga.com/memcached/.

The frustration here is caused by the author of the PHP extension which was badly named memcached, since it shares the same name as the actual daemon called memcached. Notice also that in the introduction to memcached (the php module), it makes mention of libmemcached, which is the shared library (or API) that is used by the module to access the memcached daemon:

memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

This extension uses libmemcached library to provide API for communicating with memcached servers. It also provides a session handler (memcached).

Information about libmemcached can be found at » http://tangent.org/552/libmemcached.html.

Regex to check with starts with http://, https:// or ftp://

Unless there is some compelling reason to use a regex, I would just use String.startsWith:

bool matches = test.startsWith("http://")
            || test.startsWith("https://") 
            || test.startsWith("ftp://");

I wouldn't be surprised if this is faster, too.

How do I insert a JPEG image into a python Tkinter window?

import tkinter as tk
from tkinter import ttk
from PIL import Image,  ImageTk
win = tk. Tk()
image1 = Image. open("Aoran. jpg")
image2 =  ImageTk. PhotoImage(image1)
image_label = ttk. Label(win , image =.image2)
image_label.place(x = 0 , y = 0)
win.mainloop()

Init function in javascript and how it works

I can't believe no-one has answered the ops question!

The last set of brackets are used for passing in the parameters to the anonymous function. So, the following example creates a function, then runs it with the x=5 and y=8

(function(x,y){
    //code here
})(5,8)

This may seem not so useful, but it has its place. The most common one I have seen is

(function($){
    //code here
})(jQuery)

which allows for jQuery to be in compatible mode, but you can refer to it as "$" within the anonymous function.

Visual studio equivalent of java System.out

Use Either Debug.WriteLine() or Trace.WriteLine(). If in release mode, only the latter will appear in the output window, in debug mode, both will.

How to remove outliers from a dataset

Outliers are quite similar to peaks, so a peak detector can be useful for identifying outliers. The method described here has quite good performance using z-scores. The animation part way down the page illustrates the method signaling on outliers, or peaks.

Peaks are not always the same as outliers, but they're similar frequently.

An example is shown here: This dataset is read from a sensor via serial communications. Occasional serial communication errors, sensor error or both lead to repeated, clearly erroneous data points. There is no statistical value in these point. They are arguably not outliers, they are errors. The z-score peak detector was able to signal on spurious data points and generated a clean resulting dataset: enter image description here

How do I check if a string contains another string in Objective-C?

For iOS 8.0+ and macOS 10.10+, you can use NSString's native containsString:.

For older versions of iOS and macOS, you can create your own (obsolete) category for NSString:

@interface NSString ( SubstringSearch )
    - (BOOL)containsString:(NSString *)substring;
@end

// - - - - 

@implementation NSString ( SubstringSearch )

- (BOOL)containsString:(NSString *)substring
{    
    NSRange range = [self rangeOfString : substring];
    BOOL found = ( range.location != NSNotFound );
    return found;
}

@end

Note: Observe Daniel Galasko's comment below regarding naming

How do I redirect in expressjs while passing some context?

I had to find another solution because none of the provided solutions actually met my requirements, for the following reasons:

  • Query strings: You may not want to use query strings because the URLs could be shared by your users, and sometimes the query parameters do not make sense for a different user. For example, an error such as ?error=sessionExpired should never be displayed to another user by accident.

  • req.session: You may not want to use req.session because you need the express-session dependency for this, which includes setting up a session store (such as MongoDB), which you may not need at all, or maybe you are already using a custom session store solution.

  • next(): You may not want to use next() or next("router") because this essentially just renders your new page under the original URL, it's not really a redirect to the new URL, more like a forward/rewrite, which may not be acceptable.

So this is my fourth solution that doesn't suffer from any of the previous issues. Basically it involves using a temporary cookie, for which you will have to first install cookie-parser. Obviously this means it will only work where cookies are enabled, and with a limited amount of data.

Implementation example:

var cookieParser = require("cookie-parser");

app.use(cookieParser());

app.get("/", function(req, res) {
    var context = req.cookies["context"];
    res.clearCookie("context", { httpOnly: true });
    res.render("home.jade", context); // Here context is just a string, you will have to provide a valid context for your template engine
});

app.post("/category", function(req, res) {
    res.cookie("context", "myContext", { httpOnly: true });
    res.redirect("/");
}

How to split data into 3 sets (train, validation and test)?

In the case of supervised learning, you may want to split both X and y (where X is your input and y the ground truth output). You just have to pay attention to shuffle X and y the same way before splitting.

Here, either X and y are in the same dataframe, so we shuffle them, separate them and apply the split for each (just like in chosen answer), or X and y are in two different dataframes, so we shuffle X, reorder y the same way as the shuffled X and apply the split to each.

# 1st case: df contains X and y (where y is the "target" column of df)
df_shuffled = df.sample(frac=1)
X_shuffled = df_shuffled.drop("target", axis = 1)
y_shuffled = df_shuffled["target"]

# 2nd case: X and y are two separated dataframes
X_shuffled = X.sample(frac=1)
y_shuffled = y[X_shuffled.index]

# We do the split as in the chosen answer
X_train, X_validation, X_test = np.split(X_shuffled, [int(0.6*len(X)),int(0.8*len(X))])
y_train, y_validation, y_test = np.split(y_shuffled, [int(0.6*len(X)),int(0.8*len(X))])

How can I brew link a specific version?

The usage info:

Usage: brew switch <formula> <version>

Example:

brew switch mysql 5.5.29

You can find the versions installed on your system with info.

brew info mysql

And to see the available versions to install, you can provide a dud version number, as brew will helpfully respond with the available version numbers:

brew switch mysql 0

Update (15.10.2014):

The brew versions command has been removed from brew, but, if you do wish to use this command first run brew tap homebrew/boneyard.

The recommended way to install an old version is to install from the homebrew/versions repo as follows:

$ brew tap homebrew/versions
$ brew install mysql55

For detailed info on all the ways to install an older version of a formula read this answer.

"query function not defined for Select2 undefined error"

if (typeof(opts.query) !== "function") {
    throw "query function not defined for Select2 " + opts.element.attr("id");
}

This is thrown becase query does not exist in options. Internally there is a check maintained which requires either of the following for parameters

  • ajax
  • tags
  • data
  • query

So you just need to provide one of these 4 options to select2 and it should work as expected.

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

I'm using tsql on a Linux/UNIX infrastructure to access MSSQL databases. Here's a simple shell script to dump a table to a file:

#!/usr/bin/ksh
#
#.....
(
tsql -S {database} -U {user} -P {password} <<EOF
select * from {table}
go
quit
EOF
) >{output_file.dump}

Add a new element to an array without specifying the index in Bash

$ declare -a arr
$ arr=("a")
$ arr=("${arr[@]}" "new")
$ echo ${arr[@]}
a new
$ arr=("${arr[@]}" "newest")
$ echo ${arr[@]}
a new newest

A JRE or JDK must be available in order to run Eclipse. No JVM was found after searching the following locations

I had this problem too on a win7 machine. I wanted to update the jre with a jdk. So i deleted the jre folder and downloaded and unzipped the new jdk. The issue was i manually deleted the jre folder, when instead i should've uninstalled it. This leaves a bunch of registry entries that still point to the old jre. Somehow eclipse still wants to use the old jre. I couldn't uninstall the old java vm, i kept getting this error:

Error 1723. There is a problem with this Windows Installer package. A DLL required for this install to complete could not be run. Contact your support personnel or package vendor

So i had to use this MS utility to fix the uninstall:

http://support.microsoft.com/kb/2438651/

Then i had to install again the vm. I installed to the same location the original one was at, to avoid losing another hour! After that eclipse started correctly.

Julio

How to make div's percentage width relative to parent div and not viewport

Specifying a non-static position, e.g., position: absolute/relative on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

_x000D_
_x000D_
#outer {_x000D_
  min-width: 2000px; _x000D_
  min-height: 1000px; _x000D_
  background: #3e3e3e; _x000D_
  position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
  left: 1%; _x000D_
  top: 45px; _x000D_
  width: 50%; _x000D_
  height: auto; _x000D_
  position: absolute; _x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
  background: #efffef;_x000D_
  position: absolute; _x000D_
  height: 400px; _x000D_
  right: 0px; _x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="inner">_x000D_
    <div id="inner-inner"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Convert pyQt UI to python

I'm not sure if PyQt does have a script like this, but after you install PySide there is a script in pythons script directory "uic.py". You can use this script to convert a .ui file to a .py file:

python uic.py input.ui -o output.py -x

How can you debug a CORS request with cURL?

The bash script "corstest" below works for me. It is based on Jun's comment above.

usage

corstest [-v] url

examples

./corstest https://api.coindesk.com/v1/bpi/currentprice.json
https://api.coindesk.com/v1/bpi/currentprice.json Access-Control-Allow-Origin: *

the positive result is displayed in green

./corstest https://github.com/IonicaBizau/jsonrequest
https://github.com/IonicaBizau/jsonrequest does not support CORS
you might want to visit https://enable-cors.org/ to find out how to enable CORS

the negative result is displayed in red and blue

the -v option will show the full curl headers

corstest

#!/bin/bash
# WF 2018-09-20
# https://stackoverflow.com/a/47609921/1497139

#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'  
red='\033[0;31m'  
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'

#
# a colored message 
#   params:
#     1: l_color - the color of the message
#     2: l_msg - the message to display
#
color_msg() {
  local l_color="$1"
  local l_msg="$2"
  echo -e "${l_color}$l_msg${endColor}"
}


#
# show the usage
#
usage() {
  echo "usage: [-v] $0 url"
  echo "  -v |--verbose: show curl result" 
  exit 1 
}

if [ $# -lt 1 ]
then
  usage
fi

# commandline option
while [  "$1" != ""  ]
do
  url=$1
  shift

  # optionally show usage
  case $url in      
    -v|--verbose)
       verbose=true;
       ;;          
  esac
done  


if [ "$verbose" = "true" ]
then
  curl -s -X GET $url -H 'Cache-Control: no-cache' --head 
fi
origin=$(curl -s -X GET $url -H 'Cache-Control: no-cache' --head | grep -i access-control)


if [ $? -eq 0 ]
then
  color_msg $green "$url $origin"
else
  color_msg $red "$url does not support CORS"
  color_msg $blue "you might want to visit https://enable-cors.org/ to find out how to enable CORS"
fi

Int to byte array

Marc's answer is of course the right answer. But since he mentioned the shift operators and unsafe code as an alternative. I would like to share a less common alternative. Using a struct with Explicit layout. This is similar in principal to a C/C++ union.

Here is an example of a struct that can be used to get to the component bytes of the Int32 data type and the nice thing is that it is two way, you can manipulate the byte values and see the effect on the Int.

  using System.Runtime.InteropServices;

  [StructLayout(LayoutKind.Explicit)]
  struct Int32Converter
  {
    [FieldOffset(0)] public int Value;
    [FieldOffset(0)] public byte Byte1;
    [FieldOffset(1)] public byte Byte2;
    [FieldOffset(2)] public byte Byte3;
    [FieldOffset(3)] public byte Byte4;

    public Int32Converter(int value)
    {
      Byte1 = Byte2 = Byte3 = Byte4 = 0;
      Value = value;
    }

    public static implicit operator Int32(Int32Converter value)
    {
      return value.Value;
    }

    public static implicit operator Int32Converter(int value)
    {
      return new Int32Converter(value);
    }
  }

The above can now be used as follows

 Int32Converter i32 = 256;
 Console.WriteLine(i32.Byte1);
 Console.WriteLine(i32.Byte2);
 Console.WriteLine(i32.Byte3);
 Console.WriteLine(i32.Byte4);

 i32.Byte2 = 2;
 Console.WriteLine(i32.Value);

Of course the immutability police may not be excited about the last possiblity :)

Call Javascript onchange event by programmatically changing textbox value

You can put it in a different class and then call a function. This works when ajax refresh

$(document).on("change", ".inputQty", function(e) {

//Call a function(input,input);
});

Round a floating-point number down to the nearest integer?

a lot of people say to use int(x), and this works ok for most cases, but there is a little problem. If OP's result is:

x = 1.9999999999999999

it will round to

x = 2

after the 16th 9 it will round. This is not a big deal if you are sure you will never come across such thing. But it's something to keep in mind.

android asynctask sending callbacks to ui

I will repeat what the others said, but will just try to make it simpler...

First, just create the Interface class

public interface PostTaskListener<K> {
    // K is the type of the result object of the async task 
    void onPostTask(K result);
}

Second, create the AsyncTask (which can be an inner static class of your activity or fragment) that uses the Interface, by including a concrete class. In the example, the PostTaskListener is parameterized with String, which means it expects a String class as a result of the async task.

public static class LoadData extends AsyncTask<Void, Void, String> {

    private PostTaskListener<String> postTaskListener;

    protected LoadData(PostTaskListener<String> postTaskListener){
        this.postTaskListener = postTaskListener;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (result != null && postTaskListener != null)
            postTaskListener.onPostTask(result);
    }
}

Finally, the part where your combine your logic. In your activity / fragment, create the PostTaskListener and pass it to the async task. Here is an example:

...
PostTaskListener<String> postTaskListener = new PostTaskListener<String>() {
    @Override
    public void onPostTask(String result) {
        //Your post execution task code
    }
}

// Create the async task and pass it the post task listener.
new LoadData(postTaskListener);

Done!

load and execute order of scripts

If you aren't dynamically loading scripts or marking them as defer or async, then scripts are loaded in the order encountered in the page. It doesn't matter whether it's an external script or an inline script - they are executed in the order they are encountered in the page. Inline scripts that come after external scripts are held until all external scripts that came before them have loaded and run.

Async scripts (regardless of how they are specified as async) load and run in an unpredictable order. The browser loads them in parallel and it is free to run them in whatever order it wants.

There is no predictable order among multiple async things. If one needed a predictable order, then it would have to be coded in by registering for load notifications from the async scripts and manually sequencing javascript calls when the appropriate things are loaded.

When a script tag is inserted dynamically, how the execution order behaves will depend upon the browser. You can see how Firefox behaves in this reference article. In a nutshell, the newer versions of Firefox default a dynamically added script tag to async unless the script tag has been set otherwise.

A script tag with async may be run as soon as it is loaded. In fact, the browser may pause the parser from whatever else it was doing and run that script. So, it really can run at almost any time. If the script was cached, it might run almost immediately. If the script takes awhile to load, it might run after the parser is done. The one thing to remember with async is that it can run anytime and that time is not predictable.

A script tag with defer waits until the entire parser is done and then runs all scripts marked with defer in the order they were encountered. This allows you to mark several scripts that depend upon one another as defer. They will all get postponed until after the document parser is done, but they will execute in the order they were encountered preserving their dependencies. I think of defer like the scripts are dropped into a queue that will be processed after the parser is done. Technically, the browser may be downloading the scripts in the background at any time, but they won't execute or block the parser until after the parser is done parsing the page and parsing and running any inline scripts that are not marked defer or async.

Here's a quote from that article:

script-inserted scripts execute asynchronously in IE and WebKit, but synchronously in Opera and pre-4.0 Firefox.

The relevant part of the HTML5 spec (for newer compliant browsers) is here. There is a lot written in there about async behavior. Obviously, this spec doesn't apply to older browsers (or mal-conforming browsers) whose behavior you would probably have to test to determine.

A quote from the HTML5 spec:

Then, the first of the following options that describes the situation must be followed:

If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element does not have a src attribute, and the element has been flagged as "parser-inserted", and the Document of the HTML parser or XML parser that created the script element has a style sheet that is blocking scripts The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, does not have an async attribute, and does not have the "force-async" flag set The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must run the following steps:

If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but abort these steps without executing the script yet.

Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.

Remove the first element from this list of scripts that will execute in order as soon as possible.

If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled execution.

If the element has a src attribute The element must be added to the set of scripts that will execute as soon as possible of the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must execute the script block and then remove the element from the set of scripts that will execute as soon as possible.

Otherwise The user agent must immediately execute the script block, even if other scripts are already executing.


What about Javascript module scripts, type="module"?

Javascript now has support for module loading with syntax like this:

<script type="module">
  import {addTextToBody} from './utils.mjs';

  addTextToBody('Modules are pretty cool.');
</script>

Or, with src attribute:

<script type="module" src="http://somedomain.com/somescript.mjs">
</script>

All scripts with type="module" are automatically given the defer attribute. This downloads them in parallel (if not inline) with other loading of the page and then runs them in order, but after the parser is done.

Module scripts can also be given the async attribute which will run inline module scripts as soon as possible, not waiting until the parser is done and not waiting to run the async script in any particular order relative to other scripts.

There's a pretty useful timeline chart that shows fetch and execution of different combinations of scripts, including module scripts here in this article: Javascript Module Loading.

How to play videos in android from assets folder or raw folder?

PlayVideoActivity.java:

public class PlayVideoActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_video);

        VideoView videoView = (VideoView) findViewById(R.id.video_view);
        MediaController mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        videoView.setMediaController(mediaController);
        videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.documentariesandyou));
        videoView.start();
    }
}

activity_play_video.xml:

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

    <VideoView
        android:id="@+id/video_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </VideoView>

</LinearLayout>

How do I calculate someone's age in Java?

I simply use the milliseconds in a year constant value to my advantage:

Date now = new Date();
long timeBetween = now.getTime() - age.getTime();
double yearsBetween = timeBetween / 3.15576e+10;
int age = (int) Math.floor(yearsBetween);

Hide particular div onload and then show div after click

$(document).ready(function() {
    $('#div2').hide(0);
    $('#preview').on('click', function() {
        $('#div1').hide(300, function() { // first hide div1
            // then show div2
            $('#div2').show(300);
        });     
    });
});

You missed # before div2

Working Sample

My Routes are Returning a 404, How can I Fix Them?

Have you tried to check if

http://localhost/mysite/public/index.php/user 

was working? If so then make sure all your path's folders don't have any uppercase letters. I had the same situation and converting letters to lower case helped.

How to set a hidden value in Razor

If I understand correct you will have something like this:

<input value="default" id="sth" name="sth" type="hidden">

And to get it you have to write:

@Html.HiddenFor(m => m.sth, new { Value = "default" })

for Strongly-typed view.

Center text in div?

You may try to use in your CSS the property vertical-align in order to center it verticaly

div {  
    vertical-align:middle;  
}

if it's a size problem, please notice that 2 text lines and a padding style have great chance to have a height superior to 30px.

For example, if your font size is 12 px and your div padding is 5 px, a one text line div height will be 5px (padding-top) + 12px + 5 px (padding-bottom) = 22px < 30px so no problem,

With a 2 text lines div, it will be 5px +12px *2 (2 lines) + 5px = 34px > 30px and your div height will be automatically changed.

Try either to increase your div height (maybe 40px) or to reduce your padding.

Hope it will help

Matplotlib transparent line plots

Plain and simple:

plt.plot(x, y, 'r-', alpha=0.7)

(I know I add nothing new, but the straightforward answer should be visible).

Print a list in reverse order with range()?

No sense to use reverse because the range method can return reversed list.

When you have iteration over n items and want to replace order of list returned by range(start, stop, step) you have to use third parameter of range which identifies step and set it to -1, other parameters shall be adjusted accordingly:

  1. Provide stop parameter as -1(it's previous value of stop - 1, stop was equal to 0).
  2. As start parameter use n-1.

So equivalent of range(n) in reverse order would be:

n = 10
print range(n-1,-1,-1) 
#[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Convert date time string to epoch in Bash

For Linux Run this command

date -d '06/12/2012 07:21:22' +"%s"

For mac OSX run this command

date -j -u -f "%a %b %d %T %Z %Y" "Tue Sep 28 19:35:15 EDT 2010" "+%s"

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

Try this:

import matplotlib as plt

after importing the file we can use matplotlib library but remember to use it as plt

df.plt(kind='line',figsize=(10,5))

after that the plot will be done and size increased. In figsize the 10 is for breadth and 5 is for height. Also other attributes can be added to the plot too.

Batch files : How to leave the console window open

I just press enter and type Pause and it works fine

Log to the base 2 in python

If you are on python 3.3 or above then it already has a built-in function for computing log2(x)

import math
'finds log base2 of x'
answer = math.log2(x)

If you are on older version of python then you can do like this

import math
'finds log base2 of x'
answer = math.log(x)/math.log(2)

How do I convert Word files to PDF programmatically?

PDFCreator has a COM component, callable from .NET or VBScript (samples included in the download).

But, it seems to me that a printer is just what you need - just mix that with Word's automation, and you should be good to go.

How to write a multiline command?

If you came here looking for an answer to this question but not exactly the way the OP meant, ie how do you get multi-line CMD to work in a single line, I have a sort of dangerous answer for you.

Trying to use this with things that actually use piping, like say findstr is quite problematic. The same goes for dealing with elses. But if you just want a multi-line conditional command to execute directly from CMD and not via a batch file, this should do work well.

Let's say you have something like this in a batch that you want to run directly in command prompt:

@echo off
for /r %%T IN (*.*) DO (
    if /i "%%~xT"==".sln" (
        echo "%%~T" is a normal SLN file, and not a .SLN.METAPROJ or .SLN.PROJ file
        echo Dumping SLN file contents
        type "%%~T"
    )
)

Now, you could use the line-continuation carat (^) and manually type it out like this, but warning, it's tedious and if you mess up you can learn the joy of typing it all out again.

Well, it won't work with just ^ thanks to escaping mechanisms inside of parentheses shrug At least not as-written. You actually would need to double up the carats like so:

@echo off ^
More? for /r %T IN (*.sln) DO (^^
More? if /i "%~xT"==".sln" (^^
More? echo "%~T" is a normal SLN file, and not a .SLN.METAPROJ or .SLN.PROJ file^^
More? echo Dumping SLN file contents^^
More? type "%~T"))

Instead, you can be a dirty sneaky scripter from the wrong side of the tracks that don't need no carats by swapping them out for a single pipe (|) per continuation of a loop/expression:

@echo off
for /r %T IN (*.sln) DO if /i "%~xT"==".sln" echo "%~T" is a normal SLN file, and not a .SLN.METAPROJ or .SLN.PROJ file | echo Dumping SLN file contents | type "%~T"

How to export data as CSV format from SQL Server using sqlcmd?

You can run something like this:

sqlcmd -S MyServer -d myDB -E -Q "select col1, col2, col3 from SomeTable" 
       -o "MyData.csv" -h-1 -s"," -w 700
  • -h-1 removes column name headers from the result
  • -s"," sets the column seperator to ,
  • -w 700 sets the row width to 700 chars (this will need to be as wide as the longest row or it will wrap to the next line)

Show image using file_get_contents

you can do like this :

<?php
    $file = 'your_images.jpg';

    header('Content-Type: image/jpeg');
    header('Content-Length: ' . filesize($file));
    echo file_get_contents($file);
?>

Smooth scroll without the use of jQuery

You can use a for loop with window.scrollTo and setTimeout to scroll smoothly with plain Javascript. To scroll to an element with my scrollToSmoothly function: scrollToSmoothly(elem.offsetTop) (assuming elem is a DOM element). You can use this to scroll smoothly to any y-position in the document.

function scrollToSmoothly(pos, time){
/*Time is only applicable for scrolling upwards*/
/*Code written by hev1*/
/*pos is the y-position to scroll to (in pixels)*/
     if(isNaN(pos)){
      throw "Position must be a number";
     }
     if(pos<0){
     throw "Position can not be negative";
     }
    var currentPos = window.scrollY||window.screenTop;
    if(currentPos<pos){
    var t = 10;
       for(let i = currentPos; i <= pos; i+=10){
       t+=10;
        setTimeout(function(){
        window.scrollTo(0, i);
        }, t/2);
      }
    } else {
    time = time || 2;
       var i = currentPos;
       var x;
      x = setInterval(function(){
         window.scrollTo(0, i);
         i -= 10;
         if(i<=pos){
          clearInterval(x);
         }
     }, time);
      }
}

Demo:

_x000D_
_x000D_
<button onClick="scrollToDiv()">Scroll To Element</button>_x000D_
<div style="margin: 1000px 0px; text-align: center;">Div element<p/>_x000D_
<button onClick="scrollToSmoothly(Number(0))">Scroll back to top</button>_x000D_
</div>_x000D_
<script>_x000D_
function scrollToSmoothly(pos, time){_x000D_
/*Time is only applicable for scrolling upwards*/_x000D_
/*Code written by hev1*/_x000D_
/*pos is the y-position to scroll to (in pixels)*/_x000D_
     if(isNaN(pos)){_x000D_
      throw "Position must be a number";_x000D_
     }_x000D_
     if(pos<0){_x000D_
     throw "Position can not be negative";_x000D_
     }_x000D_
    var currentPos = window.scrollY||window.screenTop;_x000D_
    if(currentPos<pos){_x000D_
    var t = 10;_x000D_
       for(let i = currentPos; i <= pos; i+=10){_x000D_
       t+=10;_x000D_
        setTimeout(function(){_x000D_
       window.scrollTo(0, i);_x000D_
        }, t/2);_x000D_
      }_x000D_
    } else {_x000D_
    time = time || 2;_x000D_
       var i = currentPos;_x000D_
       var x;_x000D_
      x = setInterval(function(){_x000D_
         window.scrollTo(0, i);_x000D_
         i -= 10;_x000D_
         if(i<=pos){_x000D_
          clearInterval(x);_x000D_
         }_x000D_
     }, time);_x000D_
      }_x000D_
}_x000D_
function scrollToDiv(){_x000D_
  var elem = document.querySelector("div");_x000D_
  scrollToSmoothly(elem.offsetTop);_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When indicating HTTP Basic Authentication we return something like:

WWW-Authenticate: Basic realm="myRealm"

Whereas Basic is the scheme and the remainder is very much dependent on that scheme. In this case realm just provides the browser a literal that can be displayed to the user when prompting for the user id and password.

You're obviously not using Basic however since there is no point having session expiry when Basic Auth is used. I assume you're using some form of Forms based authentication.

From recollection, Windows Challenge Response uses a different scheme and different arguments.

The trick is that it's up to the browser to determine what schemes it supports and how it responds to them.

My gut feel if you are using forms based authentication is to stay with the 200 + relogin page but add a custom header that the browser will ignore but your AJAX can identify.

For a really good User + AJAX experience, get the script to hang on to the AJAX request that found the session expired, fire off a relogin request via a popup, and on success, resubmit the original AJAX request and carry on as normal.

Avoid the cheat that just gets the script to hit the site every 5 mins to keep the session alive cause that just defeats the point of session expiry.

The other alternative is burn the AJAX request but that's a poor user experience.

The equivalent of wrap_content and match_parent in flutter?

To make a child fill its parent, simply wrap it into a FittedBox

    FittedBox(
     child: Image.asset('foo.png'),
     fit: BoxFit.fill,
   )

css absolute position won't work with margin-left:auto margin-right: auto

When you are defining styles for division which is positioned absolutely, they specifying margins are useless. Because they are no longer inside the regular DOM tree.

You can use float to do the trick.

.divtagABS {
    float: left;
    margin-left: auto;  
    margin-right:auto;
 }

Dataframe to Excel sheet

From your above needs, you will need to use both Python (to export pandas data frame) and VBA (to delete existing worksheet content and copy/paste external data).

With Python: use the to_csv or to_excel methods. I recommend the to_csv method which performs better with larger datasets.

# DF TO EXCEL
from pandas import ExcelWriter

writer = ExcelWriter('PythonExport.xlsx')
yourdf.to_excel(writer,'Sheet5')
writer.save()

# DF TO CSV
yourdf.to_csv('PythonExport.csv', sep=',')

With VBA: copy and paste source to destination ranges.

Fortunately, in VBA you can call Python scripts using Shell (assuming your OS is Windows).

Sub DataFrameImport()
  'RUN PYTHON TO EXPORT DATA FRAME
  Shell "C:\pathTo\python.exe fullpathOfPythonScript.py", vbNormalFocus

  'CLEAR EXISTING CONTENT
  ThisWorkbook.Worksheets(5).Cells.Clear

  'COPY AND PASTE TO WORKBOOK
  Workbooks("PythonExport").Worksheets(1).Cells.Copy
  ThisWorkbook.Worksheets(5).Range("A1").Select
  ThisWorkbook.Worksheets(5).Paste
End Sub

Alternatively, you can do vice versa: run a macro (ClearExistingContent) with Python. Be sure your Excel file is a macro-enabled (.xlsm) one with a saved macro to delete Sheet 5 content only. Note: macros cannot be saved with csv files.

import os
import win32com.client
from pandas import ExcelWriter

if os.path.exists("C:\Full Location\To\excelsheet.xlsm"):
  xlApp=win32com.client.Dispatch("Excel.Application")
  wb = xlApp.Workbooks.Open(Filename="C:\Full Location\To\excelsheet.xlsm")

  # MACRO TO CLEAR SHEET 5 CONTENT
  xlApp.Run("ClearExistingContent")
  wb.Save() 
  xlApp.Quit()
  del xl

  # WRITE IN DATA FRAME TO SHEET 5
  writer = ExcelWriter('C:\Full Location\To\excelsheet.xlsm')
  yourdf.to_excel(writer,'Sheet5')
  writer.save() 

How to use multiple @RequestMapping annotations in spring?

The shortest way is: @RequestMapping({"", "/", "welcome"})

Although you can also do:

  • @RequestMapping(value={"", "/", "welcome"})
  • @RequestMapping(path={"", "/", "welcome"})

Standard Android menu icons, for example refresh

Never mind, I found it in the source: base.git/core/res/res and subdirectories.

As others said in the comments, if you have the Android SDK installed it’s also on your computer. The path is [SDK]/platforms/android-[VERSION]/data/res.

How to center a window on the screen in Tkinter?

CENTERING THE WINDOW IN PYTHON Tkinter This is the most easiest thing in tkinter because all we must know is the dimension of the window as well as the dimensions of the computer screen. I come up with the following code which can help someone somehow and i did add some comments so that they can follow up.

code

    #  create a window first
    root = Tk()
    # define window dimensions width and height
    window_width = 800
    window_height = 500
    # get the screen size of your computer [width and height using the root object as foolows]
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    # Get the window position from the top dynamically as well as position from left or right as follows
    position_top = int(screen_height/2 -window_height/2)
    position_right = int(screen_width / 2 - window_width/2)
    # this is the line that will center your window
    root.geometry(f'{window_width}x{window_height}+{position_right}+{position_top}')
    # initialise the window
    root.mainloop(0)

How can I convert IPV6 address to IPV4 address?

Some googling led me to the following post:

http://www.developerweb.net/forum/showthread.php?t=3434

The code provided in the post is in C, but it shouldn't be too hard to rewrite it to Java.

MSVCP120d.dll missing

I have the same problem with you when I implement OpenCV 2.4.11 on VS 2015. I tried to solve this problem by three methods one by one but they didn't work:

  1. download MSVCP120.DLL online and add it to windows path and OpenCV bin file path
  2. install Visual C++ Redistributable Packages for Visual Studio 2013 both x86 and x86
  3. adjust Debug mode. Go to configuration > C/C++ > Code Generation > Runtime Library and select Multi-threaded Debug (/MTd)

Finally I solved this problem by reinstalling VS2015 with selecting all the options that can be installed, it takes a lot space but it really works.

Sorting an Array of int using BubbleSort

Really not getting the bubble sort, which can be called a sinking sort more appropriately since it's actually sinking the bigger/heavier to the bottom as the majority of the answers presented. One of the most typicals will be

private static void sortZero(Comparable[] arr) {
    boolean moreSinkingRequired = true;
    while (moreSinkingRequired) {
        moreSinkingRequired = false;
        for (int j = 0; j < arr.length - 1; ++j) {
            if (less(arr, j + 1, j)) { 
                exch(arr, j, j + 1);
                moreSinkingRequired = true;
            }
        }
    }
}

By the way, you have to traverse once more than actually required to stop earlier.

But as I see it bubbling as

private static void sortOne(Comparable[] arr) {
    for (int i = 0; i < arr.length - 1; ++i) {
        for (int j = arr.length - 1; j > i; --j) { // start from the bottom
            if (less(arr, j, j - 1)) {
                exch(arr, j - 1, j);
            }
        }
    }
}

You have to know this method is actually better since it's tracking the end point for comparison by j > i with [0, i-1] already sorted.

We also can add earlier termination but it then becomes verbose as

private static void sortTwo(Comparable[] arr) {
    boolean moreBubbleRequired = true;
    for (int i = 0; i < arr.length - 1 && moreBubbleRequired; ++i) {
        moreBubbleRequired = false;
        for (int j = arr.length - 1; j > i; --j) {
            if (less(arr, j, j - 1)) {
                exch(arr, j - 1, j);
                moreBubbleRequired = true;
            }
        }
    }
}

The utils used to make the process terse are

public static boolean less(Comparable[] arr, int i, int j) {
    return less(arr[i], arr[j]);
}

public static boolean less(Comparable a, Comparable b) {
    return a.compareTo(b) < 0;
}

public static void exch(Comparable[] arr, int i, int j) {
    Comparable t = arr[i];
    arr[i] = arr[j];
    arr[j] = t;
}

C++ convert string to hexadecimal and vice versa

Simplest example using the Standard Library.

#include <iostream>
using namespace std;

int main()
{
  char c = 'n';
  cout << "HEX " << hex << (int)c << endl;  // output in hexadecimal
  cout << "ASC" << c << endl; // output in ascii
  return 0;
}

To check the output, codepad returns: 6e

and an online ascii-to-hexadecimal conversion tool yields 6e as well. So it works.

You can also do this:

template<class T> std::string toHexString(const T& value, int width) {
    std::ostringstream oss;
    oss << hex;
    if (width > 0) {
        oss << setw(width) << setfill('0');
    }
    oss << value;
    return oss.str();
}

Getting DOM node from React child element

this.props.children should either be a ReactElement or an array of ReactElement, but not components.

To get the DOM nodes of the children elements, you need to clone them and assign them a new ref.

render() {
  return (
    <div>
      {React.Children.map(this.props.children, (element, idx) => {
        return React.cloneElement(element, { ref: idx });
      })}
    </div>
  );
}

You can then access the child components via this.refs[childIdx], and retrieve their DOM nodes via ReactDOM.findDOMNode(this.refs[childIdx]).

Count the number of commits on a Git branch

To count the commits for the branch you are on:

git rev-list --count HEAD

for a branch

git rev-list --count <branch-name>

If you want to count the commits on a branch that are made since you created the branch

git rev-list --count HEAD ^<branch-name>

This will count all commits ever made that are not on the branch-name as well.

Examples

git checkout master
git checkout -b test
<We do 3 commits>
git rev-list --count HEAD ^master

Result: 3

If your branch comes of a branch called develop:

git checkout develop
git checkout -b test
<We do 3 commits>
git rev-list --count HEAD ^develop

Result: 3

Ignoring Merges

If you merge another branch into the current branch without fast forward and you do the above, the merge is also counted. This is because for git a merge is a commit.

If you don't want to count these commits add --no-merges:

git rev-list --no-merges --count HEAD ^develop

Bash integer comparison

Easier solution;

#/bin/bash
if (( ${1:-2} >= 2 )); then
    echo "First parameter must be 0 or 1"
fi
# rest of script...

Output

$ ./test 
First parameter must be 0 or 1
$ ./test 0
$ ./test 1
$ ./test 4
First parameter must be 0 or 1
$ ./test 2
First parameter must be 0 or 1

Explanation

  • (( )) - Evaluates the expression using integers.
  • ${1:-2} - Uses parameter expansion to set a value of 2 if undefined.
  • >= 2 - True if the integer is greater than or equal to two 2.

Unstaged changes left after git reset --hard

If you use Git for Windows, this is likely your issue

I've had the same problem and stash, hard reset, clean or even all of them was still leaving changes behind. What turned out to be the problem was the x file mode that was not set properly by git. This is a "known issue" with git for windows. The local changes show in gitk and git status as old mode 100755 new mode 100644, without any actual file differences.

The fix is to ignore the file mode:

git config core.filemode false

More info here

How do I read the contents of a Node.js stream into a string variable?

All the answers listed appear to open the Readable Stream in flowing mode which is not the default in NodeJS and can have limitations since it lacks backpressure support that NodeJS provides in Paused Readable Stream Mode. Here is an implementation using Just Buffers, Native Stream and Native Stream Transforms and support for Object Mode

import {Transform} from 'stream';

let buffer =null;    

function objectifyStream() {
    return new Transform({
        objectMode: true,
        transform: function(chunk, encoding, next) {

            if (!buffer) {
                buffer = Buffer.from([...chunk]);
            } else {
                buffer = Buffer.from([...buffer, ...chunk]);
            }
            next(null, buffer);
        }
    });
}

process.stdin.pipe(objectifyStream()).process.stdout

Angular 2: 404 error occur when I refresh through the browser

Perhaps you can do it while registering your root with RouterModule. You can pass a second object with property useHash:true like the below:

import { NgModule }       from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { ROUTES }   from './app.routes';

@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule],
    RouterModule.forRoot(ROUTES ,{ useHash: true }),],
    providers: [],
    bootstrap: [AppComponent],
})
export class AppModule {}

Uncaught TypeError: Cannot read property 'top' of undefined

The problem you are most likely having is that there is a link somewhere in the page to an anchor that does not exist. For instance, let's say you have the following:

<a href="#examples">Skip to examples</a>

There has to be an element in the page with that id, example:

<div id="examples">Here are the examples</div>

So make sure that each one of the links are matched inside the page with it's corresponding anchor.

PHP 5 disable strict standards error

In php.ini set :

error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT

C/C++ switch case with string

You can use enumeration and a map, so your string will become the key and enum value is value for that key.

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

New line character in VB.Net?

The proper way to do this in VB is to use on of the VB constants for newlines. The main three are

  • vbCrLf = "\r\n"
  • vbCr = "\r"
  • vbLf = "\n"

VB by default doesn't allow for any character escape codes in strings which is different than languages like C# and C++ which do. One of the reasons for doing this is ease of use when dealing with file paths.

  • C++ file path string: "c:\\foo\\bar.txt"
  • VB file path string: "c:\foo\bar.txt"
  • C# file path string: C++ way or @"c:\foo\bar.txt"

how to Call super constructor in Lombok

for superclasses with many members I would suggest you to use @Delegate

@Data
public class A {
    @Delegate public class AInner{
        private final int x;
        private final int y;
    }
}

@Data
@EqualsAndHashCode(callSuper = true)
public class B extends A {
    private final int z;

    public B(A.AInner a, int z) {
        super(a);
        this.z = z;
    }
}

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

To remove all objects in oracle :

1) Dynamic

DECLARE
CURSOR IX IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE ='TABLE' 
AND OWNER='SCHEMA_NAME';
 CURSOR IY IS
 SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE 
IN ('SEQUENCE',
'PROCEDURE',
'PACKAGE',
'FUNCTION',
'VIEW') AND  OWNER='SCHEMA_NAME';
 CURSOR IZ IS
 SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('TYPE') AND  OWNER='SCHEMA_NAME';
BEGIN
 FOR X IN IX LOOP
   EXECUTE IMMEDIATE('DROP '||X.OBJECT_TYPE||' '||X.OBJECT_NAME|| ' CASCADE CONSTRAINT');
 END LOOP;
 FOR Y IN IY LOOP
   EXECUTE IMMEDIATE('DROP '||Y.OBJECT_TYPE||' '||Y.OBJECT_NAME);
 END LOOP;
 FOR Z IN IZ LOOP
   EXECUTE IMMEDIATE('DROP '||Z.OBJECT_TYPE||' '||Z.OBJECT_NAME||' FORCE ');
 END LOOP;
END;
/

2)Static

    SELECT 'DROP TABLE "' || TABLE_NAME || '" CASCADE CONSTRAINTS;' FROM user_tables
        union ALL
        select 'drop '||object_type||' '|| object_name || ';' from user_objects 
        where object_type in ('VIEW','PACKAGE','SEQUENCE', 'PROCEDURE', 'FUNCTION')
        union ALL
        SELECT 'drop '
        ||object_type
        ||' '
        || object_name
        || ' force;'
        FROM user_objects
        WHERE object_type IN ('TYPE');

How do I accomplish an if/else in mustache.js?

You can define a helper in the view. However, the conditional logic is somewhat limited. Moxy-Stencil (https://github.com/dcmox/moxyscript-stencil) seems to address this with "parameterized" helpers, eg:

{{isActive param}}

and in the view:

view.isActive = function (path: string){ return path === this.path ? "class='active'" : '' }

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

Empty set literal?

Just to extend the accepted answer:

From version 2.7 and 3.1 python has got set literal {} in form of usage {1,2,3}, but {} itself still used for empty dict.

Python 2.7 (first line is invalid in Python <2.7)

>>> {1,2,3}.__class__
<type 'set'>
>>> {}.__class__
<type 'dict'>

Python 3.x

>>> {1,2,3}.__class__
<class 'set'>
>>> {}.__class__
<class 'dict'>

More here: https://docs.python.org/3/whatsnew/2.7.html#other-language-changes

Test if something is not undefined in JavaScript

I know i went here 7 months late, but I found this questions and it looks interesting. I tried this on my browser console.

try{x,true}catch(e){false}

If variable x is undefined, error is catched and it will be false, if not, it will return true. So you can use eval function to set the value to a variable

var isxdefined = eval('try{x,true}catch(e){false}')

What are the true benefits of ExpandoObject?

Interop with other languages founded on the DLR is #1 reason I can think of. You can't pass them a Dictionary<string, object> as it's not an IDynamicMetaObjectProvider. Another added benefit is that it implements INotifyPropertyChanged which means in the databinding world of WPF it also has added benefits beyond what Dictionary<K,V> can provide you.

How to get the full URL of a Drupal page?

For Drupal 8 you can do this :

$url = 'YOUR_URL';
$url = \Drupal\Core\Url::fromUserInput('/' . $url,  array('absolute' => 'true'))->toString();

Single quotes vs. double quotes in C or C++

Some compilers also implement an extension, that allows multi-character constants. The C99 standard says:

6.4.4.4p10: "The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined."

This could look like this, for instance:

const uint32_t png_ihdr = 'IHDR';

The resulting constant (in GCC, which implements this) has the value you get by taking each character and shifting it up, so that 'I' ends up in the most significant bits of the 32-bit value. Obviously, you shouldn't rely on this if you are writing platform independent code.

flutter remove back button on appbar

You can remove the back button by passing an empty new Container() as the leading argument to your AppBar.

If you find yourself doing this, you probably don't want the user to be able to press the device's back button to get back to the earlier route. Instead of calling pushNamed, try calling Navigator.pushReplacementNamed to cause the earlier route to disappear.

The function pushReplacementNamed will remove the previous route in the backstack and replace it with the new route.

Full code sample for the latter is below.

import 'package:flutter/material.dart';

class LogoutPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Logout Page"),
      ),
      body: new Center(
        child: new Text('You have been logged out'),
      ),
    );
  }

}
class MyHomePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Remove Back Button"),
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.fullscreen_exit),
        onPressed: () {
          Navigator.pushReplacementNamed(context, "/logout");
        },
      ),
    );
  }
}

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyHomePage(),
      routes: {
        "/logout": (_) => new LogoutPage(),
      },
    );
  }
}

Get property value from string using reflection

The below method works perfect for me:

class MyClass {
    public string prop1 { set; get; }

    public object this[string propertyName]
    {
        get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
        set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
    }
}

To get the property value:

MyClass t1 = new MyClass();
...
string value = t1["prop1"].ToString();

To set the property value:

t1["prop1"] = value;

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

Two things you could do I think...

  1. Create the System.Diagnostics.Process object manually and bypass Start-Process
  2. Run the executable in a background job (only for non-interactive processes!)

Here's how you could do either:

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "notepad.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = ""
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
#Do Other Stuff Here....
$p.WaitForExit()
$p.ExitCode

OR

Start-Job -Name DoSomething -ScriptBlock {
    & ping.exe somehost
    Write-Output $LASTEXITCODE
}
#Do other stuff here
Get-Job -Name DoSomething | Wait-Job | Receive-Job

Scanner is skipping nextLine() after using next() or nextFoo()?

There seem to be many questions about this issue with java.util.Scanner. I think a more readable/idiomatic solution would be to call scanner.skip("[\r\n]+") to drop any newline characters after calling nextInt().

EDIT: as @PatrickParker noted below, this will cause an infinite loop if user inputs any whitespace after the number. See their answer for a better pattern to use with skip: https://stackoverflow.com/a/42471816/143585

How do I hide an element on a click event anywhere outside of the element?

$( "element" ).focusout(function() {
    //your code on element
})

In C can a long printf statement be broken up into multiple lines?

If you want to break a string literal onto multiple lines, you can concatenate multiple strings together, one on each line, like so:

printf("name: %s\t"
"args: %s\t"
"value %d\t"
"arraysize %d\n", 
sp->name, 
sp->args, 
sp->value, 
sp->arraysize);

Check empty string in Swift?

I can recommend add small extension to String or Array that looks like

extension Collection {
    public var isNotEmpty: Bool {
        return !self.isEmpty
    }
}

With it you can write code that is easier to read. Compare this two lines

if !someObject.someParam.someSubParam.someString.isEmpty {}

and

if someObject.someParam.someSubParam.someString.isNotEmpty {}

It is easy to miss ! sign in the beginning of fist line.

Reading a JSP variable from JavaScript

   <% String s="Hi"; %>
   var v ="<%=s%>"; 

react change class name on state change

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

Explanation

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

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

Example

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

Update: "Loops"

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

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

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

How do I get current scope dom-element in AngularJS controller?

The better and correct solution is to have a directive. The scope is the same, whether in the controller of the directive or the main controller. Use $element to do DOM operations. The method defined in the directive controller is accessible in the main controller.

Example, finding a child element:

var app = angular.module('myapp', []);
app.directive("testDir", function () {
    function link(scope, element) { 

    }
    return {
        restrict: "AE", 
        link: link, 
        controller:function($scope,$element){
            $scope.name2 = 'this is second name';
            var barGridSection = $element.find('#barGridSection'); //helps to find the child element.
    }
    };
})

app.controller('mainController', function ($scope) {
$scope.name='this is first name'
});

Angular 2 / 4 / 5 - Set base href dynamically

Based on your (@sharpmachine) answer, I was able to further refactor it a little, so that we don't have to hack out a function in index.html.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF, Location } from '@angular/common';

import { AppComponent } from './';
import { getBaseLocation } from './shared/common-functions.util';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpModule,
  ],
  bootstrap: [AppComponent],
  providers: [
    appRoutingProviders,
    {
        provide: APP_BASE_HREF,
        useFactory: getBaseLocation
    },
  ]
})
export class AppModule { }

And, ./shared/common-functions.util.ts contains:

export function getBaseLocation() {
    let paths: string[] = location.pathname.split('/').splice(1, 1);
    let basePath: string = (paths && paths[0]) || 'my-account'; // Default: my-account
    return '/' + basePath;
}

How do I use Maven through a proxy?

Thanks @krosenvold.

If the settings file changes don't work, try this in the command prompt having the POM file.

mvn install -Dhttp.proxyHost=abcproxy -Dhttp.proxyPort=8080 -Dhttps.proxyHost=abcproxy -Dhttps.proxyPort=8080

This has helped me immediately after a password change.

What is difference between mutable and immutable String in java


String in Java is immutable. However what does it mean to be mutable in programming context is the first question. Consider following class,

public class Dimension {
    private int height;

    private int width;

    public Dimenstion() {
    }

    public void setSize(int height, int width) {
        this.height = height;
        this.width = width;
    }

    public getHeight() {
        return height;
    }

    public getWidth() {
        return width;
    }
}

Now after creating the instance of Dimension we can always update it's attributes. Note that if any of the attribute, in other sense state, can be updated for instance of the class then it is said to be mutable. We can always do following,

Dimension d = new Dimension();
d.setSize(10, 20);// Dimension changed
d.setSize(10, 200);// Dimension changed
d.setSize(100, 200);// Dimension changed

Let's see in different ways we can create a String in Java.

String str1 = "Hey!";
String str2 = "Jack";
String str3 = new String("Hey Jack!");
String str4 = new String(new char[] {'H', 'e', 'y', '!'});
String str5 = str1 + str2;
str1 = "Hi !";
// ...

So,

  1. str1 and str2 are String literals which gets created in String constant pool
  2. str3, str4 and str5 are String Objects which are placed in Heap memory
  3. str1 = "Hi!"; creates "Hi!" in String constant pool and it's totally different reference than "Hey!" which str1 referencing earlier.

Here we are creating the String literal or String Object. Both are different, I would suggest you to read following post to understand more about it.

In any String declaration, one thing is common, that it does not modify but it gets created or shifted to other.

String str = "Good"; // Create the String literal in String pool
str = str + " Morning"; // Create String with concatenation of str + "Morning"
|_____________________|
       |- Step 1 : Concatenate "Good"  and " Morning" with StringBuilder
       |- Step 2 : assign reference of created "Good Morning" String Object to str

How String became immutable ?

It's non changing behaviour, means, the value once assigned can not be updated in any other way. String class internally holds data in character array. Moreover, class is created to be immutable. Take a look at this strategy for defining immutable class.

Shifting the reference does not mean you changed it's value. It would be mutable if you can update the character array which is behind the scene in String class. But in reality that array will be initialized once and throughout the program it remains the same.

Why StringBuffer is mutable ?

As you already guessed, StringBuffer class is mutable itself as you can update it's state directly. Similar to String it also holds value in character array and you can manipulate that array by different methods i.e. append, delete, insert etc. which directly changes the character value array.

Take nth column in a text file

You can use the cut command:

cut -d' ' -f3,5 < datafile.txt

prints

1657 19.6117
1410 18.8302
3078 18.6695
2434 14.0508
3129 13.5495

the

  • -d' ' - mean, use space as a delimiter
  • -f3,5 - take and print 3rd and 5th column

The cut is much faster for large files as a pure shell solution. If your file is delimited with multiple whitespaces, you can remove them first, like:

sed 's/[\t ][\t ]*/ /g' < datafile.txt | cut -d' ' -f3,5

where the (gnu) sed will replace any tab or space characters with a single space.

For a variant - here is a perl solution too:

perl -lanE 'say "$F[2] $F[4]"' < datafile.txt

How to Use slideDown (or show) function on a table row?

function hideTr(tr) {
  tr.find('td').wrapInner('<div style="display: block;" />').parent().find('td > div').slideUp(50, function () {
    tr.hide();
    var $set = jQuery(this);
    $set.replaceWith($set.contents());
  });
}

function showTr(tr) {
  tr.show()
  tr.find('td').wrapInner('<div style="display: none;" />').parent().find('td > div').slideDown(50, function() {
    var $set = jQuery(this);
    $set.replaceWith($set.contents());
  });
}

you can use these methods like:

jQuery("[data-toggle-tr-trigger]").click(function() {
  var $tr = jQuery(this).parents(trClass).nextUntil(trClass);
  if($tr.is(':hidden')) {
    showTr($tr);
  } else {
    hideTr($tr);
  }
});

Cannot find JavaScriptSerializer in .Net 4.0

using System.Web.Script.Serialization; 

is in assembly : System.Web.Extensions (System.Web.Extensions.dll)

Get an array of list element contents in jQuery

Without redundant intermediate arrays:

arr = $('li').map(function(i,el) {
    return $(el).text();
}).get();

See jsfiddle demo

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I had same issue and I solved it by "pod setup" after installing cocoapods.

How to Use UTF-8 Collation in SQL Server database?

No! It's not a joke.

Take a look here: http://msdn.microsoft.com/en-us/library/ms186939.aspx

Character data types that are either fixed-length, nchar, or variable-length, nvarchar, Unicode data and use the UNICODE UCS-2 character set.

And also here: http://en.wikipedia.org/wiki/UTF-16

The older UCS-2 (2-byte Universal Character Set) is a similar character encoding that was superseded by UTF-16 in version 2.0 of the Unicode standard in July 1996.

How to set tbody height with overflow scroll

HTML:

<table id="uniquetable">
    <thead>
      <tr>
        <th> {{ field[0].key }} </th>
        <th> {{ field[1].key }} </th>
        <th> {{ field[2].key }} </th>
        <th> {{ field[3].key }} </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="obj in objects" v-bind:key="obj.id">
        <td> {{ obj.id }} </td>
        <td> {{ obj.name }} </td>
        <td> {{ obj.age }} </td>
        <td> {{ obj.gender }} </td>
      </tr>
    </tbody>
</table>

CSS:

#uniquetable thead{
    display:block;
    width: 100%;
}
#uniquetable tbody{
    display:block;
    width: 100%;
    height: 100px;
    overflow-y:overlay;
    overflow-x:hidden;
}
#uniquetable tbody tr,#uniquetable thead tr{
    width: 100%;
    display:table;
}
#uniquetable tbody tr td, #uniquetable thead tr th{
   display:table-cell;
   width:20% !important;
   overflow:hidden;
}

this will work as well:

#uniquetable tbody {
    width:inherit !important;
    display:block;
    max-height: 400px;
    overflow-y:overlay;
  }
  #uniquetable thead {
    width:inherit !important;
    display:block;
  }
  #uniquetable tbody tr, #uniquetable thead tr {
    display:inline-flex;
    width:100%;
  }
  #uniquetable tbody tr td,  #uniquetable thead tr th {
    display:block;
    width:20%;
    border-top:none;
    text-overflow: ellipsis;
    overflow: hidden;
    max-height:400px;
  }

struct.error: unpack requires a string argument of length 4

By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char.

To disable this, use: struct.unpack("=BH", data). This will use standard alignment, which doesn't add padding:

>>> struct.calcsize('=BH')
3

The = character will use native byte ordering. You can also use < or > instead of = to force little-endian or big-endian byte ordering, respectively.

Creating an empty bitmap and drawing though canvas in Android

This is probably simpler than you're thinking:

int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

Here's a series of tutorials I've found on the topic: Drawing with Canvas Series

Android Studio - mergeDebugResources exception

It happens to me only when modifying the XML files on the project. If you rebuild the entire project before running (Build > Rebuild Project) it doesn't show up anymore.

Conditional operator in Python?

simple is the best and works in every version.

if a>10: 
    value="b"
else: 
    value="c"

Setting focus to iframe contents

I had a similar problem with the jQuery Thickbox (a lightbox-style dialog widget). The way I fixed my problem is as follows:

function setFocusThickboxIframe() {
    var iframe = $("#TB_iframeContent")[0];
    iframe.contentWindow.focus();
}

$(document).ready(function(){
   $("#id_cmd_open").click(function(){
      /*
         run thickbox code here to open lightbox,
         like tb_show("google this!", "http://www.google.com");
       */
      setTimeout(setFocusThickboxIframe, 100);
      return false;
   });
});

The code doesn't seem to work without the setTimeout(). Based on my testing, it works in Firefox3.5, Safari4, Chrome4, IE7 and IE6.

Suppress console output in PowerShell

Try redirecting the output to Out-Null. Like so,

$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose | out-null

How can I find whitespace in a String?

I purpose to you a very simple method who use String.contains:

public static boolean containWhitespace(String value) {
    return value.contains(" ");
}

A little usage example:

public static void main(String[] args) {
    System.out.println(containWhitespace("i love potatoes"));
    System.out.println(containWhitespace("butihatewhitespaces"));
}

Output:

true
false

How do you set the startup page for debugging in an ASP.NET MVC application?

While you can have a default page in the MVC project, the more conventional implementation for a default view would be to use a default controller, implememented in the global.asax, through the 'RegisterRoutes(...)' method. For instance if you wanted your Public\Home controller to be your default route/view, the code would be:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Public", action = "Home", id = UrlParameter.Optional } // Parameter defaults
        );

    }

For this to be functional, you are required to have have a set Start Page in the project.

What does ENABLE_BITCODE do in xcode 7?

What is embedded bitcode?

According to docs:

Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.

Update: This phrase in "New Features in Xcode 7" made me to think for a long time that Bitcode is needed for Slicing to reduce app size:

When you archive for submission to the App Store, Xcode will compile your app into an intermediate representation. The App Store will then compile the bitcode down into the 64 or 32 bit executables as necessary.

However that's not true, Bitcode and Slicing work independently: Slicing is about reducing app size and generating app bundle variants, and Bitcode is about certain binary optimizations. I've verified this by checking included architectures in executables of non-bitcode apps and founding that they only include necessary ones.

Bitcode allows other App Thinning component called Slicing to generate app bundle variants with particular executables for particular architectures, e.g. iPhone 5S variant will include only arm64 executable, iPad Mini armv7 and so on.

When to enable ENABLE_BITCODE in new Xcode?

For iOS apps, bitcode is the default, but optional. If you provide bitcode, all apps and frameworks in the app bundle need to include bitcode. For watchOS and tvOS apps, bitcode is required.

What happens to the binary when ENABLE_BITCODE is enabled in the new Xcode?

From Xcode 7 reference:

Activating this setting indicates that the target or project should generate bitcode during compilation for platforms and architectures which support it. For Archive builds, bitcode will be generated in the linked binary for submission to the app store. For other builds, the compiler and linker will check whether the code complies with the requirements for bitcode generation, but will not generate actual bitcode.

Here's a couple of links that will help in deeper understanding of Bitcode:

LAST_INSERT_ID() MySQL

We only have one person entering records, so I execute the following query immediately following the insert:

$result = $conn->query("SELECT * FROM corex ORDER BY id DESC LIMIT 1");

while ($row = $result->fetch_assoc()) {

            $id = $row['id'];

}

This retrieves the last id from the database.

How do I get a Cron like scheduler in Python?

There isn't a "pure python" way to do this because some other process would have to launch python in order to run your solution. Every platform will have one or twenty different ways to launch processes and monitor their progress. On unix platforms, cron is the old standard. On Mac OS X there is also launchd, which combines cron-like launching with watchdog functionality that can keep your process alive if that's what you want. Once python is running, then you can use the sched module to schedule tasks.

ASP.NET document.getElementById('<%=Control.ClientID%>'); returns null

Is Button1 visible? I mean, from the server side. Make sure Button1.Visible is true.

Controls that aren't Visible won't be rendered in HTML, so although they are assigned a ClientID, they don't actually exist on the client side.

How do you use window.postMessage across domains?

Probably you try to send your data from mydomain.com to www.mydomain.com or reverse, NOTE you missed "www". http://mydomain.com and http://www.mydomain.com are different domains to javascript.

Getting started with OpenCV 2.4 and MinGW on Windows 7

If you installed opencv 2.4.2 then you need to change the -lopencv_core240 to -lopencv_core242

I made the same mistake.

What do the python file extensions, .pyc .pyd .pyo stand for?

  1. .py: This is normally the input source code that you've written.
  2. .pyc: This is the compiled bytecode. If you import a module, python will build a *.pyc file that contains the bytecode to make importing it again later easier (and faster).
  3. .pyo: This was a file format used before Python 3.5 for *.pyc files that were created with optimizations (-O) flag. (see the note below)
  4. .pyd: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll

Also for some further discussion on .pyc vs .pyo, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)

  • When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
  • Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only __doc__ strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.
  • A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
  • When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.

Note:

On 2015-09-15 the Python 3.5 release implemented PEP-488 and eliminated .pyo files. This means that .pyc files represent both unoptimized and optimized bytecode.

What are Java command line options to set to allow JVM to be remotely debugged?

Command Line

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=PORT_NUMBER

Gradle

gradle bootrun --debug-jvm

Maven

mvn spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=PORT_NUMBER

select the TOP N rows from a table

select * from table_name LIMIT 100

remember this only works with MYSQL

Cannot connect to MySQL 4.1+ using old authentication

you can do these line on your mysql query browser or something

SET old_passwords = 0;
UPDATE mysql.user SET Password = PASSWORD('testpass') WHERE User = 'testuser' limit 1;
SELECT LENGTH(Password) FROM mysql.user WHERE User = 'testuser';
FLUSH PRIVILEGES;

note:your username and password

after that it should able to work. I just solved mine too

Xcode doesn't see my iOS device but iTunes does

Had the same problem. In my case it was my usb cord.

How to set the thumbnail image on HTML5 video?

_x000D_
_x000D_
<video width="400" controls="controls" preload="metadata">_x000D_
  <source src="https://www.youtube.com/watch?v=Ulp1Kimblg0">_x000D_
</video>
_x000D_
_x000D_
_x000D_

Get the element with the highest occurrence in an array

function mode(){
  var input = $("input").val().split(",");
  var mode = [];
  var m = [];
  var p = [];
    for(var x = 0;x< input.length;x++){
      if(m.indexOf(input[x])==-1){
        m[m.length]=input[x];
    }}
  for(var x = 0; x< m.length;x++){
    p[x]=0;
    for(var y = 0; y<input.length;y++){
      if(input[y]==m[x]){
      p[x]++; 
 }}}
 for(var x = 0;x< p.length;x++){
   if(p[x] ==(Math.max.apply(null, p))){
     mode.push(m[x]);
 }} 
$("#output").text(mode);}

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

query to find sql that opened.

SELECT s.machine, oc.user_name, oc.sql_text, count(1) 
FROM v$open_cursor oc, v$session s
WHERE oc.sid = s.sid
and S.USERNAME='XXXX'
GROUP BY user_name, sql_text, machine
HAVING COUNT(1) > 2
ORDER BY count(1) DESC

How to append the output to a file?

Use >> to append:

command >> file

Can I extend a class using more than 1 class in PHP?

I have read several articles discouraging inheritance in projects (as opposed to libraries/frameworks), and encouraging to program agaisnt interfaces, no against implementations.
They also advocate OO by composition: if you need the functions in class a and b, make c having members/fields of this type:

class C
{
    private $a, $b;

    public function __construct($x, $y)
    {
        $this->a = new A(42, $x);
        $this->b = new B($y);
    }

    protected function DoSomething()
    {
        $this->a->Act();
        $this->b->Do();
    }
}

Could not obtain information about Windows NT group user

Just solved this problem. In my case it was domain controller is not accessible, because both dns servers was google dns.

I just add to checklist for this problem:

  • check domain controller is accessible

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

I have one same Warning caused to com.google.gms:google-services.

The solution is to upgrade classpath com.google.gms:google-services to classpath 'com.google.gms:google-services:3.2.0' in file in build.gradle Project:

enter image description here

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.2.0'
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

In Android Studio verion 3.1 dependencies complie word is replaced to implementation

dependencies with Warning in android studio 3.1

dependencies {
            compile fileTree(dir: 'libs', include: ['*.jar'])
            compile 'com.android.support:appcompat-v7:27.1.0'
            compile 'com.android.support.constraint:constraint-layout:1.0.2'
            testImplementation 'junit:junit:4.12'
            androidTestImplementation 'com.android.support.test:runner:1.0.1'
            androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    }

dependencies OK in android studio 3.1

    dependencies {
            implementation fileTree(dir: 'libs', include: ['*.jar'])
            implementation 'com.android.support:appcompat-v7:27.1.0'
            implementation 'com.android.support.constraint:constraint-layout:1.0.2'
            testImplementation 'junit:junit:4.12'
            androidTestImplementation 'com.android.support.test:runner:1.0.1'
            androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    }

Gradel generate by Android Studio 3.1 for new project.

Gradel generate by Android Studio 3.1 for new project.

Visit https://docs.gradle.org/current/userguide/dependency_management_for_java_projects.html

For details https://docs.gradle.org/current/userguide/declaring_dependencies.html

Paging with LINQ for objects

Using Skip and Take is definitely the way to go. If I were implementing this, I would probably write my own extension method to handle paging (to make the code more readable). The implementation can of course use Skip and Take:

static class PagingUtils {
  public static IEnumerable<T> Page<T>(this IEnumerable<T> en, int pageSize, int page) {
    return en.Skip(page * pageSize).Take(pageSize);
  }
  public static IQueryable<T> Page<T>(this IQueryable<T> en, int pageSize, int page) {
    return en.Skip(page * pageSize).Take(pageSize);
  }
}

The class defines two extension methods - one for IEnumerable and one for IQueryable, which means that you can use it with both LINQ to Objects and LINQ to SQL (when writing database query, the compiler will pick the IQueryable version).

Depending on your paging requirements, you could also add some additional behavior (for example to handle negative pageSize or page value). Here is an example how you would use this extension method in your query:

var q = (from p in products
         where p.Show == true
         select new { p.Name }).Page(10, pageIndex);

How to call same method for a list of objects?

It seems like there would be a more Pythonic way of doing this, but I haven't found it yet.

I use "map" sometimes if I'm calling the same function (not a method) on a bunch of objects:

map(do_something, a_list_of_objects)

This replaces a bunch of code that looks like this:

 do_something(a)
 do_something(b)
 do_something(c)
 ...

But can also be achieved with a pedestrian "for" loop:

  for obj in a_list_of_objects:
       do_something(obj)

The downside is that a) you're creating a list as a return value from "map" that's just being throw out and b) it might be more confusing that just the simple loop variant.

You could also use a list comprehension, but that's a bit abusive as well (once again, creating a throw-away list):

  [ do_something(x) for x in a_list_of_objects ]

For methods, I suppose either of these would work (with the same reservations):

map(lambda x: x.method_call(), a_list_of_objects)

or

[ x.method_call() for x in a_list_of_objects ]

So, in reality, I think the pedestrian (yet effective) "for" loop is probably your best bet.

The page cannot be displayed because an internal server error has occurred on server

I got the same error when I added the applicationinitialization module with lots of initializationpages and deployed it on Azure app. The issue turned out to be duplicate entries in my applicationinitialization module. I din't see any errors in the logs so it was hard to troubleshoot. Below is an example of the error code:

  <configuration>
  <system.webServer>
    <applicationInitialization doAppInitAfterRestart="true" skipManagedModules="true">
      <add initializationPage="/init1.aspx?call=2"/>
      <add initializationPage="/init1.aspx?call=2" />
    </applicationInitialization>
  </system.webServer>

Make sure there are no duplicate entries because those will be treated as duplicate keys which are not allowed and will result in "Cannot add duplicate collection entry" error for web.config.

TypeError: p.easing[this.easing] is not a function

use the latest one for bootstrap 4 and above, this won't affect your UI

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

Basically, you need to redirect out of that page but it still can make a problem while your internet slow (Redirect header from serverside)

Example of basic scenario :

Click on submit button twice

Way to solve

  • Client side

  • Server side

    • Using differentiate based hashing timestamp / timestamp when request was sent.
    • Userequest tokens. When the main loads up assign a temporary request tocken which if repeated is ignored.

Custom edit view in UITableViewCell while swipe left. Objective-C or Swift

create a view on the custom cell in the table view and apply PanGestureRecognizer to the view on the cell.Add the buttons to the custom cell, when you swipe the view on the custom cell then the buttons on the custom cell will be visible.

 UIGestureRecognizer* recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    recognizer.delegate = self;
    [YourView addGestureRecognizer:recognizer];

And handle the panning on the view in the method

 if (recognizer.state == UIGestureRecognizerStateBegan) {
    // if the gesture has just started, record the current centre location
    _originalCenter = vwCell.center;
}

// 2
if (recognizer.state == UIGestureRecognizerStateChanged) {
    // translate the center
    CGPoint translation = [recognizer translationInView:self];
    vwCell.center = CGPointMake(_originalCenter.x + translation.x, _originalCenter.y);
    // determine whether the item has been dragged far enough to initiate  / complete
    _OnDragRelease = vwCell.frame.origin.x < -vwCell.frame.size.width / 2;

}

// 3
if (recognizer.state == UIGestureRecognizerStateEnded) {
    // the frame this cell would have had before being dragged
    CGPoint translation = [recognizer translationInView:self];

    if (_originalCenter.x+translation.x<22) {
          vwCell.center = CGPointMake(22, _originalCenter.y);
        IsvwRelease=YES;

    }
    CGRect originalFrame = CGRectMake(0, vwCell.frame.origin.y,
                                      vwCell.bounds.size.width, vwCell.bounds.size.height);
    if (!_deleteOnDragRelease) {
        // if the item is not being dragged far enough , snap back to the original location
        [UIView animateWithDuration:0.2
                         animations:^{
                             vwCell.frame = originalFrame;
                         }
         ];
    }
}

JSON.stringify doesn't work with normal Javascript array

Json has to have key-value pairs. Tho you can still have an array as the value part. Thus add a "key" of your chousing:

var json = JSON.stringify({whatver: test});

How to add a new column to a CSV file?

I don't see where you're adding the new column, but try this:

    import csv
    i = 0
    Berry = open("newcolumn.csv","r").readlines()
    with open(input.csv,'r') as csvinput:
        with open(output.csv, 'w') as csvoutput:
            writer = csv.writer(csvoutput)
            for row in csv.reader(csvinput):
                writer.writerow(row+","+Berry[i])
                i++

C# how to convert File.ReadLines into string array?

File.ReadLines() returns an object of type System.Collections.Generic.IEnumerable<String>
File.ReadAllLines() returns an array of strings.

If you want to use an array of strings you need to call the correct function.

You could use Jim solution, just use ReadAllLines() or you could change your return type.

This would also work:

System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("c:\\file.txt");

You can use any generic collection which implements IEnumerable. IList for an example.

Call a Vue.js component method from outside the component

You can set ref for child components then in parent can call via $refs:

Add ref to child component:

<my-component ref="childref"></my-component>

Add click event to parent:

<button id="external-button" @click="$refs.childref.increaseCount()">External Button</button>

_x000D_
_x000D_
var vm = new Vue({_x000D_
  el: '#app',_x000D_
  components: {_x000D_
    'my-component': { _x000D_
      template: '#my-template',_x000D_
      data: function() {_x000D_
        return {_x000D_
          count: 1,_x000D_
        };_x000D_
      },_x000D_
      methods: {_x000D_
        increaseCount: function() {_x000D_
          this.count++;_x000D_
        }_x000D_
      }_x000D_
    },_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<div id="app">_x000D_
  _x000D_
  <my-component ref="childref"></my-component>_x000D_
  <button id="external-button" @click="$refs.childref.increaseCount()">External Button</button>_x000D_
</div>_x000D_
  _x000D_
<template id="my-template">_x000D_
  <div style="border: 1px solid; padding: 2px;" ref="childref">_x000D_
    <p>A counter: {{ count }}</p>_x000D_
    <button @click="increaseCount">Internal Button</button>_x000D_
  </div>_x000D_
</template>
_x000D_
_x000D_
_x000D_

Hiding an Excel worksheet with VBA

You can do this programmatically using a VBA macro. You can make the sheet hidden or very hidden:

Sub HideSheet()

    Dim sheet As Worksheet

    Set sheet = ActiveSheet

    ' this hides the sheet but users will be able 
    ' to unhide it using the Excel UI
    sheet.Visible = xlSheetHidden

    ' this hides the sheet so that it can only be made visible using VBA
    sheet.Visible = xlSheetVeryHidden

End Sub

Sublime 3 - Set Key map for function Goto Definition

For anyone else who wants to set Eclipse style goto definition, you need to create .sublime-mousemap file in Sublime User folder.

Windows - create Default (Windows).sublime-mousemap in %appdata%\Sublime Text 3\Packages\User

Linux - create Default (Linux).sublime-mousemap in ~/.config/sublime-text-3/Packages/User

Mac - create Default (OSX).sublime-mousemap in ~/Library/Application Support/Sublime Text 3/Packages/User

Now open that file and put the following configuration inside

[
    {
        "button": "button1", 
        "count": 1, 
        "modifiers": ["ctrl"],
        "press_command": "drag_select",
        "command": "goto_definition"
    }
]

You can change modifiers key as you like.


Since Ctrl-button1 on Windows and Linux is used for multiple selections, adding a second modifier key like Alt might be a good idea if you want to use both features:

[
    {
        "button": "button1", 
        "count": 1, 
        "modifiers": ["ctrl", "alt"],
        "press_command": "drag_select",
        "command": "goto_definition"
    }
]

Alternatively, you could use the right mouse button (button2) with Ctrl alone, and not interfere with any built-in functions.

How to get the Power of some Integer in Swift language?

It turns out you can also use pow(). For example, you can use the following to express 10 to the 9th.

pow(10, 9)

Along with pow, powf() returns a float instead of a double. I have only tested this on Swift 4 and macOS 10.13.

Center the content inside a column in Bootstrap 4

Really simple answer in bootstrap 4, change this

<row>
  ...
</row>

to this

<row justify-content-center>
  ...
</row>

Remove blank values from array using C#

If you are using .NET 3.5+ you could use LINQ (Language INtegrated Query).

test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();

How to know Hive and Hadoop versions from command prompt?

another way is to make a REST call, if you have WebHCat (part of Hive project) installed, is

curl -i http://172.22.123.63:50111/templeton/v1/version/hive?user.name=foo

which will come back with JSON like

{"module":"hive","version":"1.2.1.2.3.0.0-2458"}

WebHCat docs has some details

horizontal scrollbar on top and bottom of table

Linking the scrollers worked, but in the way it's written it creates a loop which makes scrolling slow in most browsers if you click on the part of the lighter scrollbar and hold it (not when dragging the scroller).

I fixed it with a flag:

$(function() {
    x = 1;
    $(".wrapper1").scroll(function() {
        if (x == 1) {
            x = 0;
            $(".wrapper2")
                .scrollLeft($(".wrapper1").scrollLeft());
        } else {
            x = 1;
        }
    });


    $(".wrapper2").scroll(function() {
        if (x == 1) {
            x = 0;
            $(".wrapper1")
                .scrollLeft($(".wrapper2").scrollLeft());
        } else {
            x = 1;
        }
    });
});

Is __init__.py not required for packages in Python 3.3+

Based on my experience, even with python 3.3+, an empty __init__.py is still needed sometimes. One situation is when you want to refer a subfolder as a package. For example, when I ran python -m test.foo, it didn't work until I created an empty __init__.py under the test folder. And I'm talking about 3.6.6 version here which is pretty recent.

Apart from that, even for reasons of compatibility with existing source code or project guidelines, its nice to have an empty __init__.py in your package folder.

Remove unwanted parts from strings in a column

Suppose your DF is having those extra character in between numbers as well.The last entry.

  result   time
0   +52A  09:00
1   +62B  10:00
2   +44a  11:00
3   +30b  12:00
4  -110a  13:00
5   3+b0  14:00

You can try str.replace to remove characters not only from start and end but also from in between.

DF['result'] = DF['result'].str.replace('\+|a|b|\-|A|B', '')

Output:

  result   time
0     52  09:00
1     62  10:00
2     44  11:00
3     30  12:00
4    110  13:00
5     30  14:00

how to display progress while loading a url to webview in android?

Check out the sample code. It help you.

 private ProgressBar progressBar;
 progressBar=(ProgressBar)findViewById(R.id.webloadProgressBar);
 WebView urlWebView= new WebView(Context);
    urlWebView.setWebViewClient(new AppWebViewClients(progressBar));
                        urlWebView.getSettings().setJavaScriptEnabled(true);
                        urlWebView.loadUrl(detailView.getUrl());

public class AppWebViewClients extends WebViewClient {
     private ProgressBar progressBar;

    public AppWebViewClients(ProgressBar progressBar) {
        this.progressBar=progressBar;
        progressBar.setVisibility(View.VISIBLE);
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);
        progressBar.setVisibility(View.GONE);
    }
}

Thanks.

Why number 9 in kill -9 command in unix?

The -9 is the signal_number, and specifies that the kill message sent should be of the KILL (non-catchable, non-ignorable) type.

kill -9 pid

Which is same as below.

kill -SIGKILL pid

Without specifying a signal_number the default is -15, which is TERM (software termination signal). Typing kill <pid> is the same as kill -15 <pid>.

Data binding to SelectedItem in a WPF Treeview

(Let's just all agree that TreeView is obviously busted in respect to this problem. Binding to SelectedItem would have been obvious. Sigh)

I needed the solution to interact properly with the IsSelected property of TreeViewItem, so here's how I did it:

// the Type CustomThing needs to implement IsSelected with notification
// for this to work.
public class CustomTreeView : TreeView
{
    public CustomThing SelectedCustomThing
    {
        get
        {
            return (CustomThing)GetValue(SelectedNode_Property);
        }
        set
        {
            SetValue(SelectedNode_Property, value);
            if(value != null) value.IsSelected = true;
        }
    }

    public static DependencyProperty SelectedNode_Property =
        DependencyProperty.Register(
            "SelectedCustomThing",
            typeof(CustomThing),
            typeof(CustomTreeView),
            new FrameworkPropertyMetadata(
                null,
                FrameworkPropertyMetadataOptions.None,
                SelectedNodeChanged));

    public CustomTreeView(): base()
    {
        this.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(SelectedItemChanged_CustomHandler);
    }

    void SelectedItemChanged_CustomHandler(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        SetValue(SelectedNode_Property, SelectedItem);
    }

    private static void SelectedNodeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var treeView = d as CustomTreeView;
        var newNode = e.NewValue as CustomThing;

        treeView.SelectedCustomThing = (CustomThing)e.NewValue;
    }
}

With this XAML:

<local:CustonTreeView ItemsSource="{Binding TreeRoot}" 
    SelectedCustomThing="{Binding SelectedNode,Mode=TwoWay}">
    <TreeView.ItemContainerStyle>
        <Style TargetType="TreeViewItem">
            <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
        </Style>
    </TreeView.ItemContainerStyle>
</local:CustonTreeView>

apache not accepting incoming connections from outside of localhost

If you are using RHEL/CentOS 7 (the OP was not, but I thought I'd share the solution for my case), then you will need to use firewalld instead of the iptables service mentioned in other answers.

firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --reload

And then check that it is running with:

firewall-cmd --permanent --zone=public --list-all

It should list 80/tcp under ports

Moving Panel in Visual Studio Code to right side

As of October 2018 (version 1.29) the button in @mvvijesh's answer no longer exists.

You now have 2 options. Right click the panel's toolbar (nowhere else on the panel will work) and choose "move panel right/bottom":

Or choose "View: Toggle Panel Position" from the command palette.

Source: VSCode update notes: https://code.visualstudio.com/updates/v1_29#_panel-position-button-to-context-menu

C - determine if a number is prime

I would just add that no even number (bar 2) can be a prime number. This results in another condition prior to for loop. So the end code should look like this:

int IsPrime(unsigned int number) {
    if (number <= 1) return 0; // zero and one are not prime
    if ((number > 2) && ((number % 2) == 0)) return 0; //no even number is prime number (bar 2)
    unsigned int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
}

React Modifying Textarea Values

As a newbie in React world, I came across a similar issues where I could not edit the textarea and struggled with binding. It's worth knowing about controlled and uncontrolled elements when it comes to react.

The value of the following uncontrolled textarea cannot be changed because of value

 <textarea type="text" value="some value"
    onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following uncontrolled textarea can be changed because of use of defaultValue or no value attribute

<textarea type="text" defaultValue="sample" 
    onChange={(event) => this.handleOnChange(event)}></textarea>

<textarea type="text" 
   onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following controlled textarea can be changed because of how value is mapped to a state as well as the onChange event listener

<textarea value={this.state.textareaValue} 
onChange={(event) => this.handleOnChange(event)}></textarea>

Here is my solution using different syntax. I prefer the auto-bind than manual binding however, if I were to not use {(event) => this.onXXXX(event)} then that would cause the content of textarea to be not editable OR the event.preventDefault() does not work as expected. Still a lot to learn I suppose.

class Editor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textareaValue: ''
    }
  }
  handleOnChange(event) {
    this.setState({
      textareaValue: event.target.value
    })
  }
  handleOnSubmit(event) {
    event.preventDefault();
    this.setState({
      textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
    })
  }
  render() {
    return <div>
        <form onSubmit={(event) => this.handleOnSubmit(event)}>
          <textarea rows={10} cols={30} value={this.state.textareaValue} 
            onChange={(event) => this.handleOnChange(event)}></textarea>
          <br/>
          <input type="submit" value="Save"/>
        </form>
      </div>
  }
}
ReactDOM.render(<Editor />, document.getElementById("content"));

The versions of libraries are

"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4" 

Finding what methods a Python object has

The simplest method is to use dir(objectname). It will display all the methods available for that object. Cool trick.

findViewByID returns null

It crashed for me because one of fields in my activity id was matching with id in an other activity. I fixed it by giving a unique id.

In my loginActivity.xml password field id was "password". In my registration activity I just fixed it by giving id r_password, then it returned not null object:

password = (EditText)findViewById(R.id.r_password);

How to write to a file, using the logging Python module?

import sys
import logging

from util import reducer_logfile
logging.basicConfig(filename=reducer_logfile, format='%(message)s',
                    level=logging.INFO, filemode='w')

How to define two angular apps / modules in one page?

Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead. AngularJS applications cannot be nested within each other. -- http://docs.angularjs.org/api/ng.directive:ngApp

See also

Iterating through all nodes in XML file

I think the fastest and simplest way would be to use an XmlReader, this will not require any recursion and minimal memory foot print.

Here is a simple example, for compactness I just used a simple string of course you can use a stream from a file etc.

  string xml = @"
    <parent>
      <child>
        <nested />
      </child>
      <child>
        <other>
        </other>
      </child>
    </parent>
    ";

  XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
  while (rdr.Read())
  {
    if (rdr.NodeType == XmlNodeType.Element)
    {
      Console.WriteLine(rdr.LocalName);
    }
  }

The result of the above will be

parent
child
nested
child
other

A list of all the elements in the XML document.

Check if a path represents a file or a folder

public static boolean isDirectory(String path) {
    return path !=null && new File(path).isDirectory();
}

To answer the question directly.

How to navigate through a vector using iterators? (C++)

Vector's iterators are random access iterators which means they look and feel like plain pointers.

You can access the nth element by adding n to the iterator returned from the container's begin() method, or you can use operator [].

std::vector<int> vec(10);
std::vector<int>::iterator it = vec.begin();

int sixth = *(it + 5);
int third = *(2 + it);
int second = it[1];

Alternatively you can use the advance function which works with all kinds of iterators. (You'd have to consider whether you really want to perform "random access" with non-random-access iterators, since that might be an expensive thing to do.)

std::vector<int> vec(10);
std::vector<int>::iterator it = vec.begin();

std::advance(it, 5);
int sixth = *it;

How to call a JavaScript function, declared in <head>, in the body when I want to call it

I'm not sure what you mean by "myself".

Any JavaScript function can be called by an event, but you must have some sort of event to trigger it.

e.g. On page load:

<body onload="myfunction();">

Or on mouseover:

<table onmouseover="myfunction();">

As a result the first question is, "What do you want to do to cause the function to execute?"

After you determine that it will be much easier to give you a direct answer.

Override and reset CSS style: auto or none don't work

Set min-width: inherit /* Reset the min-width */

Try this. It will work.

shared global variables in C

In the header file write it with extern. And at the global scope of one of the c files declare it without extern.

jquery 3.0 url.indexOf error

@choz answer is the correct way. If you have many usages and want to make sure it works everywhere without changes you can add these small migration-snippet:

/* Migration jQuery from 1.8 to 3.x */
jQuery.fn.load = function (callback) {
    var el = $(this);

    el.on('load', callback);

    return el;
};

In this case you got no erros on other nodes e.g. on $image like in @Korsmakolnikov answer!

const $image = $('img.image').load(function() {
  $(this).doSomething();
});

$image.doSomethingElseWithTheImage();

How many socket connections can a web server handle?

To add my two cents to the conversation a process can have simultaneously open a number of sockets connected equal to this number (in Linux type sytems) /proc/sys/net/core/somaxconn

cat /proc/sys/net/core/somaxconn

This number can be modified on the fly (only by root user of course)

echo 1024 > /proc/sys/net/core/somaxconn

But entirely depends on the server process, the hardware of the machine and the network, the real number of sockets that can be connected before crashing the system

DataRow: Select cell value by a given column name

Be careful on datatype. If not match it will throw an error.

var fieldName = dataRow.Field<DataType>("fieldName");

Byte array to image conversion

try (UPDATE)

MemoryStream ms = new MemoryStream(byteArrayIn,0,byteArrayIn.Length);
ms.Position = 0; // this is important
returnImage = Image.FromStream(ms,true);

Get user info via Google API

This scope https://www.googleapis.com/auth/userinfo.profile has been deprecated now. Please look at https://developers.google.com/+/api/auth-migration#timetable.

New scope you will be using to get profile info is: profile or https://www.googleapis.com/auth/plus.login

and the endpoint is - https://www.googleapis.com/plus/v1/people/{userId} - userId can be just 'me' for currently logged in user.

How to replace an entire line in a text file by line number

On mac I used

sed -i '' -e 's/text-on-line-to-be-changed.*/text-to-replace-the=whole-line/' file-name

MySQL COUNT DISTINCT

Overall

SELECT
       COUNT(DISTINCT `site_id`) as distinct_sites
  FROM `cp_visits`
 WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)

Or per site

  SELECT
         `site_id` as site,
         COUNT(DISTINCT `user_id`) as distinct_users_per_site
    FROM `cp_visits`
   WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
GROUP BY `site_id`

Having the time column in the result doesn't make sense - since you are aggregating the rows, showing one particular time is irrelevant, unless it is the min or max you are after.

Redirect using AngularJS

Assuming you're not using html5 routing, try $location.path("route"). This will redirect your browser to #/route which might be what you want.

Installation of SQL Server Business Intelligence Development Studio

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

Business Intelligence Development Studio is Microsoft Visual Studio 2008 with additional project types that are specific to SQL Server business intelligence. Business Intelligence Development Studio is the primary environment that you will use to develop business solutions that include Analysis Services, Integration Services, and Reporting Services projects. Each project type supplies templates for creating the objects required for business intelligence solutions, and provides a variety of designers, tools, and wizards to work with the objects.

If you already have Visual Studio installed, the new project types will be installed along with SQL Server.

More Information

How can I count the numbers of rows that a MySQL query returned?

If you want the result plus the number of rows returned do something like this. Using PHP.

$query = "SELECT * FROM Employee";
$result = mysql_query($query);
echo "There are ".mysql_num_rows($result)." Employee(s).";

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

How to restrict user to type 10 digit numbers in input element?

HTML

<input type="text" name="fieldName" id="fieldSelectorId">

This field only takes at max 10 digits number and do n't accept zero as the first digit.

JQuery

jQuery(document).ready(function () {
      jQuery("#fieldSelectorId").keypress(function (e) {
         var length = jQuery(this).val().length;
       if(length > 9) {
            return false;
       } else if(e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
       } else if((length == 0) && (e.which == 48)) {
            return false;
       }
      });
    });

Why I've got no crontab entry on OS X when using vim?

As the previous posts didn't work for me because of some permissions issues, I found that creating a separate crontab file and adding it to the user's crontab with the -u parameter while root worked for me.

sudo crontab -u {USERNAME} ~/{PATH_TO_CRONTAB_FILE}

How to disable text selection highlighting

Workaround for WebKit:

/* Disable tap highlighting */
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);

I found it in a CardFlip example.

Disabling Log4J Output in Java

 log4j.rootLogger=OFF

Valid characters in a Java class name

Further to previous answers its worth noting that:

  1. Java allows any Unicode currency symbol in symbol names, so the following will all work:

$var1 £var2 €var3

I believe the usage of currency symbols originates in C/C++, where variables added to your code by the compiler conventionally started with '$'. An obvious example in Java is the names of '.class' files for inner classes, which by convention have the format 'Outer$Inner.class'

  1. Many C# and C++ programmers adopt the convention of placing 'I' in front of interfaces (aka pure virtual classes in C++). This is not required, and hence not done, in Java because the implements keyword makes it very clear when something is an interface.

Compare:

class Employee : public IPayable //C++

with

class Employee : IPayable //C#

and

class Employee implements Payable //Java

  1. Many projects use the convention of placing an underscore in front of field names, so that they can readily be distinguished from local variables and parameters e.g.

private double _salary;

A tiny minority place the underscore after the field name e.g.

private double salary_;

Split bash string by newline characters

Another way:

x=$'Some\nstring'
readarray -t y <<<"$x"

Or, if you don't have bash 4, the bash 3.2 equivalent:

IFS=$'\n' read -rd '' -a y <<<"$x"

You can also do it the way you were initially trying to use:

y=(${x//$'\n'/ })

This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'. To make it work, you need to restrict the word separator before parsing it:

IFS=$'\n' y=(${x//$'\n'/ })

...and then, since you are changing the separator, you don't need to convert the \n to space anymore, so you can simplify it to:

IFS=$'\n' y=($x)

This approach will function unless $x contains a matching globbing pattern (such as "*") - in which case it will be replaced by the matched file name(s). The read/readarray methods require newer bash versions, but work in all cases.

How to get file size in Java

Did a quick google. Seems that to find the file size you do this,

long size = f.length();

The differences between the three methods you posted can be found here

getFreeSpace() and getTotalSpace() are pretty self explanatory, getUsableSpace() seems to be the space that the JVM can use, which in most cases will be the same as the amount of free space.

Python Iterate Dictionary by Index

Some of the comments are right in saying that these answers do not correspond to the question.

One reason one might want to loop through a dictionary using "indexes" is for example to compute a distance matrix for a set of objects in a dictionary. To put it as an example (going a bit to the basics on the bullet below):

  • Assuming one have 1000 objects on a dictionary, the distance square matrix consider all combinations from one object to any other and so it would have dimensions of 1000x1000 elements. But if the distance from object 1 to object 2 is the same as from object 2 to object 1, one need to compute the distance only to less than half of the square matrix, since the diagonal will have distance 0 and the values are mirrored above and below the diagonal.

This is why most packages use a condensed distance matrix ( How does condensed distance matrix work? (pdist) )

But consider the case one is implementing the computation of a distance matrix, or any kind of permutation of the sort. In such case you need to skip the results from more than half of the cases. This means that a FOR loop that runs through all the dictionary is just hitting an IF and jumping to the next iteration without performing really any job most of the time. For large datasets this additional "IFs" and loops add up to a relevant amount on the processing time and could be avoided if, at each loop, one starts one "index" further on the dictionary.

Going than to the question, my conclusion right now is that the answer is NO. One has no way to directly access the dictionary values by any index except the key or an iterator.

I understand that most of the answers up to now applies different approaches to perform this task but really don't allow any index manipulation, that would be useful in a case such as exemplified.

The only alternative I see is to use a list or other variable as a sequential index to the dictionary. Here than goes an implementation to exemplify such case:

#!/usr/bin/python3

dishes = {'spam': 4.25, 'eggs': 1.50, 'sausage': 1.75, 'bacon': 2.00}
print("Dictionary: {}\n".format(dishes))

key_list = list(dishes.keys())
number_of_items = len(key_list)

condensed_matrix = [0]*int(round(((number_of_items**2)-number_of_items)/2,0))
c_m_index = 0

for first_index in range(0,number_of_items):
    for second_index in range(first_index+1,number_of_items):
        condensed_matrix[c_m_index] = dishes[key_list[first_index]] - dishes[key_list[second_index]]
        print("{}. {}-{} = {}".format(c_m_index,key_list[first_index],key_list[second_index],condensed_matrix[c_m_index]))
        c_m_index+=1

The output is:

Dictionary: {'spam': 4.25, 'eggs': 1.5, 'sausage': 1.75, 'bacon': 2.0}

0. spam-eggs = 2.75
1. spam-sausage = 2.5
2. spam-bacon = 2.25
3. eggs-sausage = -0.25
4. eggs-bacon = -0.5
5. sausage-bacon = -0.25

Its also worth mentioning that are packages such as intertools that allows one to perform similar tasks in a shorter format.

Simple PHP form: Attachment to email (code golf)

PEAR::Mail_Mime? Sure, PEAR dependency of (min) 2 files (just mail_mime itself if you edit it to remove the pear dependencies), but it works well. Additionally, most servers have PEAR installed to some extent, and in the best cases they have Pear/Mail and Pear/Mail_Mime. Something that cannot be said for most other libraries offering the same functionality.

You may also consider looking in to PHP's IMAP extension. It's a little more complicated, and requires more setup (not enabled or installed by default), but is must more efficient at compilng and sending messages to an IMAP capable server.

Does Java read integers in little endian or big endian?

There are no unsigned integers in Java. All integers are signed and in big endian.

On the C side the each byte has tne LSB at the start is on the left and the MSB at the end.

It sounds like you are using LSB as Least significant bit, are you? LSB usually stands for least significant byte. Endianness is not bit based but byte based.

To convert from unsigned byte to a Java integer:

int i = (int) b & 0xFF;

To convert from unsigned 32-bit little-endian in byte[] to Java long (from the top of my head, not tested):

long l = (long)b[0] & 0xFF;
l += ((long)b[1] & 0xFF) << 8;
l += ((long)b[2] & 0xFF) << 16;
l += ((long)b[3] & 0xFF) << 24;