Programs & Examples On #Asprepeater

Constraint Layout Vertical Align Center

May be i did not fully understand the problem, but, centering all view inside a ConstraintLayout seems very simple. This is what I used:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center">

enter image description here

Last two lines did the trick!

Comparing two .jar files

Please try http://www.osjava.org/jardiff/ - tool is old and the dependency list is large. From the docs, it looks like worth trying.

How to merge lists into a list of tuples?

I am not sure if this a pythonic way or not but this seems simple if both lists have the same number of elements :

list_a = [1, 2, 3, 4]

list_b = [5, 6, 7, 8]

list_c=[(list_a[i],list_b[i]) for i in range(0,len(list_a))]

Removing items from a ListBox in VB.net

Here's the code I came up with to remove items selected by a user from a listbox It seems to work ok in a multiselect listbox (selectionmode prop is set to multiextended).:

Private Sub cmdRemoveList_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdRemoveList.Click
    Dim knt As Integer = lstwhatever.SelectedIndices.Count
    Dim i As Integer
    For i = 0 To knt - 1
        lstwhatever.Items.RemoveAt(lstwhatever.SelectedIndex)
    Next
End Sub

Self-reference for cell, column and row in worksheet functions

I don't see the need for Indirect, especially for conditional formatting.

The simplest way to self-reference a cell, row or column is to refer to it normally, e.g., "=A1" in cell A1, and make the reference partly or completely relative. For example, in a conditional formatting formula for checking whether there's a value in the first column of various cells' rows, enter the following with A1 highlighted and copy as necessary. The conditional formatting will always refer to column A for the row of each cell:

= $A1 <> ""

How to monitor SQL Server table changes by using c#?

Another, very simple way of monitoring tables is table versioning. The system is proven working in constructions such as DNS synchronization. To make it work you create a table containing table names and table versions as decimal or bigint.In each table that you need monitored, create trigger on insert, update and delete that will increment appropriate table version in versioning table when executed. If you expect any of the monitored tables to be altered often, you need to provision for version reusing. Finally, in your application, every time you query monitored table, you also query its version and store it. When you go to alter the monitored table from your app, you first query its current version and process the change only if the version is unchanged. You can have stored proc on sql server do that work for you. This is extremely simple but proven solid solution. It has specific functional use (to ensure data consistency) and is light on resources (you do not raise brokered events that you would not watch for) but needs application to actively check for changes rather than passively wait for event to happen.

Hibernate: flush() and commit()

flush(); Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory. It will update or insert into your tables in the running transaction, but it may not commit those changes.

You need to flush in batch processing otherwise it may give OutOfMemoryException.

Commit(); Commit will make the database commit. When you have a persisted object and you change a value on it, it becomes dirty and hibernate needs to flush these changes to your persistence layer. So, you should commit but it also ends the unit of work (transaction.commit()).

XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

Essentially the only way to deal with this is to have a webserver running on localhost and to serve them from there.

It is insecure for a browser to allow an ajax request to access any file on your computer, therefore most browsers seem to treat "file://" requests as having no origin for the purpose of "Same Origin Policy"

Starting a webserver can be as trivial as cding into the directory the files are in and running:

python -m SimpleHTTPServer

Multiple lines of input in <input type="text" />

You can't. At the time of writing, the only HTML form element that's designed to be multi-line is <textarea>.

Do you need to dispose of objects and set them to null?

Normally, there's no need to set fields to null. I'd always recommend disposing unmanaged resources however.

From experience I'd also advise you to do the following:

  • Unsubscribe from events if you no longer need them.
  • Set any field holding a delegate or an expression to null if it's no longer needed.

I've come across some very hard to find issues that were the direct result of not following the advice above.

A good place to do this is in Dispose(), but sooner is usually better.

In general, if a reference exists to an object the garbage collector (GC) may take a couple of generations longer to figure out that an object is no longer in use. All the while the object remains in memory.

That may not be a problem until you find that your app is using a lot more memory than you'd expect. When that happens, hook up a memory profiler to see what objects are not being cleaned up. Setting fields referencing other objects to null and clearing collections on disposal can really help the GC figure out what objects it can remove from memory. The GC will reclaim the used memory faster making your app a lot less memory hungry and faster.

Test if numpy array contains only zeros

The other answers posted here will work, but the clearest and most efficient function to use is numpy.any():

>>> all_zeros = not np.any(a)

or

>>> all_zeros = not a.any()
  • This is preferred over numpy.all(a==0) because it uses less RAM. (It does not require the temporary array created by the a==0 term.)
  • Also, it is faster than numpy.count_nonzero(a) because it can return immediately when the first nonzero element has been found.
    • Edit: As @Rachel pointed out in the comments, np.any() no longer uses "short-circuit" logic, so you won't see a speed benefit for small arrays.

How to detect if javascript files are loaded?

Like T.J. wrote: the order is defined (at least it's sequential when your browser is about to execute any JavaScript, even if it may download the scripts in parallel somehow). However, as apparently you're having trouble, maybe you're using third-party JavaScript libraries that yield some 404 Not Found or timeout? If so, then read Best way to use Google’s hosted jQuery, but fall back to my hosted library on Google fail.

Use Toast inside Fragment

You are not calling show() on the Toast you are creating with makeText().

In Python, when to use a Dictionary, List or Set?

  • Do you just need an ordered sequence of items? Go for a list.
  • Do you just need to know whether or not you've already got a particular value, but without ordering (and you don't need to store duplicates)? Use a set.
  • Do you need to associate values with keys, so you can look them up efficiently (by key) later on? Use a dictionary.

ASP.NET MVC get textbox input value

You may use jQuery:

<input type="text" name="IP" id="IP" value=""/>
@Html.ActionLink(@Resource.ButtonTitleAdd, "Add", "Configure", new { ipValue ="xxx", TypeId = "1" }, new {@class = "link"})

<script>
  $(function () {
    $('.link').click(function () {
      var ipvalue = $("#IP").val();
      this.href = this.href.replace("xxx", ipvalue);
    });
  });
</script>

getElementById returns null?

There could be many reason why document.getElementById doesn't work

  • You have an invalid ID

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). (resource: What are valid values for the id attribute in HTML?)

  • you used some id that you already used as <meta> name in your header (e.g. copyright, author... ) it looks weird but happened to me: if your 're using IE take a look at (resource: http://www.phpied.com/getelementbyid-description-in-ie/)

  • you're targeting an element inside a frame or iframe. In this case if the iframe loads a page within the same domain of the parent you should target the contentdocument before looking for the element (resource: Calling a specific id inside a frame)

  • you're simply looking to an element when the node is not effectively loaded in the DOM, or maybe it's a simple misspelling

I doubt you used same ID twice or more: in that case document.getElementById should return at least the first element

CSS3 animate border color

You can try this also...

_x000D_
_x000D_
button {
  background: none;
  border: 0;
  box-sizing: border-box;
  margin: 1em;
  padding: 1em 2em;
  box-shadow: inset 0 0 0 2px #f45e61;
  color: #f45e61;
  font-size: inherit;
  font-weight: 700;
  vertical-align: middle;
  position: relative;
}
button::before, button::after {
  box-sizing: inherit;
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
}

.draw {
  -webkit-transition: color 0.25s;
  transition: color 0.25s;
}
.draw::before, .draw::after {
  border: 2px solid transparent;
  width: 0;
  height: 0;
}
.draw::before {
  top: 0;
  left: 0;
}
.draw::after {
  bottom: 0;
  right: 0;
}
.draw:hover {
  color: #60daaa;
}
.draw:hover::before, .draw:hover::after {
  width: 100%;
  height: 100%;
}
.draw:hover::before {
  border-top-color: #60daaa;
  border-right-color: #60daaa;
  -webkit-transition: width 0.25s ease-out, height 0.25s ease-out 0.25s;
  transition: width 0.25s ease-out, height 0.25s ease-out 0.25s;
}
.draw:hover::after {
  border-bottom-color: #60daaa;
  border-left-color: #60daaa;
  -webkit-transition: border-color 0s ease-out 0.5s, width 0.25s ease-out 0.5s, height 0.25s ease-out 0.75s;
  transition: border-color 0s ease-out 0.5s, width 0.25s ease-out 0.5s, height 0.25s ease-out 0.75s;
}
_x000D_
<section class="buttons">
  <button class="draw">Draw</button>
</section>
_x000D_
_x000D_
_x000D_

Android Pop-up message

You can use Dialog to create this easily

create a Dialog instance using the context

Dialog dialog = new Dialog(contex);

You can design your layout as you like.

You can add this layout to your dialog by dialog.setContentView(R.layout.popupview);//popup view is the layout you created

then you can access its content (textviews, etc.) by using findViewById method

TextView txt = (TextView)dialog.findViewById(R.id.textbox);

you can add any text here. the text can be stored in the String.xml file in res\values.

txt.setText(getString(R.string.message));

then finally show the pop up menu

dialog.show();

more information http://developer.android.com/guide/topics/ui/dialogs.html

http://developer.android.com/reference/android/app/Dialog.html

How do I sleep for a millisecond in Perl?

Time::HiRes:

  use Time::HiRes;
  Time::HiRes::sleep(0.1); #.1 seconds
  Time::HiRes::usleep(1); # 1 microsecond.

http://perldoc.perl.org/Time/HiRes.html

Format numbers in django templates

Be aware that changing locale is process-wide and not thread safe (iow., can have side effects or can affect other code executed within the same process).

My proposition: check out the Babel package. Some means of integrating with Django templates are available.

If else on WHERE clause

try this ,hope it helps

select user_display_image as user_image,
user_display_name as user_name,
invitee_phone,
(
 CASE 
    WHEN invitee_status=1 THEN "attending" 
    WHEN invitee_status=2 THEN "unsure" 
    WHEN invitee_status=3 THEN "declined" 
    WHEN invitee_status=0 THEN "notreviwed" END
) AS  invitee_status
 FROM your_tbl

How to determine whether a given Linux is 32 bit or 64 bit?

lscpu will list out these among other information regarding your CPU:

Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
...

Javascript Object push() function

Objects does not support push property, but you can save it as well using the index as key,

_x000D_
_x000D_
var tempData = {};_x000D_
for ( var index in data ) {_x000D_
  if ( data[index].Status == "Valid" ) { _x000D_
    tempData[index] = data; _x000D_
  } _x000D_
 }_x000D_
data = tempData;
_x000D_
_x000D_
_x000D_

I think this is easier if remove the object if its status is invalid, by doing.

_x000D_
_x000D_
for(var index in data){_x000D_
  if(data[index].Status == "Invalid"){ _x000D_
    delete data[index]; _x000D_
  } _x000D_
}
_x000D_
_x000D_
_x000D_

And finally you don't need to create a var temp –

How to avoid reverse engineering of an APK file?

Nothing is secure when you put it on end-users hand but some common practice may make this harder for attacker to steal data.

  • Put your main logic (algorithms) into server side.
  • Communicate with server and client; make sure communication b/w server and client is secured via SSL or HTTPS; or use other techniques key-pair generation algorithms (ECC, RSA). Ensure that sensitive information is remain End-to-End encrypted.
  • Use sessions and expire them after specific time interval.
  • Encrypt resources and fetch them from server on demand.
  • Or you can make Hybrid app which access system via webview protect resource + code on server

Multiple approaches; this is obvious you have to sacrifice among performance and security

How to read all rows from huge table?

So it turns out that the crux of the problem is that by default, Postgres starts in "autoCommit" mode, and also it needs/uses cursors to be able to "page" through data (ex: read the first 10K results, then the next, then the next), however cursors can only exist within a transaction. So the default is to read all rows, always, into RAM, and then allow your program to start processing "the first result row, then the second" after it has all arrived, for two reasons, it's not in a transaction (so cursors don't work), and also a fetch size hasn't been set.

So how the psql command line tool achieves batched response (its FETCH_COUNT setting) for queries, is to "wrap" its select queries within a short-term transaction (if a transaction isn't yet open), so that cursors can work. You can do something like that also with JDBC:

  static void readLargeQueryInChunksJdbcWay(Connection conn, String originalQuery, int fetchCount, ConsumerWithException<ResultSet, SQLException> consumer) throws SQLException {
    boolean originalAutoCommit = conn.getAutoCommit();
    if (originalAutoCommit) {
      conn.setAutoCommit(false); // start temp transaction
    }
    try (Statement statement = conn.createStatement()) {
      statement.setFetchSize(fetchCount);
      ResultSet rs = statement.executeQuery(originalQuery);
      while (rs.next()) {
        consumer.accept(rs); // or just do you work here
      }
    } finally {
      if (originalAutoCommit) {
        conn.setAutoCommit(true); // reset it, also ends (commits) temp transaction
      }
    }
  }
  @FunctionalInterface
  public interface ConsumerWithException<T, E extends Exception> {
    void accept(T t) throws E;
  }

This gives the benefit of requiring less RAM, and, in my results, seemed to run overall faster, even if you don't need to save the RAM. Weird. It also gives the benefit that your processing of the first row "starts faster" (since it process it a page at a time).

And here's how to do it the "raw postgres cursor" way, along with full demo code, though in my experiments it seemed the JDBC way, above, was slightly faster for whatever reason.

Another option would be to have autoCommit mode off, everywhere, though you still have to always manually specify a fetchSize for each new Statement (or you can set a default fetch size in the URL string).

How to add number of days to today's date?

You could extend the javascript Date object like this

Date.prototype.addDays = function(days) {
    this.setDate(this.getDate() + parseInt(days));
    return this;
};

and in your javascript code you could call

var currentDate = new Date();
// to add 4 days to current date
currentDate.addDays(4);

ORA-01652 Unable to extend temp segment by in tablespace

You don't need to create a new datafile; you can extend your existing tablespace data files.

Execute the following to determine the filename for the existing tablespace:

  SELECT * FROM DBA_DATA_FILES;

Then extend the size of the datafile as follows (replace the filename with the one from the previous query):

  ALTER DATABASE DATAFILE 'D:\ORACLEXE\ORADATA\XE\SYSTEM.DBF' RESIZE 2048M; 

NPM global install "cannot find module"

I got this error Error: Cannot find module 'number-is-nan' whereas the module actually exists. It was due to a bad/incomplete Node.js installation.

For Windows , as other answers suggest it, you need a clean Node installation :

  • Uninstall Node.js
  • Delete the two folders npm and npm_cache in C:\Users\user\AppData\Roaming
  • Restart Windows and install Node.js
  • Run npm initor (npm init --yes for default config)
  • Set the Windows environment variable for NODE_PATH. This path is where your packages are installed. It's probably something likeNODE_PATH = C:\Users\user\node_modules or C:\Users\user\AppData\Roaming\npm\node_modules
  • Start a new cmd console and npm should work fine

Note :

Try the last points before reinstalling Node.js, it could save you some time and avoid to re-install all your packages.

#include errors detected in vscode

The answer is here: How to use C/Cpp extension and add includepath to configurations.

Click the light bulb and then edit the JSON file which is opened. Choose the right block corresponding to your platform (there are Mac, Linux, Win32 – ms-vscode.cpptools version: 3). Update paths in includePath (matters if you compile with VS Code) or browse.paths (matters if you navigate with VS Code) or both.

Thanks to @Francesco Borzì, I will append his answer here:

You have to Left click on the bulb next to the squiggled code line.

If a #include file or one of its dependencies cannot be found, you can also click on the red squiggles under the include statements to view suggestions for how to update your configuration.

enter image description here

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

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

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

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

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

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

Regular expression to extract text between square brackets

([[][a-z \s]+[]])

Above should work given the following explaination

  • characters within square brackets[] defines characte class which means pattern should match atleast one charcater mentioned within square brackets

  • \s specifies a space

  •  + means atleast one of the character mentioned previously to +.

How to disable a ts rule for a specific line?

@ts-expect-error

TS 3.9 introduces a new magic comment. @ts-expect-error will:

  • have same functionality as @ts-ignore
  • trigger an error, if actually no compiler error has been suppressed (= indicates useless flag)
if (false) {
  // @ts-expect-error: Let's ignore a single compiler error like this unreachable code 
  console.log("hello"); // compiles
}

// If @ts-expect-error didn't suppress anything at all, we now get a nice warning 
let flag = true;
// ...
if (flag) {
  // @ts-expect-error
  // ^~~~~~~~~~~~~~~^ error: "Unused '@ts-expect-error' directive.(2578)"
  console.log("hello"); 
}

Alternatives

@ts-ignore and @ts-expect-error can be used for all sorts of compiler errors. For type issues (like in OP), I recommend one of the following alternatives due to narrower error suppression scope:

? Use any type

// type assertion for single expression
delete ($ as any).summernote.options.keyMap.pc.TAB;

// new variable assignment for multiple usages
const $$: any = $
delete $$.summernote.options.keyMap.pc.TAB;
delete $$.summernote.options.keyMap.mac.TAB;

? Augment JQueryStatic interface

// ./global.d.ts
interface JQueryStatic {
  summernote: any;
}

// ./main.ts
delete $.summernote.options.keyMap.pc.TAB; // works

In other cases, shorthand module declarations or module augmentations for modules with no/extendable types are handy utilities. A viable strategy is also to keep not migrated code in .js and use --allowJs with checkJs: false.

What are Maven goals and phases and what is their difference?

Life cycle is a sequence of named phases.
Phases executes sequentially. Executing a phase means executes all previous phases.

Plugin is a collection of goals also called MOJO (Maven Old Java Object).
Analogy : Plugin is a class and goals are methods within the class.

Maven is based around the central concept of a Build Life Cycles. Inside each Build Life Cycles there are Build Phases, and inside each Build Phases there are Build Goals.

We can execute either a build phase or build goal. When executing a build phase we execute all build goals within that build phase. Build goals are assigned to one or more build phases. We can also execute a build goal directly.

There are three major built-in Build Life Cycles:

  1. default
  2. clean
  3. site

Each Build Lifecycle is Made Up of Phases

For example the default lifecycle comprises of the following Build Phases:

?validate - validate the project is correct and all necessary information is available
?compile - compile the source code of the project
?test - test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
?package - take the compiled code and package it in its distributable format, such as a JAR.
?integration-test - process and deploy the package if necessary into an environment where integration tests can be run
?verify - run any checks to verify the package is valid and meets quality criteria
?install - install the package into the local repository, for use as a dependency in other projects locally
?deploy - done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

So to go through the above phases, we just have to call one command:

mvn <phase> { Ex: mvn install }

For the above command, starting from the first phase, all the phases are executed sequentially till the ‘install’ phase. mvn can either execute a goal or a phase (or even multiple goals or multiple phases) as follows:

mvn clean install plugin:goal  

However, if you want to customize the prefix used to reference your plugin, you can specify the prefix directly through a configuration parameter on the maven-plugin-plugin in your plugin's POM.

A Build Phase is Made Up of Plugin Goals

Most of Maven's functionality is in plugins. A plugin provides a set of goals that can be executed using the following syntax:

 mvn [plugin-name]:[goal-name]

For example, a Java project can be compiled with the compiler-plugin's compile-goal by running mvn compiler:compile.

Build lifecycle is a list of named phases that can be used to give order to goal execution.

Goals provided by plugins can be associated with different phases of the lifecycle. For example, by default, the goal compiler:compile is associated with the compile phase, while the goal surefire:test is associated with the test phase. Consider the following command:

mvn test

When the preceding command is executed, Maven runs all goals associated with each of the phases up to and including the test phase. In such a case, Maven runs the resources:resources goal associated with the process-resources phase, then compiler:compile, and so on until it finally runs the surefire:test goal.

However, even though a build phase is responsible for a specific step in the build lifecycle, the manner in which it carries out those responsibilities may vary. And this is done by declaring the plugin goals bound to those build phases.

A plugin goal represents a specific task (finer than a build phase) which contributes to the building and managing of a project. It may be bound to zero or more build phases. A goal not bound to any build phase could be executed outside of the build lifecycle by direct invocation. The order of execution depends on the order in which the goal(s) and the build phase(s) are invoked. For example, consider the command below. The clean and package arguments are build phases, while the dependency:copy-dependencies is a goal (of a plugin).

mvn clean dependency:copy-dependencies package

If this were to be executed, the clean phase will be executed first (meaning it will run all preceding phases of the clean lifecycle, plus the clean phase itself), and then the dependency:copy-dependencies goal, before finally executing the package phase (and all its preceding build phases of the default lifecycle).

Moreover, if a goal is bound to one or more build phases, that goal will be called in all those phases.

Furthermore, a build phase can also have zero or more goals bound to it. If a build phase has no goals bound to it, that build phase will not execute. But if it has one or more goals bound to it, it will execute all those goals.

Built-in Lifecycle Bindings
Some phases have goals bound to them by default. And for the default lifecycle, these bindings depend on the packaging value.

Maven Architecture:

enter image description here

Reference 1
Reference 2

Eclipse sample for Maven Lifecycle Mapping

Eclipse sample for Maven Lifecycle Mapping

How to get an absolute file path in Python

You could use the new Python 3.4 library pathlib. (You can also get it for Python 2.6 or 2.7 using pip install pathlib.) The authors wrote: "The aim of this library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations users do over them."

To get an absolute path in Windows:

>>> from pathlib import Path
>>> p = Path("pythonw.exe").resolve()
>>> p
WindowsPath('C:/Python27/pythonw.exe')
>>> str(p)
'C:\\Python27\\pythonw.exe'

Or on UNIX:

>>> from pathlib import Path
>>> p = Path("python3.4").resolve()
>>> p
PosixPath('/opt/python3/bin/python3.4')
>>> str(p)
'/opt/python3/bin/python3.4'

Docs are here: https://docs.python.org/3/library/pathlib.html

How can I write text on a HTML5 canvas element?

It is easy to write text to a canvas. Lets say that you canvas is declared like below.

<html>
  <canvas id="YourCanvas" width="500" height="500">
   Your Internet Browser does not support HTML5 (Get a new Browser)
  </canvas>
</html>

This part of the code returns a variable into canvas which is a representation of your canvas in HTML.

  var c  = document.getElementById("YourCanvas");

The following code returns the methods for drawing lines, text, fills to your canvas.

  var ctx = canvas.getContext("2d");

<script>
  ctx.font="20px Times Roman";
  ctx.fillText("Hello World!",50,100);

  ctx.font="30px Verdana";

  var g = ctx.createLinearGradient(0,0,c.width,0);

  g.addColorStop("0","magenta");
  g.addColorStop("0.3","blue");
  g.addColorStop("1.0","red");

  ctx.fillStyle=g; //Sets the fille of your text here. In this case it is set to the gradient that was created above. But you could set it to Red, Green, Blue or whatever.

  ctx.fillText("This is some new and funny TEXT!",40,190);
</script>

There is a beginners guide out on Amazon for the kindle http://www.amazon.com/HTML5-Canvas-Guide-Beginners-ebook/dp/B00JSFVY9O/ref=sr_1_4?ie=UTF8&qid=1398113376&sr=8-4&keywords=html5+canvas+beginners that is well worth the money. I purchased it a couple of days ago and it showed me a lot of simple techniques that were very useful.

Adding custom HTTP headers using JavaScript

I think the easiest way to accomplish it is to use querystring instead of HTTP headers.

Max parallel http connections in a browser?

Max Number of default simultaneous persistent connections per server/proxy:

Firefox 2:  2
Firefox 3+: 6
Opera 9.26: 4
Opera 12:   6
Safari 3:   4
Safari 5:   6
IE 7:       2
IE 8:       6
IE 10:      8
Edge:       6
Chrome:     6

The limit is per-server/proxy, so your wildcard scheme will work.

FYI: this is specifically related to HTTP 1.1; other protocols have separate concerns and limitations (i.e., SPDY, TLS, HTTP 2).

List of Java class file format major version numbers?

If you have a class file at build/com/foo/Hello.class, you can check what java version it is compiled at using the command:

javap -v build/com/foo/Hello.class | grep "major"

Example usage:

$ javap -v build/classes/java/main/org/aguibert/liberty/Book.class | grep major
  major version: 57

According to the table in the OP, major version 57 means the class file was compiled to JDK 13 bytecode level

Links not going back a directory?

To go up a directory in a link, use ... This means "go up one directory", so your link will look something like this:

<a href="../index.html">Home</a>

How does ifstream's eof() work?

The EOF flag is only set after a read operation attempts to read past the end of the file. get() is returning the symbolic constant traits::eof() (which just happens to equal -1) because it reached the end of the file and could not read any more data, and only at that point will eof() be true. If you want to check for this condition, you can do something like the following:

int ch;
while ((ch = inf.get()) != EOF) {
    std::cout << static_cast<char>(ch) << "\n";
}

What does HTTP/1.1 302 mean exactly?

This question was asked a long ago, while the RFC 2616 was still hanging around. Some answers to this question are based in such document, which is no longer relevant nowadays. Quoting Mark Nottingham who, at the time of writing, co-chairs the IETF HTTP and QUIC Working Groups:

Don’t use RFC2616. Delete it from your hard drives, bookmarks, and burn (or responsibly recycle) any copies that are printed out.

The old RFC 2616 has been supplanted by the following documents that, together, define the HTTP/1.1 protocol:

So I aim to provide an answer based in the RFC 7231 which is the current reference for HTTP/1.1 status codes.

The 302 status code

A response with 302 is a common way of performing URL redirection. Along with the 302 status code, the response should include a Location header with a different URI. Such header will be parsed by the user agent and then perform the redirection:


Redirection example


Web browsers may change from POST to GET in the subsequent request. If this behavior is undesired, the 307 (Temporary Redirect) status code can be used instead.

This is how the 302 status code is defined in the RFC 7231:

6.4.3. 302 Found

The 302 (Found) status code indicates that the target resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client ought to continue to use the effective request URI for future requests.

The server SHOULD generate a Location header field in the response containing a URI reference for the different URI. The user agent MAY use the Location field value for automatic redirection. The server's response payload usually contains a short hypertext note with a hyperlink to the different URI(s).

Note: For historical reasons, a user agent MAY change the request method from POST to GET for the subsequent request. If this behavior is undesired, the 307 (Temporary Redirect) status code can be used instead.

According to MDN web docs from Mozilla, a typical use case for 302 is:

The Web page is temporarily not available for reasons that have not been unforeseen. That way, search engines don't update their links.

Other status codes for redirection

The RFC 7231 defines the following status codes for redirection:

  • 301 (Moved Permanently)
  • 302 (Found)
  • 307 (Temporary Redirect)

The RFC 7238 was created to define another status code for redirection:

  • 308 (Permanent Redirect)

Refer to this answer for further details.

How do I read a file line by line in VB Script?

When in doubt, read the documentation:

filename = "C:\Temp\vblist.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

Do Until f.AtEndOfStream
  WScript.Echo f.ReadLine
Loop

f.Close

Select multiple images from android gallery

A lot of these answers have similarities but are all missing the most important part which is in onActivityResult, check if data.getClipData is null before checking data.getData

The code to call the file chooser:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*"); //allows any image file type. Change * to specific extension to limit it
//**The following line is the important one!
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURES); //SELECT_PICTURES is simply a global int used to check the calling intent in onActivityResult

The code to get all of the images selected:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == SELECT_PICTURES) {
        if(resultCode == Activity.RESULT_OK) {
            if(data.getClipData() != null) {
                int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
                for(int i = 0; i < count; i++)  
                    Uri imageUri = data.getClipData().getItemAt(i).getUri();
                    //do something with the image (save it to some directory or whatever you need to do with it here) 
                }
            } else if(data.getData() != null) {
                String imagePath = data.getData().getPath();
                //do something with the image (save it to some directory or whatever you need to do with it here)
            }
        }
    }
}

Note that Android's chooser has Photos and Gallery available on some devices. Photos allows multiple images to be selected. Gallery allows just one at a time.

How to turn a vector into a matrix in R?

Just use matrix:

matrix(vec,nrow = 7,ncol = 7)

One advantage of using matrix rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow argument in matrix.

jQuery $(this) keyword

$(this) returns a cached version of the element, hence improving performance since jQuery doesn't have to do a complete lookup in the DOM of the element again.

ReactJS - Call One Component Method From Another Component

You can do something like this

import React from 'react';

class Header extends React.Component {

constructor() {
    super();
}

checkClick(e, notyId) {
    alert(notyId);
}

render() {
    return (
        <PopupOver func ={this.checkClick } />
    )
}
};

class PopupOver extends React.Component {

constructor(props) {
    super(props);
    this.props.func(this, 1234);
}

render() {
    return (
        <div className="displayinline col-md-12 ">
            Hello
        </div>
    );
}
}

export default Header;

Using statics

var MyComponent = React.createClass({
 statics: {
 customMethod: function(foo) {
  return foo === 'bar';
  }
 },
   render: function() {
 }
});

MyComponent.customMethod('bar');  // true

How do I Validate the File Type of a File Upload?

Seems like you are going to have limited options since you want the check to occur before the upload. I think the best you are going to get is to use javascript to validate the extension of the file. You could build a hash of valid extensions and then look to see if the extension of the file being uploaded existed in the hash.

HTML:

<input type="file" name="FILENAME"  size="20" onchange="check_extension(this.value,"upload");"/>
<input type="submit" id="upload" name="upload" value="Attach" disabled="disabled" />

Javascript:

var hash = {
  'xls'  : 1,
  'xlsx' : 1,
};

function check_extension(filename,submitId) {
      var re = /\..+$/;
      var ext = filename.match(re);
      var submitEl = document.getElementById(submitId);
      if (hash[ext]) {
        submitEl.disabled = false;
        return true;
      } else {
        alert("Invalid filename, please select another file");
        submitEl.disabled = true;

        return false;
      }
}

Easiest way to flip a boolean value?

The codegolf'ish solution would be more like:

flipVal = (wParam == VK_F11) ? !flipVal : flipVal;
otherVal = (wParam == VK_F12) ? !otherVal : otherVal;

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

You can add function to:

c:\Users\David\Documents\WindowsPowerShell\profile.ps1

An the function will be available.

align an image and some text on the same line without using div width?

I built on the last answer and used display:table for an outer div, and display:table-cell for inner divs.

This was the only thing that worked for me using CSS.

Why is Git better than Subversion?

Git and DVCS in general is great for developers doing a lot of coding independently of each other because everyone has their own branch. If you need a change from someone else, though, she has to commit to her local repo and then she must push that changeset to you or you must pull it from her.

My own reasoning also makes me think DVCS makes things harder for QA and release management if you do things like centralized releases. Someone has to be responsible for doing that push/pull from everyone else's repository, resolving any conflicts that would have been resolved at initial commit time before, then doing the build, and then having all the other developers re-sync their repos.

All of this can be addressed with human processes, of course; DVCS just broke something that was fixed by centralized version control in order to provide some new conveniences.

What are the safe characters for making URLs?

To quote section 2.3 of RFC 3986:

Characters that are allowed in a URI, but do not have a reserved purpose, are called unreserved. These include uppercase and lowercase letters, decimal digits, hyphen, period, underscore, and tilde.

  ALPHA  DIGIT  "-" / "." / "_" / "~"

Note that RFC 3986 lists fewer reserved punctuation marks than the older RFC 2396.

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

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

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

Required attribute HTML5

Just put the following below your form. Make sure your input fields are required.

<script>
    var forms = document.getElementsByTagName('form');
    for (var i = 0; i < forms.length; i++) {
        forms[i].noValidate = true;
        forms[i].addEventListener('submit', function(event) {
            if (!event.target.checkValidity()) {
                event.preventDefault();
                alert("Please complete all fields and accept the terms.");
            }
        }, false);
    }
</script>

JPA CriteriaBuilder - How to use "IN" comparison operator

If I understand well, you want to Join ScheduleRequest with User and apply the in clause to the userName property of the entity User.

I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join part (because it handles the Join logic outside the Criteria Query).

List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
    myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);

In order to write more type-safe code you could also use Metamodel by replacing this line:

Expression<String> exp = scheduleRequest.get("createdBy");

with this:

Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);

If it works, then you may try to add the Join logic into the Criteria Query. But right now I can't test it, so I prefer to see if somebody else wants to try.


Not a perfect answer though may be code snippets might help.

public <T> List<T> findListWhereInCondition(Class<T> clazz,
            String conditionColumnName, Serializable... conditionColumnValues) {
        QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
        addWhereInClause(queryBuilder, conditionColumnName,
                conditionColumnValues);
        queryBuilder.select();
        return queryBuilder.getResultList();

    }


private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
            String conditionColumnName, Serializable... conditionColumnValues) {

        Path<Object> path = queryBuilder.root.get(conditionColumnName);
        In<Object> in = queryBuilder.criteriaBuilder.in(path);
        for (Serializable conditionColumnValue : conditionColumnValues) {
            in.value(conditionColumnValue);
        }
        queryBuilder.criteriaQuery.where(in);

    }

Are there any free Xml Diff/Merge tools available?

A7Soft provide XML comparison tools freeware and shareware:

http://www.a7soft.com

jQuery animated number counter from zero to value

This is work for me !

<script type="text/javascript">
$(document).ready(function(){
        countnumber(0,40,"stat1",50);
        function countnumber(start,end,idtarget,duration){
            cc=setInterval(function(){
                if(start==end)
                {
                    $("#"+idtarget).html(start);
                    clearInterval(cc);
                }
                else
                {
                   $("#"+idtarget).html(start);
                   start++;
                }
            },duration);
        }
    });
</script>
<span id="span1"></span>

Notepad++ add to every line

Open Notepad++, then click Ctrl+ F.

Choose Regular Expression

*Find What: "^" (which represents index of the each line - "PREFIX").

Replace with : "anyText"*

enter image description here

For Suffix on each line: Follow the same steps as above "Replace ^ with $" . That's it.

Setting the correct PATH for Eclipse

For me none worked. I compared my existing eclipse.ini with a new one and started removing options and testing if eclipse worked.

The only option that prevented eclipse from starting was -XX:+UseParallelGC, so I removed it and voilá!

C++ printing boolean, what is displayed?

The standard streams have a boolalpha flag that determines what gets displayed -- when it's false, they'll display as 0 and 1. When it's true, they'll display as false and true.

There's also an std::boolalpha manipulator to set the flag, so this:

#include <iostream>
#include <iomanip>

int main() {
    std::cout<<false<<"\n";
    std::cout << std::boolalpha;   
    std::cout<<false<<"\n";
    return 0;
}

...produces output like:

0
false

For what it's worth, the actual word produced when boolalpha is set to true is localized--that is, <locale> has a num_put category that handles numeric conversions, so if you imbue a stream with the right locale, it can/will print out true and false as they're represented in that locale. For example,

#include <iostream>
#include <iomanip>
#include <locale>

int main() {
    std::cout.imbue(std::locale("fr"));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

...and at least in theory (assuming your compiler/standard library accept "fr" as an identifier for "French") it might print out faux instead of false. I should add, however, that real support for this is uneven at best--even the Dinkumware/Microsoft library (usually quite good in this respect) prints false for every language I've checked.

The names that get used are defined in a numpunct facet though, so if you really want them to print out correctly for particular language, you can create a numpunct facet to do that. For example, one that (I believe) is at least reasonably accurate for French would look like this:

#include <array>
#include <string>
#include <locale>
#include <ios>
#include <iostream>

class my_fr : public std::numpunct< char > {
protected:
    char do_decimal_point() const { return ','; }
    char do_thousands_sep() const { return '.'; }
    std::string do_grouping() const { return "\3"; }
    std::string do_truename() const { return "vrai";  }
    std::string do_falsename() const { return "faux"; }
};

int main() {
    std::cout.imbue(std::locale(std::locale(), new my_fr));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

And the result is (as you'd probably expect):

0
faux

python numpy ValueError: operands could not be broadcast together with shapes

We might confuse ourselves that a * b is a dot product.

But in fact, it is broadcast.

Dot Product : a.dot(b)

Broadcast:

The term broadcasting refers to how numpy treats arrays with different dimensions during arithmetic operations which lead to certain constraints, the smaller array is broadcast across the larger array so that they have compatible shapes.

(m,n) +-/* (1,n) ? (m,n) : the operation will be applied to m rows

What is the syntax for adding an element to a scala.collection.mutable.Map?

As always, you should question whether you truly need a mutable map.

Immutable maps are trivial to build:

val map = Map(
  "mykey" -> "myval",
  "myotherkey" -> "otherval"
)

Mutable maps are no different when first being built:

val map = collection.mutable.Map(
  "mykey" -> "myval",
  "myotherkey" -> "otherval"
)

map += "nextkey" -> "nextval"

In both of these cases, inference will be used to determine the correct type parameters for the Map instance.

You can also hold an immutable map in a var, the variable will then be updated with a new immutable map instance every time you perform an "update"

var map = Map(
  "mykey" -> "myval",
  "myotherkey" -> "otherval"
)

map += "nextkey" -> "nextval"

If you don't have any initial values, you can use Map.empty:

val map : Map[String, String] = Map.empty //immutable
val map = Map.empty[String,String] //immutable
val map = collection.mutable.Map.empty[String,String] //mutable

JavaScript equivalent to printf/String.Format

For those who like Node.JS and its util.format feature, I've just extracted it out into its vanilla JavaScript form (with only functions that util.format uses):

exports = {};

function isString(arg) {
    return typeof arg === 'string';
}
function isNull(arg) {
    return arg === null;
}
function isObject(arg) {
    return typeof arg === 'object' && arg !== null;
}
function isBoolean(arg) {
    return typeof arg === 'boolean';
}
function isUndefined(arg) {
    return arg === void 0;
}
function stylizeNoColor(str, styleType) {
    return str;
}
function stylizeWithColor(str, styleType) {
    var style = inspect.styles[styleType];

    if (style) {
        return '\u001b[' + inspect.colors[style][0] + 'm' + str +
            '\u001b[' + inspect.colors[style][3] + 'm';
    } else {
        return str;
    }
}
function isFunction(arg) {
    return typeof arg === 'function';
}
function isNumber(arg) {
    return typeof arg === 'number';
}
function isSymbol(arg) {
    return typeof arg === 'symbol';
}
function formatPrimitive(ctx, value) {
    if (isUndefined(value))
        return ctx.stylize('undefined', 'undefined');
    if (isString(value)) {
        var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
                .replace(/'/g, "\\'")
                .replace(/\\"/g, '"') + '\'';
        return ctx.stylize(simple, 'string');
    }
    if (isNumber(value)) {
        // Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
        // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
        if (value === 0 && 1 / value < 0)
            return ctx.stylize('-0', 'number');
        return ctx.stylize('' + value, 'number');
    }
    if (isBoolean(value))
        return ctx.stylize('' + value, 'boolean');
    // For some reason typeof null is "object", so special case here.
    if (isNull(value))
        return ctx.stylize('null', 'null');
    // es6 symbol primitive
    if (isSymbol(value))
        return ctx.stylize(value.toString(), 'symbol');
}
function arrayToHash(array) {
    var hash = {};

    array.forEach(function (val, idx) {
        hash[val] = true;
    });

    return hash;
}
function objectToString(o) {
    return Object.prototype.toString.call(o);
}
function isDate(d) {
    return isObject(d) && objectToString(d) === '[object Date]';
}
function isError(e) {
    return isObject(e) &&
        (objectToString(e) === '[object Error]' || e instanceof Error);
}
function isRegExp(re) {
    return isObject(re) && objectToString(re) === '[object RegExp]';
}
function formatError(value) {
    return '[' + Error.prototype.toString.call(value) + ']';
}
function formatPrimitiveNoColor(ctx, value) {
    var stylize = ctx.stylize;
    ctx.stylize = stylizeNoColor;
    var str = formatPrimitive(ctx, value);
    ctx.stylize = stylize;
    return str;
}
function isArray(ar) {
    return Array.isArray(ar);
}
function hasOwnProperty(obj, prop) {
    return Object.prototype.hasOwnProperty.call(obj, prop);
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
    var name, str, desc;
    desc = Object.getOwnPropertyDescriptor(value, key) || {value: value[key]};
    if (desc.get) {
        if (desc.set) {
            str = ctx.stylize('[Getter/Setter]', 'special');
        } else {
            str = ctx.stylize('[Getter]', 'special');
        }
    } else {
        if (desc.set) {
            str = ctx.stylize('[Setter]', 'special');
        }
    }
    if (!hasOwnProperty(visibleKeys, key)) {
        name = '[' + key + ']';
    }
    if (!str) {
        if (ctx.seen.indexOf(desc.value) < 0) {
            if (isNull(recurseTimes)) {
                str = formatValue(ctx, desc.value, null);
            } else {
                str = formatValue(ctx, desc.value, recurseTimes - 1);
            }
            if (str.indexOf('\n') > -1) {
                if (array) {
                    str = str.split('\n').map(function (line) {
                        return '  ' + line;
                    }).join('\n').substr(2);
                } else {
                    str = '\n' + str.split('\n').map(function (line) {
                        return '   ' + line;
                    }).join('\n');
                }
            }
        } else {
            str = ctx.stylize('[Circular]', 'special');
        }
    }
    if (isUndefined(name)) {
        if (array && key.match(/^\d+$/)) {
            return str;
        }
        name = JSON.stringify('' + key);
        if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
            name = name.substr(1, name.length - 2);
            name = ctx.stylize(name, 'name');
        } else {
            name = name.replace(/'/g, "\\'")
                .replace(/\\"/g, '"')
                .replace(/(^"|"$)/g, "'")
                .replace(/\\\\/g, '\\');
            name = ctx.stylize(name, 'string');
        }
    }

    return name + ': ' + str;
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
    var output = [];
    for (var i = 0, l = value.length; i < l; ++i) {
        if (hasOwnProperty(value, String(i))) {
            output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
                String(i), true));
        } else {
            output.push('');
        }
    }
    keys.forEach(function (key) {
        if (!key.match(/^\d+$/)) {
            output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
                key, true));
        }
    });
    return output;
}
function reduceToSingleString(output, base, braces) {
    var length = output.reduce(function (prev, cur) {
        return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
    }, 0);

    if (length > 60) {
        return braces[0] +
            (base === '' ? '' : base + '\n ') +
            ' ' +
            output.join(',\n  ') +
            ' ' +
            braces[1];
    }

    return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
function formatValue(ctx, value, recurseTimes) {
    // Provide a hook for user-specified inspect functions.
    // Check that value is an object with an inspect function on it
    if (ctx.customInspect &&
        value &&
        isFunction(value.inspect) &&
            // Filter out the util module, it's inspect function is special
        value.inspect !== exports.inspect &&
            // Also filter out any prototype objects using the circular check.
        !(value.constructor && value.constructor.prototype === value)) {
        var ret = value.inspect(recurseTimes, ctx);
        if (!isString(ret)) {
            ret = formatValue(ctx, ret, recurseTimes);
        }
        return ret;
    }

    // Primitive types cannot have properties
    var primitive = formatPrimitive(ctx, value);
    if (primitive) {
        return primitive;
    }

    // Look up the keys of the object.
    var keys = Object.keys(value);
    var visibleKeys = arrayToHash(keys);

    if (ctx.showHidden) {
        keys = Object.getOwnPropertyNames(value);
    }

    // This could be a boxed primitive (new String(), etc.), check valueOf()
    // NOTE: Avoid calling `valueOf` on `Date` instance because it will return
    // a number which, when object has some additional user-stored `keys`,
    // will be printed out.
    var formatted;
    var raw = value;
    try {
        // the .valueOf() call can fail for a multitude of reasons
        if (!isDate(value))
            raw = value.valueOf();
    } catch (e) {
        // ignore...
    }

    if (isString(raw)) {
        // for boxed Strings, we have to remove the 0-n indexed entries,
        // since they just noisey up the output and are redundant
        keys = keys.filter(function (key) {
            return !(key >= 0 && key < raw.length);
        });
    }

    // Some type of object without properties can be shortcutted.
    if (keys.length === 0) {
        if (isFunction(value)) {
            var name = value.name ? ': ' + value.name : '';
            return ctx.stylize('[Function' + name + ']', 'special');
        }
        if (isRegExp(value)) {
            return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
        }
        if (isDate(value)) {
            return ctx.stylize(Date.prototype.toString.call(value), 'date');
        }
        if (isError(value)) {
            return formatError(value);
        }
        // now check the `raw` value to handle boxed primitives
        if (isString(raw)) {
            formatted = formatPrimitiveNoColor(ctx, raw);
            return ctx.stylize('[String: ' + formatted + ']', 'string');
        }
        if (isNumber(raw)) {
            formatted = formatPrimitiveNoColor(ctx, raw);
            return ctx.stylize('[Number: ' + formatted + ']', 'number');
        }
        if (isBoolean(raw)) {
            formatted = formatPrimitiveNoColor(ctx, raw);
            return ctx.stylize('[Boolean: ' + formatted + ']', 'boolean');
        }
    }

    var base = '', array = false, braces = ['{', '}'];

    // Make Array say that they are Array
    if (isArray(value)) {
        array = true;
        braces = ['[', ']'];
    }

    // Make functions say that they are functions
    if (isFunction(value)) {
        var n = value.name ? ': ' + value.name : '';
        base = ' [Function' + n + ']';
    }

    // Make RegExps say that they are RegExps
    if (isRegExp(value)) {
        base = ' ' + RegExp.prototype.toString.call(value);
    }

    // Make dates with properties first say the date
    if (isDate(value)) {
        base = ' ' + Date.prototype.toUTCString.call(value);
    }

    // Make error with message first say the error
    if (isError(value)) {
        base = ' ' + formatError(value);
    }

    // Make boxed primitive Strings look like such
    if (isString(raw)) {
        formatted = formatPrimitiveNoColor(ctx, raw);
        base = ' ' + '[String: ' + formatted + ']';
    }

    // Make boxed primitive Numbers look like such
    if (isNumber(raw)) {
        formatted = formatPrimitiveNoColor(ctx, raw);
        base = ' ' + '[Number: ' + formatted + ']';
    }

    // Make boxed primitive Booleans look like such
    if (isBoolean(raw)) {
        formatted = formatPrimitiveNoColor(ctx, raw);
        base = ' ' + '[Boolean: ' + formatted + ']';
    }

    if (keys.length === 0 && (!array || value.length === 0)) {
        return braces[0] + base + braces[1];
    }

    if (recurseTimes < 0) {
        if (isRegExp(value)) {
            return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
        } else {
            return ctx.stylize('[Object]', 'special');
        }
    }

    ctx.seen.push(value);

    var output;
    if (array) {
        output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
    } else {
        output = keys.map(function (key) {
            return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
        });
    }

    ctx.seen.pop();

    return reduceToSingleString(output, base, braces);
}
function inspect(obj, opts) {
    // default options
    var ctx = {
        seen: [],
        stylize: stylizeNoColor
    };
    // legacy...
    if (arguments.length >= 3) ctx.depth = arguments[2];
    if (arguments.length >= 4) ctx.colors = arguments[3];
    if (isBoolean(opts)) {
        // legacy...
        ctx.showHidden = opts;
    } else if (opts) {
        // got an "options" object
        exports._extend(ctx, opts);
    }
    // set default options
    if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
    if (isUndefined(ctx.depth)) ctx.depth = 2;
    if (isUndefined(ctx.colors)) ctx.colors = false;
    if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
    if (ctx.colors) ctx.stylize = stylizeWithColor;
    return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;


// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
    'bold': [1, 22],
    'italic': [3, 23],
    'underline': [4, 24],
    'inverse': [7, 27],
    'white': [37, 39],
    'grey': [90, 39],
    'black': [30, 39],
    'blue': [34, 39],
    'cyan': [36, 39],
    'green': [32, 39],
    'magenta': [35, 39],
    'red': [31, 39],
    'yellow': [33, 39]
};

// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
    'special': 'cyan',
    'number': 'yellow',
    'boolean': 'yellow',
    'undefined': 'grey',
    'null': 'bold',
    'string': 'green',
    'symbol': 'green',
    'date': 'magenta',
    // "name": intentionally not styling
    'regexp': 'red'
};


var formatRegExp = /%[sdj%]/g;
exports.format = function (f) {
    if (!isString(f)) {
        var objects = [];
        for (var j = 0; j < arguments.length; j++) {
            objects.push(inspect(arguments[j]));
        }
        return objects.join(' ');
    }

    var i = 1;
    var args = arguments;
    var len = args.length;
    var str = String(f).replace(formatRegExp, function (x) {
        if (x === '%%') return '%';
        if (i >= len) return x;
        switch (x) {
            case '%s':
                return String(args[i++]);
            case '%d':
                return Number(args[i++]);
            case '%j':
                try {
                    return JSON.stringify(args[i++]);
                } catch (_) {
                    return '[Circular]';
                }
            default:
                return x;
        }
    });
    for (var x = args[i]; i < len; x = args[++i]) {
        if (isNull(x) || !isObject(x)) {
            str += ' ' + x;
        } else {
            str += ' ' + inspect(x);
        }
    }
    return str;
};

Harvested from: https://github.com/joyent/node/blob/master/lib/util.js

How to add external fonts to android application

Create a folder named fonts in the assets folder and add the snippet from the below link.

Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
textview.setTypeface(tf);

NSNotificationCenter addObserver in Swift

A nice way of doing this is to use the addObserver(forName:object:queue:using:) method rather than the addObserver(_:selector:name:object:) method that is often used from Objective-C code. The advantage of the first variant is that you don't have to use the @objc attribute on your method:

    func batteryLevelChanged(notification: Notification) {
        // do something useful with this information
    }

    let observer = NotificationCenter.default.addObserver(
        forName: NSNotification.Name.UIDeviceBatteryLevelDidChange,
        object: nil, queue: nil,
        using: batteryLevelChanged)

and you can even just use a closure instead of a method if you want:

    let observer = NotificationCenter.default.addObserver(
        forName: NSNotification.Name.UIDeviceBatteryLevelDidChange,
        object: nil, queue: nil) { _ in print("") }

You can use the returned value to stop listening for the notification later:

    NotificationCenter.default.removeObserver(observer)

There used to be another advantage in using this method, which was that it doesn't require you to use selector strings which couldn't be statically checked by the compiler and so were fragile to breaking if the method is renamed, but Swift 2.2 and later include #selector expressions that fix that problem.

Scroll / Jump to id without jQuery

on anchor tag use href and not onclick

<a href="#target1">asdf<a>

And div:

<div id="target1">some content</div>

Dynamically Add C# Properties at Runtime

Have you taken a look at ExpandoObject?

see: http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx

From MSDN:

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").

Allowing you to do cool things like:

dynamic dynObject = new ExpandoObject();
dynObject.SomeDynamicProperty = "Hello!";
dynObject.SomeDynamicAction = (msg) =>
    {
        Console.WriteLine(msg);
    };

dynObject.SomeDynamicAction(dynObject.SomeDynamicProperty);

Based on your actual code you may be more interested in:

public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
    return new MyDynObject(properties);
}

public sealed class MyDynObject : DynamicObject
{
    private readonly Dictionary<string, object> _properties;

    public MyDynObject(Dictionary<string, object> properties)
    {
        _properties = properties;
    }

    public override IEnumerable<string> GetDynamicMemberNames()
    {
        return _properties.Keys;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            result = _properties[binder.Name];
            return true;
        }
        else
        {
            result = null;
            return false;
        }
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            _properties[binder.Name] = value;
            return true;
        }
        else
        {
            return false;
        }
    }
}

That way you just need:

var dyn = GetDynamicObject(new Dictionary<string, object>()
    {
        {"prop1", 12},
    });

Console.WriteLine(dyn.prop1);
dyn.prop1 = 150;

Deriving from DynamicObject allows you to come up with your own strategy for handling these dynamic member requests, beware there be monsters here: the compiler will not be able to verify a lot of your dynamic calls and you won't get intellisense, so just keep that in mind.

How to serialize an object to XML without getting xmlns="..."?

        XmlWriterSettings settings = new XmlWriterSettings
        {
            OmitXmlDeclaration = true
        };

        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("", "");

        StringBuilder sb = new StringBuilder();

        XmlSerializer xs = new XmlSerializer(typeof(BankingDetails));

        using (XmlWriter xw = XmlWriter.Create(sb, settings))
        {
            xs.Serialize(xw, model, ns);
            xw.Flush();
            return sb.ToString();
        }

Qt: How do I handle the event of the user pressing the 'X' (close) button?

If you have a QMainWindow you can override closeEvent method.

#include <QCloseEvent>
void MainWindow::closeEvent (QCloseEvent *event)
{
    QMessageBox::StandardButton resBtn = QMessageBox::question( this, APP_NAME,
                                                                tr("Are you sure?\n"),
                                                                QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
                                                                QMessageBox::Yes);
    if (resBtn != QMessageBox::Yes) {
        event->ignore();
    } else {
        event->accept();
    }
}


If you're subclassing a QDialog, the closeEvent will not be called and so you have to override reject():

void MyDialog::reject()
{
    QMessageBox::StandardButton resBtn = QMessageBox::Yes;
    if (changes) {
        resBtn = QMessageBox::question( this, APP_NAME,
                                        tr("Are you sure?\n"),
                                        QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
                                        QMessageBox::Yes);
    }
    if (resBtn == QMessageBox::Yes) {
        QDialog::reject();
    }
}

what does -zxvf mean in tar -zxvf <filename>?

  • z means (un)z_ip.
  • x means ex_tract files from the archive.
  • v means print the filenames v_erbosely.
  • f means the following argument is a f_ilename.

For more details, see tar's man page.

MySQL error code: 1175 during UPDATE in MySQL Workbench

I found the answer. The problem was that I have to precede the table name with the schema name. i.e, the command should be:

UPDATE schemaname.tablename SET columnname=1;

Thanks all.

How to encode a URL in Swift

Swift 3:

let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)

HTML5 live streaming

Firstly you need to setup a media streaming server. You can use Wowza, red5 or nginx-rtmp-module. Read their documentation and setup on OS you want. All the engine are support HLS (Http Live Stream protocol that was developed by Apple). You should read documentation for config. Example with nginx-rtmp-module:

rtmp {
    server {
        listen 1935; # Listen on standard RTMP port
        chunk_size 4000;

        application show {
            live on;
            # Turn on HLS
            hls on;
            hls_path /mnt/hls/;
            hls_fragment 3;
            hls_playlist_length 60;
            # disable consuming the stream from nginx as rtmp
            deny play all;
        }
    }
} 

server {
    listen 8080;

    location /hls {
        # Disable cache
        add_header Cache-Control no-cache;

        # CORS setup
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
        add_header 'Access-Control-Allow-Headers' 'Range';

        # allow CORS preflight requests
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Headers' 'Range';
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
        }

        types {
            application/vnd.apple.mpegurl m3u8;
            video/mp2t ts;
        }

        root /mnt/;
    }
}

After server was setup and configuration successful. you must use some rtmp encoder software (OBS, wirecast ...) for start streaming like youtube or twitchtv.

In client side (browser in your case) you can use Videojs or JWplayer to play video for end user. You can do something like below for Videojs:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Live Streaming</title>
    <link href="//vjs.zencdn.net/5.8/video-js.min.css" rel="stylesheet">
    <script src="//vjs.zencdn.net/5.8/video.min.js"></script>
</head>
<body>
<video id="player" class="video-js vjs-default-skin" height="360" width="640" controls preload="none">
    <source src="http://localhost:8080/hls/stream.m3u8" type="application/x-mpegURL" />
</video>
<script>
    var player = videojs('#player');
</script>
</body>
</html>

You don't need to add others plugin like flash (because we use HLS not rtmp). This player can work well cross browser with out flash.

javascript convert int to float

toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.

var fval = 4;

console.log(fval.toFixed(2)); // prints 4.00

How to fix "Attempted relative import in non-package" even with __init__.py

For me only this worked: I had to explicitly set the value of package to the parent directory, and add the parent directory to sys.path

from os import path
import sys
if __package__ is None:
    sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
    __package__= "myparent"

from .subdir import something # the . can now be resolved

I can now directly run my script with python myscript.py.

CSS: center element within a <div> element

Set text-align:center; to the parent div, and margin:auto; to the child div.

_x000D_
_x000D_
#parent {_x000D_
    text-align:center;_x000D_
    background-color:blue;_x000D_
    height:400px;_x000D_
    width:600px;_x000D_
}_x000D_
.block {_x000D_
    height:100px;_x000D_
    width:200px;_x000D_
    text-align:left;_x000D_
}_x000D_
.center {_x000D_
    margin:auto;_x000D_
    background-color:green;_x000D_
}_x000D_
.left {_x000D_
    margin:auto auto auto 0;_x000D_
    background-color:red;_x000D_
}_x000D_
.right {_x000D_
    margin:auto 0 auto auto;_x000D_
    background-color:yellow;_x000D_
}
_x000D_
<div id="parent">_x000D_
    <div id="child1" class="block center">_x000D_
        a block to align center and with text aligned left_x000D_
    </div>_x000D_
    <div id="child2" class="block left">_x000D_
        a block to align left and with text aligned left_x000D_
    </div>_x000D_
    <div id="child3" class="block right">_x000D_
        a block to align right and with text aligned left_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This a good resource to center mostly anything.
http://howtocenterincss.com/

Drop Down Menu/Text Field in one

Inspired by the js fiddle by @ajdeguzman (made my day), here is my node/React derivative:

 <div style={{position:"relative",width:"200px",height:"25px",border:0,
              padding:0,margin:0}}>
    <select style={{position:"absolute",top:"0px",left:"0px",
                    width:"200px",height:"25px",lineHeight:"20px",
                    margin:0,padding:0}} onChange={this.onMenuSelect}>
            <option></option>
            <option value="starttime">Filter by Start Time</option>
            <option value="user"     >Filter by User</option>
            <option value="buildid"  >Filter by Build Id</option>
            <option value="invoker"  >Filter by Invoker</option>
    </select>
    <input name="displayValue" id="displayValue" 
           style={{position:"absolute",top:"2px",left:"3px",width:"180px",
                   height:"21px",border:"1px solid #A9A9A9"}}
           onfocus={this.select} type="text" onChange={this.onIdFilterChange}
           onMouseDown={this.onMouseDown} onMouseUp={this.onMouseUp} 
           placeholder="Filter by Build ID"/>
 </div>

Looks like this:

enter image description here

Creating a jQuery object from a big HTML-string

the reason why $(string) is not working is because jquery is not finding html content between $(). Therefore you need to first parse it to html. once you have a variable in which you have parsed the html. you can then use $(string) and use all functions available on the object

How to access first element of JSON object array?

'[{"event":"inbound","ts":1426249238}]' is a string, you cannot access any properties there. You will have to parse it to an object, with JSON.parse() and then handle it like a normal object

Shuffle DataFrame rows

What is also useful, if you use it for Machine_learning and want to seperate always the same data, you could use:

df.sample(n=len(df), random_state=42)

this makes sure, that you keep your random choice always replicatable

Excel "External table is not in the expected format."

the file might be locked by another process, you need to copy it then load it as it says in this post

Can I access variables from another file?

I did like what answer above said but although, it didn't worked with me

because I was declaring these variables inside JQuery $( document ).ready()

so make sure you declare your variables inside the <script> tag not somewhere else

angularjs: ng-src equivalent for background-image:url(...)

It's also possible to do something like this with ng-style:

ng-style="image_path != '' && {'background-image':'url('+image_path+')'}"

which would not attempt to fetch a non-existing image.

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

This happens because the Child Entity is marked as Modified instead of Deleted.

And the modification that EF does to the Child Entity when parent.Remove(child) is executed, is simply setting the reference to its parent to null.

You can check the child's EntityState by typing the following code into Visual Studio's Immediate Window when the exception occurs, after executing SaveChanges():

_context.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified).ElementAt(X).Entity

where X should be replaced by the deleted Entity.

If you don't have access to the ObjectContext to execute _context.ChildEntity.Remove(child), you can solve this issue by making the foreign key a part of the primary key on the child table.

Parent
 ________________
| PK    IdParent |
|       Name     |
|________________|

Child
 ________________
| PK    IdChild  |
| PK,FK IdParent |
|       Name     |
|________________|

This way, if you execute parent.Remove(child), EF will correctly mark the Entity as Deleted.

Return HTML content as a string, given URL. Javascript Function

Here's a version of the accepted answer that 1) returns a value from the function (bugfix), and 2) doesn't break when using "use strict";

I use this code to pre-load a .txt file into my <textarea> when the user loads the page.

function httpGet(theUrl)
{
    let xmlhttp;
    
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", theUrl, false);
    xmlhttp.send();
    
    return xmlhttp.response;
}

Using lambda expressions for event handlers

EventHandler handler = (s, e) => MessageBox.Show("Woho");

button.Click += handler;
button.Click -= handler;

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

For me it was server responding with something other than 200 and the response was not json formatted. I ended up doing this before the json parse:

# this is the https request for data in json format
response_json = requests.get() 

# only proceed if I have a 200 response which is saved in status_code
if (response_json.status_code == 200):  
     response = response_json.json() #converting from json to dictionary using json library

Clone only one branch

I have done with below single git command:

git clone [url] -b [branch-name] --single-branch

What is the difference between ( for... in ) and ( for... of ) statements?

For...in loop

The for...in loop improves upon the weaknesses of the for loop by eliminating the counting logic and exit condition.

Example:

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const index in digits) {
  console.log(digits[index]);
}

But, you still have to deal with the issue of using an index to access the values of the array, and that stinks; it almost makes it more confusing than before.

Also, the for...in loop can get you into big trouble when you need to add an extra method to an array (or another object). Because for...in loops loop over all enumerable properties, this means if you add any additional properties to the array's prototype, then those properties will also appear in the loop.

Array.prototype.decimalfy = function() {
  for (let i = 0; i < this.length; i++) {
    this[i] = this[i].toFixed(2);
  }
};

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const index in digits) {
  console.log(digits[index]);
}

Prints:

0

1

2

3

4

5

6

7

8

9

function() { for (let i = 0; i < this.length; i++) { this[i] = this[i].toFixed(2); } }

This is why for...in loops are discouraged when looping over arrays.

NOTE: The forEach loop is another type of for loop in JavaScript. However, forEach() is actually an array method, so it can only be used exclusively with arrays. There is also no way to stop or break a forEach loop. If you need that type of behavior in your loop, you’ll have to use a basic for loop.

For...of loop

The for...of loop is used to loop over any type of data that is iterable.

Example:

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const digit of digits) {
  console.log(digit);
}

Prints:

0

1

2

3

4

5

6

7

8

9

This makes the for...of loop the most concise version of all the for loops.

But wait, there’s more! The for...of loop also has some additional benefits that fix the weaknesses of the for and for...in loops.

You can stop or break a for...of loop at anytime.

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const digit of digits) {
  if (digit % 2 === 0) {
    continue;
  }
  console.log(digit);
}

Prints:

1

3

5

7

9

And you don’t have to worry about adding new properties to objects. The for...of loop will only loop over the values in the object.

How to convert a string from uppercase to lowercase in Bash?

Note that tr can only handle plain ASCII, making any tr-based solution fail when facing international characters.

Same goes for the bash 4 based ${x,,} solution.

The awk tool, on the other hand, properly supports even UTF-8 / multibyte input.

y="HELLO"
val=$(echo "$y" | awk '{print tolower($0)}')
string="$val world"

Answer courtesy of liborw.

Force flushing of output to a file while bash script is still running

I had this problem with a background process in Mac OS X using the StartupItems. This is how I solve it:

If I make sudo ps aux I can see that mytool is launched.

I found that (due to buffering) when Mac OS X shuts down mytool never transfers the output to the sed command. However, if I execute sudo killall mytool, then mytool transfers the output to the sed command. Hence, I added a stop case to the StartupItems that is executed when Mac OS X shuts down:

start)
    if [ -x /sw/sbin/mytool ]; then
      # run the daemon
      ConsoleMessage "Starting mytool"
      (mytool | sed .... >> myfile.txt) & 
    fi
    ;;
stop)
    ConsoleMessage "Killing mytool"
    killall mytool
    ;;

Class has no objects member

First install pylint-django using following command

$ pip install pylint-django

Then run the second command as follows:

$ pylint test_file.py --load-plugins pylint_django

--load-plugins pylint_django is necessary for correctly review a code of django

iPhone Safari Web App opens links in new window

If you are using jQuery, you can do:

$("a").click(function (event) {
    event.preventDefault();
    window.location = $(this).attr("href");
});

Most efficient way to see if an ArrayList contains an object in Java

There are three basic options:

1) If retrieval performance is paramount and it is practical to do so, use a form of hash table built once (and altered as/if the List changes).

2) If the List is conveniently sorted or it is practical to sort it and O(log n) retrieval is sufficient, sort and search.

3) If O(n) retrieval is fast enough or if it is impractical to manipulate/maintain the data structure or an alternate, iterate over the List.

Before writing code more complex than a simple iteration over the List, it is worth thinking through some questions.

  • Why is something different needed? (Time) performance? Elegance? Maintainability? Reuse? All of these are okay reasons, apart or together, but they influence the solution.

  • How much control do you have over the data structure in question? Can you influence how it is built? Managed later?

  • What is the life cycle of the data structure (and underlying objects)? Is it built up all at once and never changed, or highly dynamic? Can your code monitor (or even alter) its life cycle?

  • Are there other important constraints, such as memory footprint? Does information about duplicates matter? Etc.

Converting dict to OrderedDict

You can create the ordered dict from old dict in one line:

from collections import OrderedDict
ordered_dict = OrderedDict(sorted(ship.items())

The default sorting key is by dictionary key, so the new ordered_dict is sorted by old dict's keys.

How to send multiple data fields via Ajax?

You can send data through JSON or via normal POST, here is an example for JSON.

 var value1 = 1;
 var value2 = 2;
 var value3 = 3;   
 $.ajax({
      type: "POST",
      contentType: "application/json; charset=utf-8",
      url: "yoururlhere",
      data: { data1: value1, data2: value2, data3: value3 },
      success: function (result) {
           // do something here
      }
 });

If you want to use it via normal post try this

 $.ajax({
      type: "POST",
      url: $('form').attr("action"),   
      data: $('#form0').serialize(),
      success: function (result) {
         // do something here
      }
 });

Python Library Path

import sys
sys.path

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

There is a Redisson java framework which implements hash Map object with entry TTL support. It uses hmap and zset Redis objects under the hood. Usage example:

RMapCache<Integer, String> map = redisson.getMapCache('map');
map.put(1, 30, TimeUnit.DAYS); // this entry expires in 30 days

This approach is quite useful.

How can I write data attributes using Angular?

About access

<ol class="viewer-nav">
    <li *ngFor="let section of sections" 
        [attr.data-sectionvalue]="section.value"
        (click)="get_data($event)">
        {{ section.text }}
    </li>  
</ol>

And

get_data(event) {
   console.log(event.target.dataset.sectionvalue)
}

Bootstrap combining rows (rowspan)

_x000D_
_x000D_
div {_x000D_
  height:50px;_x000D_
}_x000D_
.short-div {_x000D_
  height:25px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="container">_x000D_
  <h1>Responsive Bootstrap</h1>_x000D_
  <div class="row">_x000D_
    <div class="col-lg-5 col-md-5 col-sm-5 col-xs-5" style="background-color:red;">Span 5</div>_x000D_
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3" style="background-color:blue">Span 3</div>_x000D_
    <div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="padding:0px">_x000D_
      <div class="short-div" style="background-color:green">Span 2</div>_x000D_
      <div class="short-div" style="background-color:purple">Span 2</div>_x000D_
    </div>_x000D_
    <div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="background-color:yellow">Span 2</div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container-fluid">_x000D_
  <div class="row-fluid">_x000D_
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">_x000D_
      <div class="short-div" style="background-color:#999">Span 6</div>_x000D_
      <div class="short-div">Span 6</div>_x000D_
    </div>_x000D_
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6" style="background-color:#ccc">Span 6</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I start my app on startup?

Another approach is to use android.intent.action.USER_PRESENT instead of android.intent.action.BOOT_COMPLETED to avoid slow downs during the boot process. But this is only true if the user has enabled the lock Screen - otherwise this intent is never broadcasted.

Reference blog - The Problem With Android’s ACTION_USER_PRESENT Intent

How do I detect a click outside an element?

This works for me

$("body").mouseup(function(e) {
    var subject = $(".main-menu");
    if(e.target.id != subject.attr('id') && !subject.has(e.target).length) {
        $('.sub-menu').hide();
    }
});

Inline functions in C#?

Do you mean inline functions in the C++ sense? In which the contents of a normal function are automatically copied inline into the callsite? The end effect being that no function call actually happens when calling a function.

Example:

inline int Add(int left, int right) { return left + right; }

If so then no, there is no C# equivalent to this.

Or Do you mean functions that are declared within another function? If so then yes, C# supports this via anonymous methods or lambda expressions.

Example:

static void Example() {
  Func<int,int,int> add = (x,y) => x + y;
  var result = add(4,6);  // 10
}

#1064 -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

I see two problems:

DOUBLE(10) precision definitions need a total number of digits, as well as a total number of digits after the decimal:

DOUBLE(10,8) would make be ten total digits, with 8 allowed after the decimal.

Also, you'll need to specify your id column as a key :

CREATE TABLE transactions( 
id int NOT NULL AUTO_INCREMENT, 
location varchar(50) NOT NULL, 
description varchar(50) NOT NULL, 
category varchar(50) NOT NULL, 
amount double(10,9) NOT NULL, 
type varchar(6) NOT NULL,  
notes varchar(512), 
receipt int(10), 
PRIMARY KEY(id) );

How to call a function after a div is ready?

You can use recursion here to do this. For example:

jQuery(document).ready(checkContainer);

function checkContainer () {
  if($('#divIDer').is(':visible'))){ //if the container is visible on the page
    createGrid();  //Adds a grid to the html
  } else {
    setTimeout(checkContainer, 50); //wait 50 ms, then try again
  }
}

Basically, this function will check to make sure that the element exists and is visible. If it is, it will run your createGrid() function. If not, it will wait 50ms and try again.

Note:: Ideally, you would just use the callback function of your AJAX call to know when the container was appended, but this is a brute force, standalone approach. :)

PHP display current server path

  • To get your current working directory: getcwd() (documentation)
  • To get the document root directory: $_SERVER['DOCUMENT_ROOT']
  • To get the filename of the current script: $_SERVER['SCRIPT_FILENAME']

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

Take a look at http://start.spring.io/ it basically gives you a kick starter with either maven or gradle build.

Note: This is a Spring Boot based archetype.

node.js shell command execution

I used this more concisely :

var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }
exec("ls -la", puts);

it works perfectly. :)

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

If, like me, you just want to disable a button, don't miss the simple answer subtly hidden in this long thread:

 $("#button").prop('disabled', true);

Why does modulus division (%) only work with integers?

I can't really say for sure, but I'd guess it's mostly historical. Quite a few early C compilers didn't support floating point at all. It was added on later, and even then not as completely -- mostly the data type was added, and the most primitive operations supported in the language, but everything else left to the standard library.

differences in application/json and application/x-www-form-urlencoded

The first case is telling the web server that you are posting JSON data as in:

{ Name : 'John Smith', Age: 23}

The second option is telling the web server that you will be encoding the parameters in the URL as in:

Name=John+Smith&Age=23

How to achieve pagination/table layout with Angular.js?

I would use table and implement the pagination in the controller to control how much is shown and buttons to move to the next page. This Fiddle might help you.

example of the pagination

 <table class="table table-striped table-condensed table-hover">
                <thead>
                    <tr>
                        <th class="id">Id&nbsp;<a ng-click="sort_by('id')"><i class="icon-sort"></i></a></th>
                        <th class="name">Name&nbsp;<a ng-click="sort_by('name')"><i class="icon-sort"></i></a></th>
                        <th class="description">Description&nbsp;<a ng-click="sort_by('description')"><i class="icon-sort"></i></a></th>
                        <th class="field3">Field 3&nbsp;<a ng-click="sort_by('field3')"><i class="icon-sort"></i></a></th>
                        <th class="field4">Field 4&nbsp;<a ng-click="sort_by('field4')"><i class="icon-sort"></i></a></th>
                        <th class="field5">Field 5&nbsp;<a ng-click="sort_by('field5')"><i class="icon-sort"></i></a></th>
                    </tr>
                </thead>
                <tfoot>
                    <td colspan="6">
                        <div class="pagination pull-right">
                            <ul>
                                <li ng-class="{disabled: currentPage == 0}">
                                    <a href ng-click="prevPage()">« Prev</a>
                                </li>
                                <li ng-repeat="n in range(pagedItems.length)"
                                    ng-class="{active: n == currentPage}"
                                ng-click="setPage()">
                                    <a href ng-bind="n + 1">1</a>
                                </li>
                                <li ng-class="{disabled: currentPage == pagedItems.length - 1}">
                                    <a href ng-click="nextPage()">Next »</a>
                                </li>
                            </ul>
                        </div>
                    </td>
                </tfoot>
                <tbody>
                    <tr ng-repeat="item in pagedItems[currentPage] | orderBy:sortingOrder:reverse">
                        <td>{{item.id}}</td>
                        <td>{{item.name}}</td>
                        <td>{{item.description}}</td>
                        <td>{{item.field3}}</td>
                        <td>{{item.field4}}</td>
                        <td>{{item.field5}}</td>
                    </tr>
                </tbody>
            </table> 

the $scope.range in the fiddle example should be:

$scope.range = function (size,start, end) {
    var ret = [];        
    console.log(size,start, end);

       if (size < end) {
        end = size;
        if(size<$scope.gap){
             start = 0;
        }else{
             start = size-$scope.gap;
        }

    }
    for (var i = start; i < end; i++) {
        ret.push(i);
    }        
     console.log(ret);        
    return ret;
};

Intellij idea cannot resolve anything in maven

I had empty settings.xml file in Users/.../.m2/settings.xml. When i added

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      https://maven.apache.org/xsd/settings-1.0.0.xsd">

</settings>

all dependicies were loaded

Bulk Insertion in Laravel using eloquent ORM

I searched many times for it, finally used custom timestamps like below:

$now = Carbon::now()->toDateTimeString();
Model::insert([
    ['name'=>'Foo', 'created_at'=>$now, 'updated_at'=>$now],
    ['name'=>'Bar', 'created_at'=>$now, 'updated_at'=>$now],
    ['name'=>'Baz', 'created_at'=>$now, 'updated_at'=>$now],
    ..................................
]);

Can you center a Button in RelativeLayout?

To center align in one of the direction use android:layout_centerHorizontal="true" or android:layout_centerVertical="true" in the child layout

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

Convert string to Color in C#

For transferring colors via xml-strings I've found out:

Color x = Color.Red; // for example
String s = x.ToArgb().ToString()
... to/from xml ...
Int32 argb = Convert.ToInt32(s);
Color red = Color.FromArgb(argb);

What is hashCode used for? Is it unique?

GetHashCode() is used to help support using the object as a key for hash tables. (A similar thing exists in Java etc). The goal is for every object to return a distinct hash code, but this often can't be absolutely guaranteed. It is required though that two logically equal objects return the same hash code.

A typical hash table implementation starts with the hashCode value, takes a modulus (thus constraining the value within a range) and uses it as an index to an array of "buckets".

Increase max_execution_time in PHP?

Theres a setting max_input_time (on Apache) for many webservers that defines how long they will wait for post data, regardless of the size. If this time runs out the connection is closed without even touching the php.

So your problem is not necessarily solvable with php only but you will need to change the server settings too.

PHP namespaces and "use"

The use operator is for giving aliases to names of classes, interfaces or other namespaces. Most use statements refer to a namespace or class that you'd like to shorten:

use My\Full\Namespace;

is equivalent to:

use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo

If the use operator is used with a class or interface name, it has the following uses:

// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;

// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;

The use operator is not to be confused with autoloading. A class is autoloaded (negating the need for include) by registering an autoloader (e.g. with spl_autoload_register). You might want to read PSR-4 to see a suitable autoloader implementation.

Adding items to end of linked list

Here's a hint, you have a graph of nodes in the linked list, and you always keep a reference to head which is the first node in the linkedList.
next points to the next node in the linkedlist, so when next is null you are at the end of the list.

How do I store the select column in a variable?

This is how to assign a value to a variable:

SELECT @EmpID = Id
  FROM dbo.Employee

However, the above query is returning more than one value. You'll need to add a WHERE clause in order to return a single Id value.

Check if a string is a date value

is it fine to check for a Date related function is available for the object to find whether it is a Date object or not ?

like

var l = new Date();
var isDate = (l.getDate !== undefined) ? true; false;

Connect to network drive with user name and password

I really don't know the hidden process, but I use a webrequest, this way I'm able to pass the credentials, and it worked perfectly for me.

var ftpDownloadFile = WebRequest.Create("filePath");
ftpDownloadFile.Method = WebRequestMethods.Ftp.DownloadFile;
ftpDownloadFile.Credentials = new NetworkCredential("user", "pass");
using (var reader = (FtpWebResponse)ftpDownloadFile.GetResponse())
using (var responseStream = reader.GetResponseStream())
{
    var writeStream = new FileStream(Path.Combine(LocalStorage), FileMode.Create);
    const int length = 2048;
    var buffer = new Byte[length];
    if (responseStream != null)
    {
        var bytesRead = responseStream.Read(buffer, 0, length);
        while (bytesRead > 0)
        {
            writeStream.Write(buffer, 0, bytesRead);
            bytesRead = responseStream.Read(buffer, 0, length);
        }
    }
    reader.Close();
    writeStream.Close();
}

Can you use if/else conditions in CSS?

You can use javascript for this purpose, this way:

  1. first you set the CSS for the 'normal' class and for the 'active' class
  2. then you give to your element the id 'MyElement'
  3. and now you make your condition in JavaScript, something like the example below... (you can run it, change the value of myVar to 5 and you will see how it works)

_x000D_
_x000D_
var myVar = 4;_x000D_
_x000D_
if(myVar == 5){_x000D_
  document.getElementById("MyElement").className = "active";_x000D_
}_x000D_
else{_x000D_
  document.getElementById("MyElement").className = "normal";_x000D_
}
_x000D_
.active{_x000D_
  background-position : 150px 8px;_x000D_
  background-color: black;_x000D_
}_x000D_
.normal{_x000D_
  background-position : 4px 8px; _x000D_
  background-color: green;_x000D_
}_x000D_
div{_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  }
_x000D_
<div id="MyElement">_x000D_
  _x000D_
  </div>
_x000D_
_x000D_
_x000D_

How can I check if a string contains ANY letters from the alphabet?

You can also do this in addition

import re
string='24234ww'
val = re.search('[a-zA-Z]+',string) 
val[0].isalpha() # returns True if the variable is an alphabet
print(val[0]) # this will print the first instance of the matching value

Also note that if variable val returns None. That means the search did not find a match

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

NSString *myString = @"hello bla bla";
NSRange rangeValue = [myString rangeOfString:@"hello" options:NSCaseInsensitiveSearch];

if (rangeValue.length > 0)
{
    NSLog(@"string contains hello");
} 
else 
{
    NSLog(@"string does not contain hello!");
}

//You can alternatively use following too :

if (rangeValue.location == NSNotFound) 
{
    NSLog(@"string does not contain hello");
} 
else 
{
    NSLog(@"string contains hello!");
}

Want to download a Git repository, what do I need (windows machine)?

To change working directory in GitMSYS's Git Bash you can just use cd

cd /path/do/directory

Note that:

  • Directory separators use the forward-slash (/) instead of backslash.
  • Drives are specified with a lower case letter and no colon, e.g. "C:\stuff" should be represented with "/c/stuff".
  • Spaces can be escaped with a backslash (\)
  • Command line completion is your friend. Press TAB at anytime to expand stuff, including Git options, branches, tags, and directories.

Also, you can right click in Windows Explorer on a directory and "Git Bash here".

UICollectionView current visible cell index

indexPathsForVisibleItems might work for most situations, but sometimes it returns an array with more than one index path and it can be tricky figuring out the one you want. In those situations, you can do something like this:

CGRect visibleRect = (CGRect){.origin = self.collectionView.contentOffset, .size = self.collectionView.bounds.size};
CGPoint visiblePoint = CGPointMake(CGRectGetMidX(visibleRect), CGRectGetMidY(visibleRect));
NSIndexPath *visibleIndexPath = [self.collectionView indexPathForItemAtPoint:visiblePoint];

This works especially well when each item in your collection view takes up the whole screen.

Swift version

let visibleRect = CGRect(origin: collectionView.contentOffset, size: collectionView.bounds.size)
let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
let visibleIndexPath = collectionView.indexPathForItem(at: visiblePoint)

How to insert the current timestamp into MySQL database using a PHP insert query

This format is used to get current timestamp and stored in mysql

$date = date("Y-m-d H:i:s"); 

$update_query = "UPDATE db.tablename SET insert_time=".$date." WHERE username='" .$somename . "'"; 

Why does cURL return error "(23) Failed writing body"?

I encountered this error message while trying to install varnish cache on ubuntu. The google search landed me here for the error (23) Failed writing body, hence posting a solution that worked for me.

The bug is encountered while running the command as root curl -L https://packagecloud.io/varnishcache/varnish5/gpgkey | apt-key add -

the solution is to run apt-key add as non root

curl -L https://packagecloud.io/varnishcache/varnish5/gpgkey | apt-key add -

What is time(NULL) in C?

The time function returns the current time (as a time_t value) in seconds since some point (on Unix systems, since midnight UTC January 1, 1970), and it takes one argument, a time_t pointer in which the time is stored. Passing NULL as the argument causes time to return the time as a normal return value but not store it anywhere else.

Get program execution time in the shell

Use the built-in time keyword:

$ help time

time: time [-p] PIPELINE
    Execute PIPELINE and print a summary of the real time, user CPU time,
    and system CPU time spent executing PIPELINE when it terminates.
    The return status is the return status of PIPELINE.  The `-p' option
    prints the timing summary in a slightly different format.  This uses
    the value of the TIMEFORMAT variable as the output format.

Example:

$ time sleep 2
real    0m2.009s
user    0m0.000s
sys     0m0.004s

Error: Cannot pull with rebase: You have unstaged changes

You can always do

git fetch && git merge --ff-only origin/master

and you will either get (a) no change if you have uncommitted changes that conflict with upstream changes or (b) the same effect as stash/pull/apply: a rebase to put you on the latest changes from HEAD and your uncommitted changes left as is.

How to extract IP Address in Spring MVC Controller get call?

In my case, I was using Nginx in front of my application with the following configuration:

location / {
     proxy_pass        http://localhost:8080/;
     proxy_set_header  X-Real-IP $remote_addr;
     proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_set_header  Host $http_host;
     add_header Content-Security-Policy 'upgrade-insecure-requests';
}

so in my application I get the real user ip like so:

String clientIP = request.getHeader("X-Real-IP");

Datetime format Issue: String was not recognized as a valid DateTime

Below code worked for me:

string _stDate = Convert.ToDateTime(DateTime.Today.AddMonths(-12)).ToString("MM/dd/yyyy");
String format ="MM/dd/yyyy";
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
DateTime _Startdate = DateTime.ParseExact(_stDate, format, culture);

regex.test V.S. string.match to know if a string matches a regular expression

Basic Usage

First, let's see what each function does:

regexObject.test( String )

Executes the search for a match between a regular expression and a specified string. Returns true or false.

string.match( RegExp )

Used to retrieve the matches when matching a string against a regular expression. Returns an array with the matches or null if there are none.

Since null evaluates to false,

if ( string.match(regex) ) {
  // There was a match.
} else {
  // No match.
} 

Performance

Is there any difference regarding performance?

Yes. I found this short note in the MDN site:

If you need to know if a string matches a regular expression regexp, use regexp.test(string).

Is the difference significant?

The answer once more is YES! This jsPerf I put together shows the difference is ~30% - ~60% depending on the browser:

test vs match | Performance Test

Conclusion

Use .test if you want a faster boolean check. Use .match to retrieve all matches when using the g global flag.

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

it should vary with the architecture because it represents the size of any object. So on a 32-bit system size_t will likely be at least 32-bits wide. On a 64-bit system it will likely be at least 64-bit wide.

Laravel where on relationship object

[OOT]

A bit OOT, but this question is the most closest topic with my question.

Here is an example if you want to show Event where ALL participant meet certain requirement. Let's say, event where ALL the participant has fully paid. So, it WILL NOT return events which having one or more participants that haven't fully paid .

Simply use the whereDoesntHave of the others 2 statuses.

Let's say the statuses are haven't paid at all [eq:1], paid some of it [eq:2], and fully paid [eq:3]

Event::whereDoesntHave('participants', function ($query) {
   return $query->whereRaw('payment = 1 or payment = 2');
})->get();

Tested on Laravel 5.8 - 7.x

How to call loading function with React useEffect only once

TL;DR

useEffect(yourCallback, []) - will trigger the callback only after the first render.

Detailed explanation

useEffect runs by default after every render of the component (thus causing an effect).

When placing useEffect in your component you tell React you want to run the callback as an effect. React will run the effect after rendering and after performing the DOM updates.

If you pass only a callback - the callback will run after each render.

If passing a second argument (array), React will run the callback after the first render and every time one of the elements in the array is changed. for example when placing useEffect(() => console.log('hello'), [someVar, someOtherVar]) - the callback will run after the first render and after any render that one of someVar or someOtherVar are changed.

By passing the second argument an empty array, React will compare after each render the array and will see nothing was changed, thus calling the callback only after the first render.

How to convert 'binary string' to normal string in Python3?

If the answer from falsetru didn't work you could also try:

>>> b'a string'.decode('utf-8')
'a string'

Intellij JAVA_HOME variable

So far, nobody has answered the actual question.

Someone can figure what is happening ?

The problem here is that while the value of your $JAVA_HOME is correct, you defined it in the wrong place.

  • When you open a terminal and launch a Bash session, it will read the ~/.bash_profile file. Thus, when you enter echo $JAVA_HOME, it will return the value that has been set there.
  • When you launch IntelliJ directly, it will not read ~/.bash_profile … why should it? So to IntelliJ, this variable is not set.

There are two possible solutions to this:

  • Launch IntelliJ from a Bash session: open a terminal and run "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea". The idea process will inherit any environment variables of Bash that have been exported. (Since you did export JAVA_HOME=…, it works!), or, the sophisticated way:
  • Set global environment variables that apply to all programs, not only Bash sessions. This is more complicated than you might think, and is explained here and here, for example. What you should do is run

    /bin/launchctl setenv JAVA_HOME $(/usr/libexec/java_home)
    

    However, this gets reset after a reboot. To make sure this gets run on every boot, execute

    cat << EOF > ~/Library/LaunchAgents/setenv.JAVA_HOME.plist
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
        "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
      <plist version="1.0">
      <dict>
        <key>Label</key>
        <string>setenv.JAVA_HOME</string>
        <key>ProgramArguments</key>
        <array>
          <string>/bin/launchctl</string>
          <string>setenv</string>
          <string>JAVA_HOME</string>
          <string>$(/usr/libexec/java_home)</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>ServiceIPC</key>
        <false/>
      </dict>
    </plist>
    EOF
    

    Note that this also affects the Terminal process, so there is no need to put anything in your ~/.bash_profile.

Insert a line at specific line number with sed or awk

sed -e '8iProject_Name=sowstest' -i start using GNU sed

Sample run:

[root@node23 ~]# for ((i=1; i<=10; i++)); do echo "Line #$i"; done > a_file
[root@node23 ~]# cat a_file
Line #1
Line #2
Line #3
Line #4
Line #5
Line #6
Line #7
Line #8
Line #9
Line #10
[root@node23 ~]# sed -e '3ixxx inserted line xxx' -i a_file 
[root@node23 ~]# cat -An a_file 
     1  Line #1$
     2  Line #2$
     3  xxx inserted line xxx$
     4  Line #3$
     5  Line #4$
     6  Line #5$
     7  Line #6$
     8  Line #7$
     9  Line #8$
    10  Line #9$
    11  Line #10$
[root@node23 ~]# 
[root@node23 ~]# sed -e '5ixxx (inserted) "line" xxx' -i a_file
[root@node23 ~]# cat -n a_file 
     1  Line #1
     2  Line #2
     3  xxx inserted line xxx
     4  Line #3
     5  xxx (inserted) "line" xxx
     6  Line #4
     7  Line #5
     8  Line #6
     9  Line #7
    10  Line #8
    11  Line #9
    12  Line #10
[root@node23 ~]# 

Overcoming "Display forbidden by X-Frame-Options"

I'm not sure how relevant it is, but I built a work-around to this. On my site, I wanted to display link in a modal window that contained an iframe which loads the URL.

What I did is, I linked the click event of the link to this javascript function. All this does is make a request to a PHP file that checks the URL headers for X-FRAME-Options before deciding whether to load the URL within the modal window or to redirect.

Here's the function:

  function opentheater(link, title){
        $.get( "url_origin_helper.php?url="+encodeURIComponent(link), function( data ) {
  if(data == "ya"){
      $(".modal-title").html("<h3 style='color:480060;'>"+title+"&nbsp;&nbsp;&nbsp;<small>"+link+"</small></h3>");
        $("#linkcontent").attr("src", link);
        $("#myModal").modal("show");
  }
  else{
      window.location.href = link;
      //alert(data);
  }
});


        }

Here's the PHP file code that checks for it:

<?php
$url = rawurldecode($_REQUEST['url']);
$header = get_headers($url, 1);
if(array_key_exists("X-Frame-Options", $header)){
    echo "nein";
}
else{
    echo "ya";
}


?>

Hope this helps.

How do you check if a certain index exists in a table?

AdaTheDEV, I used your syntax and created the following and why.

Problem: Process runs once a quarter taking an hour due to missing index.

Correction: Alter query process or Procedure to check for index and create it if missing... Same code is placed at the end of the query and procedure to remove index since it is not needed but quarterly. Showing Only drop syntax here

-- drop the index 
begin

  IF EXISTS (SELECT *  FROM sys.indexes  WHERE name='Index_Name' 
    AND object_id = OBJECT_ID('[SchmaName].[TableName]'))
  begin
    DROP INDEX [Index_Name] ON [SchmaName].[TableName];
  end

end

Why is Java's SimpleDateFormat not thread-safe?

Here’s an example defines a SimpleDateFormat object as a static field. When two or more threads access “someMethod” concurrently with different dates, they can mess with each other’s results.

    public class SimpleDateFormatExample {
         private static final SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

         public String someMethod(Date date) {
            return simpleFormat.format(date);
         }
    }

You can create a service like below and use jmeter to simulate concurrent users using the same SimpleDateFormat object formatting different dates and their results will be messed up.

public class FormattedTimeHandler extends AbstractHandler {

private static final String OUTPUT_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
private static final String INPUT_TIME_FORMAT = "yyyy-MM-ddHH:mm:ss";
private static final SimpleDateFormat simpleFormat = new SimpleDateFormat(OUTPUT_TIME_FORMAT);
// apache commons lang3 FastDateFormat is threadsafe
private static final FastDateFormat fastFormat = FastDateFormat.getInstance(OUTPUT_TIME_FORMAT);

public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    response.setContentType("text/html;charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    baseRequest.setHandled(true);

    final String inputTime = request.getParameter("time");
    Date date = LocalDateTime.parse(inputTime, DateTimeFormat.forPattern(INPUT_TIME_FORMAT)).toDate();

    final String method = request.getParameter("method");
    if ("SimpleDateFormat".equalsIgnoreCase(method)) {
        // use SimpleDateFormat as a static constant field, not thread safe
        response.getWriter().println(simpleFormat.format(date));
    } else if ("FastDateFormat".equalsIgnoreCase(method)) {
        // use apache commons lang3 FastDateFormat, thread safe
        response.getWriter().println(fastFormat.format(date));
    } else {
        // create new SimpleDateFormat instance when formatting date, thread safe
        response.getWriter().println(new SimpleDateFormat(OUTPUT_TIME_FORMAT).format(date));
    }
}

public static void main(String[] args) throws Exception {
    // embedded jetty configuration, running on port 8090. change it as needed.
    Server server = new Server(8090);
    server.setHandler(new FormattedTimeHandler());

    server.start();
    server.join();
}

}

The code and jmeter script can be downloaded here .

What is the behavior of integer division?

Where the result is negative, C truncates towards 0 rather than flooring - I learnt this reading about why Python integer division always floors here: Why Python's Integer Division Floors

Select entries between dates in doctrine 2


    EDIT: See the other answers for better solutions

The original newbie approaches that I offered were (opt1):

$qb->where("e.fecha > '" . $monday->format('Y-m-d') . "'");
$qb->andWhere("e.fecha < '" . $sunday->format('Y-m-d') . "'");

And (opt2):

$qb->add('where', "e.fecha between '2012-01-01' and '2012-10-10'");

That was quick and easy and got the original poster going immediately.

Hence the accepted answer.

As per comments, it is the wrong answer, but it's an easy mistake to make, so I'm leaving it here as a "what not to do!"

Exit a Script On Error

If you put set -e in a script, the script will terminate as soon as any command inside it fails (i.e. as soon as any command returns a nonzero status). This doesn't let you write your own message, but often the failing command's own messages are enough.

The advantage of this approach is that it's automatic: you don't run the risk of forgetting to deal with an error case.

Commands whose status is tested by a conditional (such as if, && or ||) do not terminate the script (otherwise the conditional would be pointless). An idiom for the occasional command whose failure doesn't matter is command-that-may-fail || true. You can also turn set -e off for a part of the script with set +e.

Add leading zeroes to number in Java?

In case of your jdk version less than 1.5, following option can be used.

    int iTest = 2;
    StringBuffer sTest = new StringBuffer("000000"); //if the string size is 6
    sTest.append(String.valueOf(iTest));
    System.out.println(sTest.substring(sTest.length()-6, sTest.length()));

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

On mac and sublime text 3 , which version is 3103, the content should be

{
    "shell_cmd": "open -a 'Google Chrome' '$file'"
}

SQL Stored Procedure: If variable is not null, update statement

Another approach when you have many updates would be to use COALESCE:

UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET    
    [ABC]  = COALESCE(@ABC, [ABC]),
    [ABCD] = COALESCE(@ABCD, [ABCD])

Angular.js How to change an elements css class on click and to remove all others

Typically with Angular you would be outputting these spans using the ngRepeat directive and (like in your case) each item would have an id. I know this is not true for all situations but it is typical if requesting data from a backend - objects in an array tend to have unique identifiers.

You can use this id to facilitate the toggling of classes on items in your list (see plunkr or code below).

Using the objects id's can also eliminate the undesirable effect when the $index (described in other answers) is messed up due to sorting in Angular.

Example Plunkr: http://plnkr.co/edit/na0gUec6cdMABK9L6drV

(basically apply the .active-selection class if the person.id is equal to $scope.activeClass - which we set when the user clicks an item.

Hope this helps someone, I've found expressions in ng-class to be very useful!

HTML

<ul>
  <li ng-repeat="person in people" 
  data-ng-class="{'active-selection': person.id == activeClass}">
    <a data-ng-click="selectPerson(person.id)">
      {{person.name}}
    </a>
  </li>
</ul>

JS

app.controller('MainCtrl', function($scope) {
  $scope.people = [{
    id: "1",
    name: "John",
  }, {
    id: "2",
    name: "Lucy"
  }, {
    id: "3",
    name: "Mark"
  }, {
    id: "4",
    name: "Sam"
  }];

  $scope.selectPerson = function(id) {
    $scope.activeClass = id;
    console.log(id);
  };
});    

CSS:

.active-selection {
  background-color: #eee;
}

How to get the full path of running process?

using System;
using System.Diagnostics;

class Program
{
    public static void printAllprocesses()
    {
        Process[] processlist = Process.GetProcesses();

        foreach (Process process in processlist)
        {
            try
            {
                String fileName = process.MainModule.FileName;
                String processName = process.ProcessName;

                Console.WriteLine("processName : {0},  fileName : {1}", processName, fileName);
            }catch(Exception e)
            {
                /* You will get access denied exception for system processes, We are skiping the system processes here */
            }

        }
    }

    static void Main()
    {
        printAllprocesses();
    }

}

Is there a real solution to debug cordova apps

On Android 4.4+ w/SDK installed:

adb logcat chromium:D SystemWebViewClient:D \*:S

Reading a string with scanf

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I think the C implementation on the Symbolics "Lisp Machines" did something like this.)

How/when to use ng-click to call a route?

just do it as follows in your html write:

<button ng-click="going()">goto</button>

And in your controller, add $state as follows:

.controller('homeCTRL', function($scope, **$state**) {

$scope.going = function(){

$state.go('your route');

}

})

Java how to sort a Linked List?

In java8 you no longer need to use Collections.sort method as LinkedList inherits the method sort from java.util.List, so adapting Fido's answer to Java8:

    LinkedList<String>list = new LinkedList<String>();
    list.add("abc");
    list.add("Bcd");
    list.add("aAb");

    list.sort( new Comparator<String>(){
    @Override
        public int compare(String o1,String o2){
            return Collator.getInstance().compare(o1,o2);
        }
    });

References:

http://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html

http://docs.oracle.com/javase/7/docs/api/java/util/List.html

What's wrong with foreign keys?

I also think that foreign keys are a necessity in most databases. The only drawback (besides the performance hit that comes with having enforced consistence) is that having a foreign key allows people to write code that assumes there is a functional foreign key. That should never be allowed.

For example, I've seen people write code that inserts into the referenced table and then attempts inserts into the referencing table without verifying the first insert was successful. If the foreign key is removed at a later time, that results in an inconsistent database.

You also don't have the option of assuming a specific behavior on update or delete. You still need to write your code to do what you want regardless of whether there is a foreign key present. If you assume deletes are cascaded when they are not, your deletes will fail. If you assume updates to the referenced columns are propogated to the referencing rows when they are not, your updates will fail. For the purposes of writing code, you might as well not have those features.

If those features are turned on, then your code will emulate them anyway and you'll lose a little performance.

So, the summary.... Foreign keys are essential if you need a consistent database. Foreign keys should never be assumed to be present or functional in code that you write.

Conditionally Remove Dataframe Rows with R

Subset is your safest and easiest answer.

subset(dataframe, A==B & E!=0)

Real data example with mtcars

subset(mtcars, cyl==6 & am!=0)

Extracting Ajax return data in jQuery

You may also use the jQuery context parameter. Link to docs

Selector Context

By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function

Therefore you could also have:

success: function(data){
    var oneval = $('#one',data).text();
    var subval = $('#sub',data).text();
}

What is the correct way of reading from a TCP socket in C/C++?

If you actually create the buffer as per dirks suggestion, then:

  int readResult = read(socketFileDescriptor, buffer, BUFFER_SIZE);

may completely fill the buffer, possibly overwriting the terminating zero character which you depend on when extracting to a stringstream. You need:

  int readResult = read(socketFileDescriptor, buffer, BUFFER_SIZE - 1 );

Add a UIView above all, even the navigation bar

UIApplication.shared.keyWindow?.insertSubview(yourView, at: 1)

This method works with xcode 9.4 , iOS 11.4

How to call a C# function from JavaScript?

If you're meaning to make a server call from the client, you should use Ajax - look at something like Jquery and use $.Ajax() or $.getJson() to call the server function, depending on what kind of return you're after or action you want to execute.

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

if you work with pandas what solved the issue for me was that i was trying to do calculations when I had NA values, the solution was to run:

df = df.dropna()

And after that the calculation that failed.

How do I open a URL from C++?

There're already answers for windows. In linux, I noticed open https://www.google.com always launch browser from shell, so you can try:

system("open https://your.domain/uri");

that's say

system(("open "s + url).c_str()); // c++

https://linux.die.net/man/1/open

mysql alphabetical order

Wildcard Characters are used with like clause to sort records.

if we want to search a string which is starts with B then code is like the following:

select * from tablename where colname like 'B%' order by columnname ;

if we want to search a string which is ends with B then code is like the following: select * from tablename where colname like '%B' order by columnname ;

if we want to search a string which is contains B then code is like the following: select * from tablename where colname like '%B%' order by columnname ;

if we want to search a string in which second character is B then code is like the following: select * from tablename where colname like '_B%' order by columnname ;

if we want to search a string in which third character is B then code is like the following: select * from tablename where colname like '__B%' order by columnname ;

note : one underscore for one character.

Batch file to run a command in cmd within a directory

This question is 5 years old. I wonder why still nobody has found the /d switch to set the working folder:

start /d "c:\activiti-5.9\setup" cmd /k ant demo.start

CSS to stop text wrapping under image

Since this question is gaining lots of views and this was the accepted answer, I felt the need to add the following disclaimer:

This answer was specific to the OP's question (Which had the width set in the examples). While it works, it requires you to have a width on each of the elements, the image and the paragraph. Unless that is your requirement, I recommend using Joe Conlin's solution which is posted as another answer on this question.

The span element is an inline element, you can't change its width in CSS.

You can add the following CSS to your span so you will be able to change its width.

display: block;

Another way, which usually makes more sense, is to use a <p> element as a parent for your <span>.

<li id="CN2787">
  <img class="fav_star" src="images/fav.png">
  <p>
     <span>Text, text and more text</span>
  </p>
</li>

Since <p> is a block element, you can set its width using CSS, without having to change anything.

But in both cases, since you have a block element now, you will need to float the image so that your text doesn't all go below your image.

li p{width: 100px; margin-left: 20px}
.fav_star {width: 20px;float:left}

P.S. Instead of float:left on the image, you can also put float:right on li p but in that case, you will also need text-align:left to realign the text correctly.

P.S.S. If you went ahead with the first solution of not adding a <p> element, your CSS should look like so:

li span{width: 100px; margin-left: 20px;display:block}
.fav_star {width: 20px;float:left}

How to control the width of select tag?

Add div wrapper

<div id=myForm>
<select name=countries>
 <option value=af>Afghanistan</option>
 <option value=ax>Åland Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>
</div>

and then write CSS

#myForm select { 
width:200px; }

#myForm select:focus {
width:auto; }

Hope this will help.

Downloading all maven dependencies to a directory NOT in repository?

The maven dependency plugin can potentially solve your problem.

If you have a pom with all your project dependencies specified, all you would need to do is run

mvn dependency:copy-dependencies

and you will find the target/dependencies folder filled with all the dependencies, including transitive.

Adding Gustavo's answer from below: To download the dependency sources, you can use

mvn dependency:copy-dependencies -Dclassifier=sources

(via Apache Maven Dependency Plugin doc).

jQuery Scroll to bottom of page/iframe

This one worked for me:

var elem = $('#box');
if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) {
  // We're at the bottom.
}

IOPub data rate exceeded in Jupyter notebook (when viewing image)

By typing 'jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10' in Anaconda PowerShell or prompt, the Jupyter notebook will open with the new configuration. Try now to run your query.

add elements to object array

You can try

Subject[] subjects = new Subject[2];
subjects[0] = new Subject{....};
subjects[1] = new Subject{....};

alternatively you can use List

List<Subject> subjects = new List<Subject>();
subjects.add(new Subject{....});
subjects.add(new Subject{....});

Calculate mean across dimension in a 2D array

Here is a non-numpy solution:

>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]

Entity Framework Provider type could not be loaded?

Late to the party, but the top voted answers all seemed like hacks to me.

All I did was remove the following from my app.config in the test project. Worked.

  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

How to add parameters to HttpURLConnection using POST using NameValuePair

AsyncTask to send data as JSONObect via POST Method

public class PostMethodDemo extends AsyncTask<String , Void ,String> {
        String server_response;

        @Override
        protected String doInBackground(String... strings) {
            URL url;
            HttpURLConnection urlConnection = null;

            try {
                url = new URL(strings[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoOutput(true);
                urlConnection.setDoInput(true);
                urlConnection.setRequestMethod("POST");

                DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream ());

                try {
                    JSONObject obj = new JSONObject();
                    obj.put("key1" , "value1");
                    obj.put("key2" , "value2");

                    wr.writeBytes(obj.toString());
                    Log.e("JSON Input", obj.toString());
                    wr.flush();
                    wr.close();
                } catch (JSONException ex) {
                    ex.printStackTrace();
                }
                urlConnection.connect();

                int responseCode = urlConnection.getResponseCode();

                if(responseCode == HttpURLConnection.HTTP_OK){
                    server_response = readStream(urlConnection.getInputStream());
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.e("Response", "" + server_response);
        }
    }

    public static String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response.toString();
    }

Merge, update, and pull Git branches without using checkouts

As Amber said, fast-forward merges are the only case in which you could conceivably do this. Any other merge conceivably needs to go through the whole three-way merge, applying patches, resolving conflicts deal - and that means there need to be files around.

I happen to have a script around I use for exactly this: doing fast-forward merges without touching the work tree (unless you're merging into HEAD). It's a little long, because it's at least a bit robust - it checks to make sure that the merge would be a fast-forward, then performs it without checking out the branch, but producing the same results as if you had - you see the diff --stat summary of changes, and the entry in the reflog is exactly like a fast forward merge, instead of the "reset" one you get if you use branch -f. If you name it git-merge-ff and drop it in your bin directory, you can call it as a git command: git merge-ff.

#!/bin/bash

_usage() {
    echo "Usage: git merge-ff <branch> <committish-to-merge>" 1>&2
    exit 1
}

_merge_ff() {
    branch="$1"
    commit="$2"

    branch_orig_hash="$(git show-ref -s --verify refs/heads/$branch 2> /dev/null)"
    if [ $? -ne 0 ]; then
        echo "Error: unknown branch $branch" 1>&2
        _usage
    fi

    commit_orig_hash="$(git rev-parse --verify $commit 2> /dev/null)"
    if [ $? -ne 0 ]; then
        echo "Error: unknown revision $commit" 1>&2
        _usage
    fi

    if [ "$(git symbolic-ref HEAD)" = "refs/heads/$branch" ]; then
        git merge $quiet --ff-only "$commit"
    else
        if [ "$(git merge-base $branch_orig_hash $commit_orig_hash)" != "$branch_orig_hash" ]; then
            echo "Error: merging $commit into $branch would not be a fast-forward" 1>&2
            exit 1
        fi
        echo "Updating ${branch_orig_hash:0:7}..${commit_orig_hash:0:7}"
        if git update-ref -m "merge $commit: Fast forward" "refs/heads/$branch" "$commit_orig_hash" "$branch_orig_hash"; then
            if [ -z $quiet ]; then
                echo "Fast forward"
                git diff --stat "$branch@{1}" "$branch"
            fi
        else
            echo "Error: fast forward using update-ref failed" 1>&2
        fi
    fi
}

while getopts "q" opt; do
    case $opt in
        q ) quiet="-q";;
        * ) ;;
    esac
done
shift $((OPTIND-1))

case $# in
    2 ) _merge_ff "$1" "$2";;
    * ) _usage
esac

P.S. If anyone sees any issues with that script, please comment! It was a write-and-forget job, but I'd be happy to improve it.

How to do a regular expression replace in MySQL?

I think there is an easy way to achieve this and It's working fine for me.

To SELECT rows using REGEX

SELECT * FROM `table_name` WHERE `column_name_to_find` REGEXP 'string-to-find'

To UPDATE rows using REGEX

UPDATE `table_name` SET column_name_to_find=REGEXP_REPLACE(column_name_to_find, 'string-to-find', 'string-to-replace') WHERE column_name_to_find REGEXP 'string-to-find'

REGEXP Reference: https://www.geeksforgeeks.org/mysql-regular-expressions-regexp/

PHPMailer - SMTP ERROR: Password command failed when send mail from my server

As others already suggested, you can enable the "less secure" applications or you can simply switch from ssl to tls:

$mailer->Host = 'tls://smtp.gmail.com';
$mailer->SMTPAuth = true;
$mailer->Username = "[email protected]";
$mailer->Password = "***";
$mailer->SMTPSecure = 'tls';
$mailer->Port = 587;

When using tls there's no need to grant access for less secure applications, just make sure, IMAP is enabled.

How can I iterate over the elements in Hashmap?

You should not map score to player. You should map player (or his name) to score:

Map<Player, Integer> player2score = new HashMap<Player, Integer>();

Then add players to map: int score = .... Player player = new Player(); player.setName("John"); // etc. player2score.put(player, score);

In this case the task is trivial:

int score = player2score.get(player);

Execute ssh with password authentication via windows command prompt

The sshpass utility is meant for exactly this. First, install sshpass by typing this command:

sudo apt-get install sshpass

Then prepend your ssh/scp command with

sshpass -p '<password>' <ssh/scp command>

This program is easiest to install when using Linux.

User should consider using SSH's more secure public key authentication (with the ssh command) instead.

Placing/Overlapping(z-index) a view above another view in android

I solved the same problem by add android:elevation="1dp" to which view you want it over another. But it can't display below 5.0, and it will have a little shadow, if you can accept it, it's OK.

So, the most correct solution which is @kcoppock said.

How to install packages offline?

If the package is on PYPI, download it and its dependencies to some local directory. E.g.

$ mkdir /pypi && cd /pypi
$ ls -la
  -rw-r--r--   1 pavel  staff   237954 Apr 19 11:31 Flask-WTF-0.6.tar.gz
  -rw-r--r--   1 pavel  staff   389741 Feb 22 17:10 Jinja2-2.6.tar.gz
  -rw-r--r--   1 pavel  staff    70305 Apr 11 00:28 MySQL-python-1.2.3.tar.gz
  -rw-r--r--   1 pavel  staff  2597214 Apr 10 18:26 SQLAlchemy-0.7.6.tar.gz
  -rw-r--r--   1 pavel  staff  1108056 Feb 22 17:10 Werkzeug-0.8.2.tar.gz
  -rw-r--r--   1 pavel  staff   488207 Apr 10 18:26 boto-2.3.0.tar.gz
  -rw-r--r--   1 pavel  staff   490192 Apr 16 12:00 flask-0.9-dev-2a6c80a.tar.gz

Some packages may have to be archived into similar looking tarballs by hand. I do it a lot when I want a more recent (less stable) version of something. Some packages aren't on PYPI, so same applies to them.

Suppose you have a properly formed Python application in ~/src/myapp. ~/src/myapp/setup.py will have install_requires list that mentions one or more things that you have in your /pypi directory. Like so:

  install_requires=[
    'boto',
    'Flask',
    'Werkzeug',
    # and so on

If you want to be able to run your app with all the necessary dependencies while still hacking on it, you'll do something like this:

$ cd ~/src/myapp
$ python setup.py develop --always-unzip --allow-hosts=None --find-links=/pypi

This way your app will be executed straight from your source directory. You can hack on things, and then rerun the app without rebuilding anything.

If you want to install your app and its dependencies into the current python environment, you'll do something like this:

$ cd ~/src/myapp
$ easy_install --always-unzip --allow-hosts=None --find-links=/pypi .

In both cases, the build will fail if one or more dependencies aren't present in /pypi directory. It won't attempt to promiscuously install missing things from Internet.

I highly recommend to invoke setup.py develop ... and easy_install ... within an active virtual environment to avoid contaminating your global Python environment. It is (virtualenv that is) pretty much the way to go. Never install anything into global Python environment.

If the machine that you've built your app has same architecture as the machine on which you want to deploy it, you can simply tarball the entire virtual environment directory into which you easy_install-ed everything. Just before tarballing though, you must make the virtual environment directory relocatable (see --relocatable option). NOTE: the destination machine needs to have the same version of Python installed, and also any C-based dependencies your app may have must be preinstalled there too (e.g. say if you depend on PIL, then libpng, libjpeg, etc must be preinstalled).

Extracting time from POSIXct

I can't find anything that deals with clock times exactly, so I'd just use some functions from package:lubridate and work with seconds-since-midnight:

require(lubridate)
clockS = function(t){hour(t)*3600+minute(t)*60+second(t)}
plot(clockS(times),val)

You might then want to look at some of the axis code to figure out how to label axes nicely.

ScrollTo function in AngularJS

I used andrew joslin's answer, which works great but triggered an angular route change, which created a jumpy looking scroll for me. If you want to avoid triggering a route change,

myApp.directive('scrollOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, $elm, attrs) {
      var idToScroll = attrs.href;
      $elm.on('click', function(event) {
        event.preventDefault();
        var $target;
        if (idToScroll) {
          $target = $(idToScroll);
        } else {
          $target = $elm;
        }
        $("body").animate({scrollTop: $target.offset().top}, "slow");
        return false;
      });
    }
  }
});

Bootstrap datepicker hide after selection

Use this for datetimepicker, it works fine

$('#Date').data("DateTimePicker").hide();

Variables as commands in bash scripts

Simply don't put whole commands in variables. You'll get into a lot of trouble trying to recover quoted arguments.

Also:

  1. Avoid using all-capitals variable names in scripts. Easy way to shoot yourself on the foot.
  2. Don't use backquotes, use $(...) instead, it nests better.

#! /bin/bash

if [ $# -ne 2 ]
then
    echo "Usage: $(basename $0) DIRECTORY BACKUP_DIRECTORY"
    exit 1
fi

directory=$1
backup_directory=$2
current_date=$(date +%Y-%m-%dT%H-%M-%S)
backup_file="${backup_directory}/${current_date}.backup"

tar cv "$directory" | openssl des3 -salt | split -b 1024m - "$backup_file"

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

Spark : how to run spark file from spark shell

In command line, you can use

spark-shell -i file.scala

to run code which is written in file.scala

Explain the "setUp" and "tearDown" Python methods used in test cases

Suppose you have a suite with 10 tests. 8 of the tests share the same setup/teardown code. The other 2 don't.

setup and teardown give you a nice way to refactor those 8 tests. Now what do you do with the other 2 tests? You'd move them to another testcase/suite. So using setup and teardown also helps give a natural way to break the tests into cases/suites

How do I display a decimal value to 2 decimal places?

If you need to keep only 2 decimal places (i.e. cut off all the rest of decimal digits):

decimal val = 3.14789m;
decimal result = Math.Floor(val * 100) / 100; // result = 3.14

If you need to keep only 3 decimal places:

decimal val = 3.14789m;
decimal result = Math.Floor(val * 1000) / 1000; // result = 3.147

Spring Security exclude url patterns in security annotation configurartion

Found the solution in Spring security examples posted in Github.

WebSecurityConfigurerAdapter has a overloaded configure message that takes WebSecurity as argument which accepts ant matchers on requests to be ignored.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/authFailure");
}

See Spring Security Samples for more details

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

Another GUI based option to fix this error is to download the PackageManagement PowerShell Modules (msi installer) from Microsoft website and install the modules.

Once this is installed you will not get "'Install-Module' is not recognized as the name of a cmdlet" error.

C++ int to byte array

You don't need a whole function for this; a simple cast will suffice:

int x;
static_cast<char*>(static_cast<void*>(&x));

Any object in C++ can be reinterpreted as an array of bytes. If you want to actually make a copy of the bytes into a separate array, you can use std::copy:

int x;
char bytes[sizeof x];
std::copy(static_cast<const char*>(static_cast<const void*>(&x)),
          static_cast<const char*>(static_cast<const void*>(&x)) + sizeof x,
          bytes);

Neither of these methods takes byte ordering into account, but since you can reinterpret the int as an array of bytes, it is trivial to perform any necessary modifications yourself.