Programs & Examples On #Imperative languages

Programming languages based on the paradigm of imperative programming.

How do you reverse a string in place in C or C++?

Yet another:

#include <stdio.h>
#include <strings.h>

int main(int argc, char **argv) {

  char *reverse = argv[argc-1];
  char *left = reverse;
  int length = strlen(reverse);
  char *right = reverse+length-1;
  char temp;

  while(right-left>=1){

    temp=*left;
    *left=*right;
    *right=temp;
    ++left;
    --right;

  }

  printf("%s\n", reverse);

}

[Vue warn]: Cannot find element

I get the same error. the solution is to put your script code before the end of body, not in the head section.

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use the below code on your string and you will get the complete string without html part.

string title = "<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)".Replace("&nbsp;",string.Empty);            
        string s = Regex.Replace(title, "<.*?>", String.Empty);

How to get 0-padded binary representation of an integer in java?

I do not know "right" solution but I can suggest you a fast patch.

String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0");

I have just tried it and saw that it works fine.

How to read integer values from text file

You can use a Scanner and its nextInt() method.
Scanner also has nextLong() for larger integers, if needed.

java calling a method from another class

You're very close. What you need to remember is when you're calling a method from another class you need to tell the compiler where to find that method.

So, instead of simply calling addWord("someWord"), you will need to initialise an instance of the WordList class (e.g. WordList list = new WordList();), and then call the method using that (i.e. list.addWord("someWord");.

However, your code at the moment will still throw an error there, because that would be trying to call a non-static method from a static one. So, you could either make addWord() static, or change the methods in the Words class so that they're not static.

My bad with the above paragraph - however you might want to reconsider ProcessInput() being a static method - does it really need to be?

How to check if a json key exists?

I used hasOwnProperty('club')

var myobj = { "regatta_name":"ProbaRegatta",
    "country":"Congo",
    "status":"invited"
 };

 if ( myobj.hasOwnProperty("club"))
     // do something with club (will be false with above data)
     var data = myobj.club;
 if ( myobj.hasOwnProperty("status"))
     // do something with the status field. (will be true with above ..)
     var data = myobj.status;

works in all current browsers.

R - " missing value where TRUE/FALSE needed "

Can you change the if condition to this:

if (!is.na(comments[l])) print(comments[l]);

You can only check for NA values with is.na().

Check difference in seconds between two times

DateTime has a Subtract method and an overloaded - operator for just such an occasion:

DateTime now = DateTime.UtcNow;
TimeSpan difference = now.Subtract(otherTime); // could also write `now - otherTime`
if (difference.TotalSeconds > 5) { ... }

Can "git pull --all" update all my local branches?

You can't do it with only one git command but you can automate it with one bash line.

To safely update all branches with one line, here is what I do:

git fetch --all && for branch in $(git branch | sed '/*/{$q;h;d};$G' | tr -d '*') ; do git checkout $branch && git merge --ff-only || break ; done
  • If it can't fast-forward one branch or encounter an error, it will stop and leave you in that branch so that you can take back control and merge manually.

  • If all branches can be fast-forwarded, it will end with the branch you were currently in, leaving you where you were before updating.

Explanations:

For a better readability, it can be split over several lines:

git fetch --all && \
for branch in $(git branch | sed '/*/{$q;h;d};$G' | tr -d '*')
    do git checkout $branch && \
    git merge --ff-only || break
done
  1. git fetch --all && ... => Fetches all refs from all remotes and continue with the next command if there has been no error.

  2. git branch | sed '/*/{$q;h;d};$G' | tr -d '*' => From the output of git branch, sed take the line with a * and move it to the end (so that the current branch will be updated last). Then tr simply remove the *.

  3. for branch in $(...) ; do git checkout $branch && git merge --ff-only || break ; done = > For each branch name obtained from the previous command, checkout this branch and try to merge with a fast-forward. If it fails, break is called and the command stops here.

Of course, you can replace git merge --ff-only with git rebase if it is what you want.

Finally, you can put it in your bashrc as an alias:

alias git-pull-all='git fetch --all && for branch in $(git branch | sed '\''/*/{$q;h;d};$G'\'' | tr -d "*") ; do git checkout $branch && git merge --ff-only || break ; done'

Or if you are afraid of messing up with the ' and ", or you simply prefer to keep syntactic readability in your editor, you can declare it as a function:

git-pull-all()
{
    git fetch --all && for branch in $(git branch | sed '/*/{$q;h;d};$G' | tr -d '*') ; do git checkout $branch && git merge --ff-only || break ; done
}

Bonus:

For those who'd like the explanation on the sed '/*/{$q;h;d};$G' part:

  • /*/ => Search for the line with a *.

  • {$q => If it is in the last line, quit (we don't need to do anything because the current branch is already the last one in the list).

  • ;h;d} => Otherwise, store the line in the hold buffer and delete it in the current list position.

  • ;$G => When it reaches the last line, append the content of the hold buffer.

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

Open your system command prompt/terminal -> Go to your Project folder path (root project folder ) -> Execute following command : command :- gradlew clean or ./gradlew clean

Make sure that all your gradle dependencies are of same version. -> Example :- your appcompat and recyclerview dependencies should have same version.

-> Change your gradle dependencies to same version like :-

compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.android.support:recyclerview-v7:23.4.0'
compile 'com.android.support:cardview-v7:23.4.0'

-> Rebuild your project and it will work fine.

Remote Connections Mysql Ubuntu

I was facing the same problem when I was trying to connect Mysql to a Remote Server. I had found out that I had to change the bind-address to the current private IP address of the DB server. But when I was trying to add the bind-address =0.0.0.0 line in my.cnf file, it was not understanding the line when I tried to create a DB.

Upon searching, I found out the original place where bind-address was declared.

The actual declaration is in : /etc/mysql/mariadb.conf.d/50-server.cnf

Therefore I changed the bind-address directly there and then all seems working.

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

I usually embed the xmlns:ads property into the adview properties this way:

<com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_ad_unit_id"/>

so that you dont need to embed into the parent every and each time you copy the adview.

Just copy and paste the adview above and paste it anywhere and it should work

MySQL - Trigger for updating same table after insert

DELIMITER $$

DROP TRIGGER IF EXISTS `setEditStatus`$$
CREATE TRIGGER `setEditStatus` **BEFORE** INSERT on ACCOUNTS
FOR EACH ROW BEGIN

    SET NEW.STATUS = 'E';

END$$

DELIMITER ;

Find length (size) of an array in jquery

obj={};

$.each(obj, function (key, value) {
    console.log(key+ ' : ' + value); //push the object value
});

for (var i in obj) {
    nameList += "" + obj[i] + "";//display the object value
}

$("id/class").html($(nameList).length);//display the length of object.

Cannot connect to repo with TortoiseSVN

Once I faced the same issue. I was trying to take svn checkout using repository URL consisting of DOMAIN NAME. I tried to connect using IP address in place of DOMAIN NAME and I was able to take checkout

Android widget: How to change the text of a button

//text button:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" text button" />

// color text button:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text button" 
        android:textColor="@android:color/color text"/>

// background button

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text button" 
        android:textColor="@android:color/white"
        android:background="@android:color/ background button"/>

// text size button

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text button" 
        android:textColor="@android:color/white"
        android:background="@android:color/black"
        android:textSize="text size"/>

HTML Input="file" Accept Attribute File Type (CSV)

In addition to the top-answer, CSV files, for example, are reported as text/plain under macOS but as application/vnd.ms-excel under Windows. So I use this:

<input type="file" accept="text/plain, .csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />

Decoding JSON String in Java

This is the best and easiest code:

public class test
{
    public static void main(String str[])
    {
        String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONObject newJSON = jsonObject.getJSONObject("stat");
        System.out.println(newJSON.toString());
        jsonObject = new JSONObject(newJSON.toString());
        System.out.println(jsonObject.getString("rcv"));
       System.out.println(jsonObject.getJSONArray("argv"));
    }
}

The library definition of the json files are given here. And it is not same libraries as posted here, i.e. posted by you. What you had posted was simple json library I have used this library.

You can download the zip. And then create a package in your project with org.json as name. and paste all the downloaded codes there, and have fun.

I feel this to be the best and the most easiest JSON Decoding.

Can you force Visual Studio to always run as an Administrator in Windows 8?

I know this is a little late, but I just figured out how to do this by modifying (read, "hacking") the manifest of the devenv.exe file. I should have come here first because the stated solutions seem a little easier, and probably more supported by Microsoft. :)

Here's how I did it:

  1. Create a project in VS called "Exe Manifests". (I think any version will work, but I used 2013 Pro. Also, it doesn't really matter what you name it.)
  2. "Add existing item" to the project, browse to the Visual Studio exe, and click Okay. In my case, it was "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe".
  3. Double-click on the "devenv.exe" file that should now be listed as a file in your project. It should bring up the exe in a resource editor.
  4. Expand the "RT_MANIFEST" node, then double-click on "1" under that. This will open up the executable's manifest in the binary editor.
  5. Find the requestedExecutionLevel tag and replace "asInvoker" with "requireAdministrator". A la: <requestedExecutionLevel level="requireAdministrator" uiAccess="false"></requestedExecutionLevel>
  6. Save the file.

You've just saved the copy of the executable that was added to your project. Now you need to back up the original and copy your modified exe to your installation directory.

As I said, this is probably not the right way to do it, but it seems to work. If anyone knows of any negative fallout or requisite wrist-slapping that needs to happen, please chime in!

Android Split string

.split method will work, but it uses regular expressions. In this example it would be (to steal from Cristian):

String[] separated = CurrentString.split("\\:");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"

Also, this came from: Android split not working correctly

How do I get multiple subplots in matplotlib?

There are several ways to do it. The subplots method creates the figure along with the subplots that are then stored in the ax array. For example:

import matplotlib.pyplot as plt

x = range(10)
y = range(10)

fig, ax = plt.subplots(nrows=2, ncols=2)

for row in ax:
    for col in row:
        col.plot(x, y)

plt.show()

enter image description here

However, something like this will also work, it's not so "clean" though since you are creating a figure with subplots and then add on top of them:

fig = plt.figure()

plt.subplot(2, 2, 1)
plt.plot(x, y)

plt.subplot(2, 2, 2)
plt.plot(x, y)

plt.subplot(2, 2, 3)
plt.plot(x, y)

plt.subplot(2, 2, 4)
plt.plot(x, y)

plt.show()

enter image description here

How to create a hex dump of file containing only the hex characters without spaces in bash?

Format strings can make hexdump behave exactly as you want it to (no whitespace at all, byte by byte):

hexdump -ve '1/1 "%.2x"'

1/1 means "each format is applied once and takes one byte", and "%.2x" is the actual format string, like in printf. In this case: 2-character hexadecimal number, leading zeros if shorter.

Tomcat: How to find out running tomcat version

For Windows PowerShell command-line method of checking running version(s) of Tomcat service:

(get-service Tomcat*).DisplayName

Sample output...

Apache Tomcat 8.5 Tomcat8

If also want to know additional details including the location of folder where service running at:

Get-WmiObject win32_service | Where-Object {$_.Name -like 'Tomcat*'} | select Name, DisplayName, State, PathName

Sample output...

Name    DisplayName               State   PathName
----    -----------               -----   --------
Tomcat8 Apache Tomcat 8.5 Tomcat8 Running "C:\Program Files\Apache Software Foundation\Tomcat 8.5\bin\Tomcat8.exe" /...

Convert spark DataFrame column to python list

This will give you all the elements as a list.

mvv_list = list(
    mvv_count_df.select('mvv').toPandas()['mvv']
)

how to remove untracked files in Git?

Those are untracked files. This means git isn't tracking them. It's only listing them because they're not in the git ignore file. Since they're not being tracked by git, git reset won't touch them.

If you want to blow away all untracked files, the simplest way is git clean -f (use git clean -n instead if you want to see what it would destroy without actually deleting anything). Otherwise, you can just delete the files you don't want by hand.

Import SQL dump into PostgreSQL database

I noticed that many examples are overcomplicated for localhost where just postgres user without password exist in many cases:

psql -d db_name -f dump.sql

Running bash script from within python

Adding an answer because I was directed here after asking how to run a bash script from python. You receive an error OSError: [Errno 2] file not found if your script takes in parameters. Lets say for instance your script took in a sleep time parameter: subprocess.call("sleep.sh 10") will not work, you must pass it as an array: subprocess.call(["sleep.sh", 10])

How to detect when cancel is clicked on file input?

You can't.

The result of the file dialog is not exposed to the browser.

how to set active class to nav menu from twitter bootstrap

it is a workaround. try

<div class="nav-collapse">
  <ul class="nav">
    <li id="home" class="active"><a href="~/Home/Index">Home</a></li>
    <li><a href="#">Project</a></li>
    <li><a href="#">Customer</a></li>
    <li><a href="#">Staff</a></li>
    <li  id="demo"><a href="~/Home/demo">Broker</a></li>
    <li id='sale'><a href="#">Sale</a></li>
  </ul>
</div>

and on each page js add

$(document).ready(function () {
  $(".nav li").removeClass("active");//this will remove the active class from  
                                     //previously active menu item 
  $('#home').addClass('active');
  //for demo
  //$('#demo').addClass('active');
  //for sale 
  //$('#sale').addClass('active');
});

Detecting iOS orientation change instantly

Add a notifier in the viewWillAppear function

-(void)viewWillAppear:(BOOL)animated{
  [super viewWillAppear:animated];
  [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(orientationChanged:)    name:UIDeviceOrientationDidChangeNotification  object:nil];
}

The orientation change notifies this function

- (void)orientationChanged:(NSNotification *)notification{
   [self adjustViewsForOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
}

which in-turn calls this function where the moviePlayerController frame is orientation is handled

- (void) adjustViewsForOrientation:(UIInterfaceOrientation) orientation {

    switch (orientation)
    {
        case UIInterfaceOrientationPortrait:
        case UIInterfaceOrientationPortraitUpsideDown:
        { 
        //load the portrait view    
        }

            break;
        case UIInterfaceOrientationLandscapeLeft:
        case UIInterfaceOrientationLandscapeRight:
        {
        //load the landscape view 
        }
            break;
        case UIInterfaceOrientationUnknown:break;
    }
}

in viewDidDisappear remove the notification

-(void)viewDidDisappear:(BOOL)animated{
   [super viewDidDisappear:animated];
   [[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
}

I guess this is the fastest u can have changed the view as per orientation

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

Since the tests will be instantiated like a Spring bean too, you just need to implement the ApplicationContextAware interface:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{

  @Autowired
  MyService service;
...
    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException
    {
        // Do something with the context here
    }
}

Save ArrayList to SharedPreferences

This is your perfect solution.. try it,

public void saveArrayList(ArrayList<String> list, String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    SharedPreferences.Editor editor = prefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(list);
    editor.putString(key, json);
    editor.apply();     // This line is IMPORTANT !!!
}

public ArrayList<String> getArrayList(String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    return gson.fromJson(json, type);
}

Calling method using JavaScript prototype

Another way with ES5 is to explicitely traverse the prototype chain using Object.getPrototypeOf(this)

const speaker = {
  speak: () => console.log('the speaker has spoken')
}

const announcingSpeaker = Object.create(speaker, {
  speak: {
    value: function() {
      console.log('Attention please!')
      Object.getPrototypeOf(this).speak()
    }
  }
})

announcingSpeaker.speak()

Name [jdbc/mydb] is not bound in this Context

For those who use Tomcat with Bitronix, this will fix the problem:

The error indicates that no handler could be found for your datasource 'jdbc/mydb', so you'll need to make sure your tomcat server refers to your bitronix configuration files as needed.

In case you're using btm-config.properties and resources.properties files to configure the datasource, specify these two JVM arguments in tomcat:

(if you already used them, make sure your references are correct):

  • btm.root
  • bitronix.tm.configuration

e.g.

-Dbtm.root="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59" 
-Dbitronix.tm.configuration="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59\conf\btm-config.properties" 

Now, restart your server and check the log.

Unable to verify leaf signature

The Secure Solution

Rather than turning off security you can add the necessary certificates to the chain. First install ssl-root-cas package from npm:

npm install ssl-root-cas

This package contains many intermediary certificates that browsers trust but node doesn't.

var sslRootCAs = require('ssl-root-cas/latest')
sslRootCAs.inject()

Will add the missing certificates. See here for more info:

https://git.coolaj86.com/coolaj86/ssl-root-cas.js

Also, See the next answer below

Set default option in mat-select

Try this

<mat-form-field>
    <mat-select [(ngModel)]="modeselect" [placeholder]="modeselect">
        <mat-option value="domain">Domain</mat-option>
        <mat-option value="exact">Exact</mat-option>
    </mat-select>
</mat-form-field>

Component:

export class SelectValueBindingExample {
    public modeselect = 'Domain';
}

Live demo

Also, don't forget to import FormsModule in your app.module

How to use router.navigateByUrl and router.navigate in Angular

In addition to the provided answer, there are more details to navigate. From the function's comments:

/**
 * Navigate based on the provided array of commands and a starting point.
 * If no starting route is provided, the navigation is absolute.
 *
 * Returns a promise that:
 * - resolves to 'true' when navigation succeeds,
 * - resolves to 'false' when navigation fails,
 * - is rejected when an error happens.
 *
 * ### Usage
 *
 * ```
 * router.navigate(['team', 33, 'user', 11], {relativeTo: route});
 *
 * // Navigate without updating the URL
 * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
 * ```
 *
 * In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
 * URL.
 */

The Router Guide has more details on programmatic navigation.

endsWith in JavaScript

all of them are very useful examples. Adding String.prototype.endsWith = function(str) will help us to simply call the method to check if our string ends with it or not, well regexp will also do it.

I found a better solution than mine. Thanks every one.

what is the difference between OLE DB and ODBC data sources?

At Microsoft website, it shows that native OLEDB provider is applied to SQL server directly and another OLEDB provider called OLEDB Provider for ODBC to access other Database, such as Sysbase, DB2 etc. There are different kinds of component under OLEDB Provider. See Distributed Queries on MSDN for more.

Where is Python language used?

Python is also great for scientific programs such as statistical models or physics sims. I've done monte-carlo programs and, using the VISUAL module, a 3D simulation of the Apollo mission.

How to trigger an event after using event.preventDefault()

The accepted solution wont work in case you are working with an anchor tag. In this case you wont be able to click the link again after calling e.preventDefault(). Thats because the click event generated by jQuery is just layer on top of native browser events. So triggering a 'click' event on an anchor tag wont follow the link. Instead you could use a library like jquery-simulate that will allow you to launch native browser events.

More details about this can be found in this link

sql server convert date to string MM/DD/YYYY

As of SQL Server 2012+, you can use FORMAT(value, format [, culture ])

Where the format param takes any valid standard format string or custom formatting string

Example:

SELECT FORMAT(GETDATE(), 'MM/dd/yyyy')

Further Reading:

What is difference between mutable and immutable String in java

Mutable means you will save the same reference to variable and change its contents but immutable you can not change contents but you will declare new reference contains the new and the old value of the variable

Ex Immutable -> String

String x = "value0ne";// adresse one x += "valueTwo"; //an other adresse {adresse two} adresse on the heap memory change.

Mutable -> StringBuffer - StringBuilder StringBuilder sb = new StringBuilder(); sb.append("valueOne"); // adresse One sb.append("valueTwo"); // adresse One

sb still in the same adresse i hope this comment helps

Maven compile: package does not exist

You do not include a <scope> tag in your dependency. If you add it, your dependency becomes something like:

<dependency>
     <groupId>org.openrdf.sesame</groupId>
     <artifactId>sesame-runtime</artifactId>
     <version>2.7.2</version>
     <scope> ... </scope>
</dependency>

The "scope" tag tells maven at which stage of the build your dependency is needed. Examples for the values to put inside are "test", "provided" or "runtime" (omit the quotes in your pom). I do not know your dependency so I cannot tell you what value to choose. Please consult the Maven documentation and the documentation of your dependency.

delete image from folder PHP

You can try this code. This is Simple PHP Image Deleting code from the server.

<form method="post">
<input type="text" name="photoname"> // You can type your image name here...
<input type="submit" name="submit" value="Delete">
</form>

<?php
if (isset($_POST['submit'])) 
{
$photoname = $_POST['photoname'];
if (!unlink($photoname))
  {
  echo ("Error deleting $photoname");
  }
else
  {
  echo ("Deleted $photoname");
  }
}
?>

Why do you need to put #!/bin/bash at the beginning of a script file?

To be more precise the shebang #!, when it is the first two bytes of an executable (x mode) file, is interpreted by the execve(2) system call (which execute programs). But POSIX specification for execve don't mention the shebang.

It must be followed by a file path of an interpreter executable (which BTW could even be relative, but most often is absolute).

A nice trick (or perhaps not so nice one) to find an interpreter (e.g. python) in the user's $PATH is to use the env program (always at /usr/bin/env on all Linux) like e.g.

 #!/usr/bin/env python

Any ELF executable can be an interpreter. You could even use #!/bin/cat or #!/bin/true if you wanted to! (but that would be often useless)

Difference between getAttribute() and getParameter()

Basic difference between getAttribute() and getParameter() is the return type.

java.lang.Object getAttribute(java.lang.String name)
java.lang.String getParameter(java.lang.String name)

How to enable CORS on Firefox?

Very often you have no option to setup the sending server so what I did I changed the XMLHttpRequest.open call in my javascript to a local get-file.php file where I have the following code in it:

_x000D_
_x000D_
<?php_x000D_
  $file = file($_GET['url']);_x000D_
  echo implode('', $file);_x000D_
?>
_x000D_
_x000D_
_x000D_

javascript is doing this:

_x000D_
_x000D_
var xhttp = new XMLHttpRequest();_x000D_
xhttp.onreadystatechange = function() {_x000D_
  if (this.readyState == 4 && this.status == 200) {_x000D_
    // File content is now in the this.responseText_x000D_
  }_x000D_
};_x000D_
xhttp.open("GET", "get-file.php?url=http://site/file", true);_x000D_
xhttp.send();
_x000D_
_x000D_
_x000D_

In my case this solved the restriction/situation just perfectly. No need to hack Firefox or servers. Just load your javascript/html file with that small php file into the server and you're done.

Log exception with traceback

Uncaught exception messages go to STDERR, so instead of implementing your logging in Python itself you could send STDERR to a file using whatever shell you're using to run your Python script. In a Bash script, you can do this with output redirection, as described in the BASH guide.

Examples

Append errors to file, other output to the terminal:

./test.py 2>> mylog.log

Overwrite file with interleaved STDOUT and STDERR output:

./test.py &> mylog.log

Convert a string to a datetime

Try to see if the following code helps you:

Dim iDate As String = "05/05/2005"
Dim oDate As DateTime = Convert.ToDateTime(iDate)

Why is using a wild card with a Java import statement bad?

The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need java.awt.Event, and are also interfacing with the company's calendaring system, which has com.mycompany.calendar.Event. If you import both using the wildcard method, one of these three things happens:

  1. You have an outright naming conflict between java.awt.Event and com.mycompany.calendar.Event, and so you can't even compile.
  2. You actually manage only to import one (only one of your two imports does .*), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.
  3. When you compile your code there is no com.mycompany.calendar.Event, but when they later add one your previously valid code suddenly stops compiling.

The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code that much easier. If you're just doing a quick one-off thing, there's nothing explicitly wrong, but future maintainers will thank you for your clarity otherwise.

How can I list all of the files in a directory with Perl?

readdir() does that.

Check http://perldoc.perl.org/functions/readdir.html

opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!";
@dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR);
closedir DIR;

Why does MSBuild look in C:\ for Microsoft.Cpp.Default.props instead of c:\Program Files (x86)\MSBuild? ( error MSB4019)

EDIT: This applies to older versions of Visual Studio / MSBuild (specifically MSVC2015?). With more modern versions, MSBuild is included in Visual Studio Build Tools 2019, and compilers are located in different places and detected in different ways.

This is due to a mismatch of installed MSBuild toolsets and registry settings. It can happen if you did one or more of the following:

  • Install multiple Visual Studio versions in the wrong order
  • Uninstall one or more versions of Visual Studio
  • Manually make registry changes or modifications to the Visual Studio installation

The only safe and reliable solution I know of is to reinstall your OS. If your project needs multiple versions of Visual Studio to build, install the oldest version first. Then fix your code so you can use one single tool to build it, or you or your colleagues will be in the same mess again soon.

If this is not an option for you, first read https://stackoverflow.com/a/41786593/2279059 for a better understanding of the problem and what the various "solutions" actually do. Then, depending on your Visual Studio version and setup, one of the other answers or variations of them may eventually help.

Some more hints:

Can Windows Containers be hosted on linux?

Solution 1 - Using VirtualBox

As Muhammad Sahputra suggested in this post, it is possible to run Windows OS inside VirtualBox (using VBoxHeadless - without graphical interface) inside Docker container.

Also, a NAT setup inside the VM network configurations can do a port forwarding which gives you the ability to pass-through any traffic that comes to and from the Docker container. This eventually, in a wide perspective, allows you to run any Windows-based service on top of Linux machine.

Maybe this is not a typical use-case of a Docker container, but it definitely an interesting approach to the problem.


Solution 2 - Using Wine

For simple applications and maybe more complicated, you can try to use wine inside a docker container.

This docker hub page may help you to achieve your goal.


I hope that Docker will release a native solution soon, like they did with docker-machine on Windows several years ago.

How can I delete all of my Git stashes at once?

this command enables you to look all stashed changes.

git stash list

Here is the following command use it to clear all of your stashed Changes

git stash clear

Now if you want to delete one of the stashed changes from stash area

git stash drop stash@{index}   // here index will be shown after getting stash list.

Note : git stash list enables you to get index from stash area of git.

Get specific ArrayList item

Try:

ArrayListname.get(index);

Where index is the position in the index and ArrayListname is the name of the Arraylist as in your case is mainList.

Using column alias in WHERE clause of MySQL query produces an error

You can use SUBSTRING(locations.raw,-6,4) for where conditon

SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,
SUBSTRING(`locations`.`raw`,-6,4) AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
WHERE SUBSTRING(`locations`.`raw`,-6,4) NOT IN #this is where the fake col is being used
(
SELECT `postcode` FROM `postcodes` WHERE `region` IN
(
 'australia'
)
)

How to remove MySQL root password

You need to set the password for root@localhost to be blank. There are two ways:

  1. The MySQL SET PASSWORD command:

    SET PASSWORD FOR root@localhost=PASSWORD('');
    
  2. Using the command-line mysqladmin tool:

    mysqladmin -u root -pType_in_your_current_password_here password ''
    

How do you push a Git tag to a branch using a refspec?

I create the tag like this and then I push it to GitHub:

git tag -a v1.1 -m "Version 1.1 is waiting for review"
git push --tags

Counting objects: 1, done.
Writing objects: 100% (1/1), 180 bytes, done.
Total 1 (delta 0), reused 0 (delta 0)
To [email protected]:neoneye/triangle_draw.git
 * [new tag]         v1.1 -> v1.1

How to set variable from a SQL query?

Use TOP 1 if the query returns multiple rows.

SELECT TOP 1 @ModelID = m.modelid 
  FROM MODELS m
 WHERE m.areaid = 'South Coast'

How to initialize weights in PyTorch?

Here is the better way, just pass your whole model

import torch.nn as nn
def initialize_weights(model):
    # Initializes weights according to the DCGAN paper
    for m in model.modules():
        if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d, nn.BatchNorm2d)):
            nn.init.normal_(m.weight.data, 0.0, 0.02)
        # if you also want for linear layers ,add one more elif condition 

How to disable horizontal scrolling of UIScrollView?

I struggled with this for some time trying unsuccessfully the various suggestions in this and other threads.

However, in another thread (not sure where) someone suggested that using a negative constraint on the UIScrollView worked for him.

So I tried various combinations of constraints with inconsistent results. What eventually worked for me was to add leading and trailing constraints of -32 to the scrollview and add an (invisible) textview with a width of 320 (and centered).

How can I replace every occurrence of a String in a file with PowerShell?

This worked for me using the current working directory in PowerShell. You need to use the FullName property, or it won't work in PowerShell version 5. I needed to change the target .NET framework version in ALL my CSPROJ files.

gci -Recurse -Filter *.csproj |
% { (get-content "$($_.FullName)")
.Replace('<TargetFramework>net47</TargetFramework>', '<TargetFramework>net462</TargetFramework>') |
 Set-Content "$($_.FullName)"}

Remove all non-"word characters" from a String in Java, leaving accented characters?

Use [^\p{L}\p{Nd}]+ - this matches all (Unicode) characters that are neither letters nor (decimal) digits.

In Java:

String resultString = subjectString.replaceAll("[^\\p{L}\\p{Nd}]+", "");

Edit:

I changed \p{N} to \p{Nd} because the former also matches some number symbols like ¼; the latter doesn't. See it on regex101.com.

Submit Button Image

It's very important for accessibility reasons that you always specify value of the submit even if you are hiding this text, or if you use <input type="image" .../> to always specify alt="" attribute for this input field.

Blind people don't know what button will do if it doesn't contain meaningful alt="" or value="".

how to format date in Component of angular 5

Refer to the below link,

https://angular.io/api/common/DatePipe

**Code Sample**

@Component({
 selector: 'date-pipe',
 template: `<div>
   <p>Today is {{today | date}}</p>
   <p>Or if you prefer, {{today | date:'fullDate'}}</p>
   <p>The time is {{today | date:'h:mm a z'}}</p>
 </div>`
})
// Get the current date and time as a date-time value.
export class DatePipeComponent {
  today: number = Date.now();
}

{{today | date:'MM/dd/yyyy'}} output: 17/09/2019

or

{{today | date:'shortDate'}} output: 17/9/19

ASP.NET Web Site or ASP.NET Web Application?

There is an article in MSDN which describes the differences:

Comparing Web Site Projects and Web Application Projects

BTW: there are some similar questions about that topic, e.g:

XML Schema (XSD) validation tool?

I tend to use xsd from Microsoft to help generate the xsd from a .NET file. I also parse out sections of the xml using xmlstarlet. The final free tool that would be of use to you is altovaxml, which is available at this URL: http://www.altova.com/download_components.html .

This allows me to scan all the xml files picking up which xsd to use by parsing the xml.

# Function:
#    verifyschemas - Will validate all xml files in a configuration directory against the schemas in the passed in directory
# Parameters:
#    The directory where the schema *.xsd files are located.  Must be using dos pathing like: VerifySchemas "c:\\XMLSchemas\\"
# Requirements:
#    Must be in the directory where the configuration files are located
#
verifyschemas()
{
    for FILENAME in $(find . -name '*.xml' -print0 | xargs -0)
    do
        local SchemaFile=$1$(getconfignamefromxml $FILENAME).xsd
        altovaxml /validate $FILENAME /schema $SchemaFile > ~/temp.txt 2> /dev/null
        if [ $? -ne 0 ]; then
            printf "Failed to verify: "
            cat ~/temp.txt | tail -1 | tr -d '\r'
            printf "    - $FILENAME with $SchemaFile\n"
        fi
    done
}

To generate the xml I use: xsd DOTNET.dll /type:CFGCLASS & rename schema0.xsd CFGCLASS.xsd

To get the xsd name I use: xmlstarlet sel -t -m /XXX/* -v local-name() $1 | sed 's/ $//'

This allows me to pickup the correct XSD using an element tag within the xml file.

The net result is that I can call a bash function to scan all the XML files and verify them. Even if they are in multiple subdirectories.

Android Studio: /dev/kvm device permission denied

Here is a simple solution

open the terminal and run the following commands

sudo groupadd -r kvm

sudo gedit /lib/udev/rules.d/60-qemu-system-common.rules

Add the following line to the opened file and save it

KERNEL=="kvm", GROUP="kvm", MODE="0660"

Finally run:

sudo usermod -a -G kvm <your_username>

Reboot your PC and Done!

Selenium C# WebDriver: Wait until element is present

Since I'm separating page elements definitions and page test scenarios using an already-found IWebElement for visibility, it could be done like this:

public static void WaitForElementToBecomeVisibleWithinTimeout(IWebDriver driver, IWebElement element, int timeout)
{
    new WebDriverWait(driver, TimeSpan.FromSeconds(timeout)).Until(ElementIsVisible(element));
}

private static Func<IWebDriver, bool> ElementIsVisible(IWebElement element)
{
    return driver => {
        try
        {
            return element.Displayed;
        }
        catch(Exception)
        {
            // If element is null, stale or if it cannot be located
            return false;
        }
    };
}

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be

lista.sort()

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..


The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:

None[0]

The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

Group a list of objects by an attribute

Using Java 8

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class Student {

    String stud_id;
    String stud_name;
    String stud_location;

    public String getStud_id() {
        return stud_id;
    }

    public String getStud_name() {
        return stud_name;
    }

    public String getStud_location() {
        return stud_location;
    }



    Student(String sid, String sname, String slocation) {

        this.stud_id = sid;
        this.stud_name = sname;
        this.stud_location = slocation;

    }
}

class Temp
{
    public static void main(String args[])
    {

        Stream<Student> studs = 
        Stream.of(new Student("1726", "John", "New York"),
                new Student("4321", "Max", "California"),
                new Student("2234", "Max", "Los Angeles"),
                new Student("7765", "Sam", "California"));
        Map<String, Map<Object, List<Student>>> map= studs.collect(Collectors.groupingBy(Student::getStud_name,Collectors.groupingBy(Student::getStud_location)));
                System.out.println(map);//print by name and then location
    }

}

The result will be:

{
    Max={
        Los Angeles=[Student@214c265e], 
        California=[Student@448139f0]
    }, 
    John={
        New York=[Student@7cca494b]
    }, 
    Sam={
        California=[Student@7ba4f24f]
    }
}

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

This one disables all bogus verbs and only allows GET and POST

<system.webServer>
  <security>
    <requestFiltering>
      <verbs allowUnlisted="false">
    <clear/>
    <add verb="GET" allowed="true"/>
    <add verb="POST" allowed="true"/>
      </verbs>
    </requestFiltering>
  </security>
</system.webServer>

"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" error

The template it is referring to is the Html helper DisplayFor.

DisplayFor expects to be given an expression that conforms to the rules as specified in the error message.

You are trying to pass in a method chain to be executed and it doesn't like it.

This is a perfect example of where the MVVM (Model-View-ViewModel) pattern comes in handy.

You could wrap up your Trainer model class in another class called TrainerViewModel that could work something like this:

class TrainerViewModel
{
    private Trainer _trainer;

    public string ShortDescription
    {
        get
        {
            return _trainer.Description.ToString().Substring(0, 100);
        }
    }

    public TrainerViewModel(Trainer trainer)
    {
        _trainer = trainer;
    }
}

You would modify your view model class to contain all the properties needed to display that data in the view, hence the name ViewModel.

Then you would modify your controller to return a TrainerViewModel object rather than a Trainer object and change your model type declaration in your view file to TrainerViewModel too.

Find all elements with a certain attribute value in jquery

Use string concatenation. Try this:

$('div[imageId="'+imageN +'"]').each(function() {
    $(this);   
});

How to update the value stored in Dictionary in C#?

It's possible by accessing the key as index

for example:

Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary["test"] = 1;
dictionary["test"] += 1;
Console.WriteLine (dictionary["test"]); // will print 2

NPM: npm-cli.js not found when running npm

just run this command :

npm i npm@latest -g

Authenticating in PHP using LDAP through Active Directory

PHP has libraries: http://ca.php.net/ldap

PEAR also has a number of packages: http://pear.php.net/search.php?q=ldap&in=packages&x=0&y=0

I haven't used either, but I was going to at one point and they seemed like they should work.

Is there an auto increment in sqlite?

One should not specify AUTOINCREMENT keyword near PRIMARY KEY. Example of creating autoincrement primary key and inserting:

$ sqlite3 ex1

CREATE TABLE IF NOT EXISTS room(room_id INTEGER PRIMARY KEY, name VARCHAR(25) NOT NULL, home_id VARCHAR(25) NOT NULL);

INSERT INTO room(name, home_id) VALUES ('test', 'home id test');

INSERT INTO room(name, home_id) VALUES ('test 2', 'home id test 2');

SELECT * FROM room;

will give:

1|test|home id test
2|test 2|home id test 2

How to extract public key using OpenSSL?

If your looking how to copy an Amazon AWS .pem keypair into a different region do the following:

openssl rsa -in .ssh/amazon-aws.pem -pubout > .ssh/amazon-aws.pub

Then

aws ec2 import-key-pair --key-name amazon-aws --public-key-material '$(cat .ssh/amazon-aws.pub)' --region us-west-2

Best way to check function arguments?

def someFunc(a, b, c):
    params = locals()
    for _item in params:
        print type(params[_item]), _item, params[_item]

Demo:

>> someFunc(1, 'asd', 1.0)
>> <type 'int'> a 1
>> <type 'float'> c 1.0
>> <type 'str'> b asd

more about locals()

Dynamically changing font size of UILabel

minimumFontSize has been deprecated with iOS 6. You can use minimumScaleFactor.

yourLabel.adjustsFontSizeToFitWidth=YES;
yourLabel.minimumScaleFactor=0.5;

This will take care of your font size according width of label and text.

Get driving directions using Google Maps API v2

This is what I am using,

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
Uri.parse("http://maps.google.com/maps?saddr="+latitude_cur+","+longitude_cur+"&daddr="+latitude+","+longitude));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_LAUNCHER );     
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);

Font awesome is not showing icon

In my case: You need to copy the whole font-awesome folder to your project css folder and not just the font-awesome.min.css file.

JavaScript onclick redirect

Change the onclick from

onclick="javascript:SubmitFrm()"

to

onclick="SubmitFrm()"

Changing case in Vim

See the following methods:

 ~    : Changes the case of current character

 guu  : Change current line from upper to lower.

 gUU  : Change current LINE from lower to upper.

 guw  : Change to end of current WORD from upper to lower.

 guaw : Change all of current WORD to lower.

 gUw  : Change to end of current WORD from lower to upper.

 gUaw : Change all of current WORD to upper.

 g~~  : Invert case to entire line

 g~w  : Invert case to current WORD

 guG : Change to lowercase until the end of document.

Check for false

If you want to check for false and alert if not, then no there isn't.

If you use if(val), then anything that evaluates to 'truthy', like a non-empty string, will also pass. So it depends on how stringent your criterion is. Using === and !== is generally considered good practice, to avoid accidentally matching truthy or falsy conditions via JavaScript's implicit boolean tests.

Android transparent status bar and actionbar

Just add these lines of code to your activity/fragment java file:

getWindow().setFlags(
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);

How to cancel/abort jQuery AJAX request?

Create a function to call your API. Within this function we define request callApiRequest = $.get(... - even though this is a definition of a variable, the request is called immediately, but now we have the request defined as a variable. Before the request is called, we check if our variable is defined typeof(callApiRequest) != 'undefined' and also if it is pending suggestCategoryRequest.state() == 'pending' - if both are true, we .abort() the request which will prevent the success callback from running.

// We need to wrap the call in a function
callApi = function () {

    //check if request is defined, and status pending
    if (typeof(callApiRequest) != 'undefined'
        && suggestCategoryRequest.state() == 'pending') {

        //abort request
        callApiRequest.abort()

    }

    //define and make request
    callApiRequest = $.get("https://example.com", function (data) {

        data = JSON.parse(data); //optional (for JSON data format)
        //success callback

    });
}

Your server/API might not support aborting the request (what if API executed some code already?), but the javascript callback will not fire. This is useful, when for example you are providing input suggestions to a user, such as hashtags input.

You can further extend this function by adding definition of error callback - what should happen if request was aborted.

Common use-case for this snippet would be a text input that fires on keypress event. You can use a timeout, to prevent sending (some of) requests that you will have to cancel .abort().

How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?

i found another solution:

  1. start session in TEAM
  2. go to SOURCE CONTROL and select WORKSPACE (mark in red)
  3. then Add new Workspace... why?
  4. because you dont work in the same workspace whey you change your account in TFS (i dont know why)
  5. and ready to MAP your project again.

Its 100% guaranteed to work.

Wildcards in a Windows hosts file

You could talk your network administrator into setting up a domain for you (say 'evilpuppetmaster.hell') and having the wildcard there so that everything (*.evilpuppetmaster.hell') resolves to your IP

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

keycode 13 is for which key

_x000D_
_x000D_
function myFunction(event) {
  var x = event.charCode;
  document.getElementById("demo").innerHTML = "The Unicode value is: " + x;
}
_x000D_
<p>Keycode 13 is: </p> 
<button>Enter</button>
<p>Press a key on the keyboard in the input field to get the Unicode character code of the pressed key.</p>
<b>You can test in below</b>

<input type="text" size="40" onkeypress="myFunction(event)">

<p id="demo"></p>

<p><strong>Note:</strong> The charCode property is not supported in IE8 and earlier versions.</p>
_x000D_
_x000D_
_x000D_

Check if a input box is empty

The above answer didn't work with Angular 6. So following is how I resolved it. Lets say this is how I defined my input box -

_x000D_
_x000D_
<input type="number" id="myTextBox" name="myTextBox"_x000D_
 [(ngModel)]="response.myTextBox"_x000D_
            #myTextBox="ngModel">
_x000D_
_x000D_
_x000D_

To check if the field is empty or not this should be the script.

_x000D_
_x000D_
<div *ngIf="!myTextBox.value" style="color:red;">_x000D_
 Your field is empty_x000D_
</div>
_x000D_
_x000D_
_x000D_

Do note the subtle difference between the above answer and this answer. I have added an additional attribute .value after my input name myTextBox. I don't know if the above answer worked for above version of Angular, but for Angular 6 this is how it should be done.

Some more explanation on why this check works; when there is no value present in the input box the default value of myTextBox.value will be undefined. As soon as you enter some text, your text becomes the new value of myTextBox.value.

When your check is !myTextBox.value it is checking that the value is undefined or not, it is equivalent to myTextBox.value == undefined.

Show data on mouseover of circle

A really good way to make a tooltip is described here: Simple D3 tooltip example

You have to append a div

var tooltip = d3.select("body")
    .append("div")
    .style("position", "absolute")
    .style("z-index", "10")
    .style("visibility", "hidden")
    .text("a simple tooltip");

Then you can just toggle it using

.on("mouseover", function(){return tooltip.style("visibility", "visible");})
.on("mousemove", function(){return tooltip.style("top",
    (d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");});

d3.event.pageX / d3.event.pageY is the current mouse coordinate.

If you want to change the text you can use tooltip.text("my tooltip text");

Working Example

MySQl Error #1064

In my case I was having the same error and later I come to know that the 'condition' is mysql reserved keyword and I used that as field name.

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

You could also use a URI template. If you structured your request into a restful URL Spring could parse the provided value from the url.

HTML

<li>
    <a id="byParameter" 
       class="textLink" href="<c:url value="/mapping/parameter/bar />">By path, method,and
           presence of parameter</a>
</li>

Controller

@RequestMapping(value="/mapping/parameter/{foo}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String foo) {
    //Perform logic with foo
    return "Mapped by path + method + presence of query parameter! (MappingController)";
}

Spring URI Template Documentation

How to format numbers by prepending 0 to single-digit numbers?

    function colorOf(r,g,b){
  var f = function (x) {
    return (x<16 ? '0' : '') + x.toString(16) 
  };

  return "#" +  f(r) + f(g) + f(b);
}

Reset the database (purge all), then seed a database

If you don't feel like dropping and recreating the whole shebang just to reload your data, you could use MyModel.destroy_all (or delete_all) in the seed.db file to clean out a table before your MyModel.create!(...) statements load the data. Then, you can redo the db:seed operation over and over. (Obviously, this only affects the tables you've loaded data into, not the rest of them.)

There's a "dirty hack" at https://stackoverflow.com/a/14957893/4553442 to add a "de-seeding" operation similar to migrating up and down...

Reading Data From Database and storing in Array List object

If your customer class has static variables remove them so your class should look something like this.

public class customer {

     private int id;
     private String name;
     private String DOB;

    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public String getDOB() {
        return DOB;
    }
     public void setId(int id) {
        this.id = id;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setDOB(String dOB) {
        this.DOB = dOB;
    }

instead of something like

public class customer {

     private static int id;
     private static String name;
     private static String DOB;

    public static int getId() {
        return id;
    }
    public static String getName() {
        return name;
    }
    public static String getDOB() {
        return DOB;
    }
     public static void setId(int id) {
        custumer.id = id;
    }
    public  static void setName(String name) {
        customer.name = name;
    }
    public static void setDOB(String dOB) {
        customer.DOB = dOB;
    }

Draw Circle using css alone

  • Create a div with a set height and width (so, for a circle, use the same height and width), forming a square
  • add a border-radius of 50% which will make it circular in shape. (note: no prefix has been required for a long time)
  • You can then play around with background-color / gradients / (even pseudo elements) to create something like this:

_x000D_
_x000D_
.red {_x000D_
  background-color: red;_x000D_
}_x000D_
.green {_x000D_
  background-color: green;_x000D_
}_x000D_
.blue {_x000D_
  background-color: blue;_x000D_
}_x000D_
.yellow {_x000D_
  background-color: yellow;_x000D_
}_x000D_
.sphere {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  border-radius: 50%;_x000D_
  text-align: center;_x000D_
  vertical-align: middle;_x000D_
  font-size: 500%;_x000D_
  position: relative;_x000D_
  box-shadow: inset -10px -10px 100px #000, 10px 10px 20px black, inset 0px 0px 10px black;_x000D_
  display: inline-block;_x000D_
  margin: 5%;_x000D_
}_x000D_
.sphere::after {_x000D_
  background-color: rgba(255, 255, 255, 0.3);_x000D_
  content: '';_x000D_
  height: 45%;_x000D_
  width: 12%;_x000D_
  position: absolute;_x000D_
  top: 4%;_x000D_
  left: 15%;_x000D_
  border-radius: 50%;_x000D_
  transform: rotate(40deg);_x000D_
}
_x000D_
<div class="sphere red"></div>_x000D_
<div class="sphere green"></div>_x000D_
<div class="sphere blue"></div>_x000D_
<div class="sphere yellow"></div>_x000D_
<div class="sphere"></div>
_x000D_
_x000D_
_x000D_

Replace all occurrences of a string in a data frame

Here is a dplyr solution

library(dplyr)
library(stringr)

Censor_consistently <-  function(x){
  str_replace(x, '^\\s*([<>])\\s*(\\d+)', '\\1\\2')
}


test_df <- tibble(x = c('0.001', '<0.002', ' < 0.003', ' >  100'),  y = 4:1)

mutate_all(test_df, funs(Censor_consistently))

# A tibble: 4 × 2
x     y
<chr> <chr>
1  0.001     4
2 <0.002     3
3 <0.003     2
4   >100     1

How can I compare two ordered lists in python?

Just use the classic == operator:

>>> [0,1,2] == [0,1,2]
True
>>> [0,1,2] == [0,2,1]
False
>>> [0,1] == [0,1,2]
False

Lists are equal if elements at the same index are equal. Ordering is taken into account then.

How to center the content inside a linear layout?

android:gravity can be used on a Layout to align its children.

android:layout_gravity can be used on any view to align itself in its parent.

NOTE: If self or children is not centering as expected, check if width/height is match_parent and change to something else

C++ template typedef

C++11 added alias declarations, which are generalization of typedef, allowing templates:

template <size_t N>
using Vector = Matrix<N, 1>;

The type Vector<3> is equivalent to Matrix<3, 1>.


In C++03, the closest approximation was:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};

Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.

Keyboard shortcuts are not active in Visual Studio with Resharper installed

Alternatively - make sure that Resharper is enabled. My visual studio didn't update my Resharper license information, so when opening the resharper menu (after trying to figure out why my shortcuts stopped working!), the was a menu item "Why is Resharper disabled?" Clicking on the menu item opens up a dialog, which then automatically resolved the license. The next question for Jetbrains is why do I have to open the dialog for the thing to automatically renew??

Specifying trust store information in spring boot application.properties

Although I am commenting late. But I have used this method to do the job. Here when I am running my spring application I am providing the application yaml file via -Dspring.config.location=file:/location-to-file/config-server-vault-application.yml which contains all of my properties

config-server-vault-application.yml
***********************************
server:
  port: 8888
  ssl:
    trust-store: /trust-store/config-server-trust-store.jks
    trust-store-password: config-server
    trust-store-type: pkcs12

************************************
Java Code
************************************
@SpringBootApplication
public class ConfigServerApplication {

 public static void main(String[] args) throws IOException {
    setUpTrustStoreForApplication();
    SpringApplication.run(ConfigServerApplication.class, args);
 }

 private static void setUpTrustStoreForApplication() throws IOException {
    YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
    List<PropertySource<?>> applicationYamlPropertySource = loader.load(
            "config-application-properties", new UrlResource(System.getProperty("spring.config.location")));
    Map<String, Object> source = ((MapPropertySource) applicationYamlPropertySource.get(0)).getSource();
    System.setProperty("javax.net.ssl.trustStore", source.get("server.ssl.trust-store").toString());
    System.setProperty("javax.net.ssl.trustStorePassword", source.get("server.ssl.trust-store-password").toString());
  }
}

How to output messages to the Eclipse console when developing for Android

Rather than trying to output to the console, Log will output to LogCat which you can find in Eclipse by going to: Window->Show View->Other…->Android->LogCat

Have a look at the reference for Log.

The benefits of using LogCat are that you can print different colours depending on your log type, e.g.: Log.d prints blue, Log.e prints orange. Also you can filter by log tag, log message, process id and/or by application name. This is really useful when you just want to see your app's logs and keep the other system stuff separate.

Get column index from column name in python pandas

Sure, you can use .get_loc():

In [45]: df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})

In [46]: df.columns
Out[46]: Index([apple, orange, pear], dtype=object)

In [47]: df.columns.get_loc("pear")
Out[47]: 2

although to be honest I don't often need this myself. Usually access by name does what I want it to (df["pear"], df[["apple", "orange"]], or maybe df.columns.isin(["orange", "pear"])), although I can definitely see cases where you'd want the index number.

How to count lines of Java code using IntelliJ IDEA?

Although it is not an IntelliJ option, you could use a simple Bash command (if your operating system is Linux/Unix). Go to your source directory and type:

find . -type f -name '*.java' | xargs cat | wc -l

Adding elements to a collection during iteration

There are two issues here:

The first issue is, adding to an Collection after an Iterator is returned. As mentioned, there is no defined behavior when the underlying Collection is modified, as noted in the documentation for Iterator.remove:

... The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

The second issue is, even if an Iterator could be obtained, and then return to the same element the Iterator was at, there is no guarantee about the order of the iteratation, as noted in the Collection.iterator method documentation:

... There are no guarantees concerning the order in which the elements are returned (unless this collection is an instance of some class that provides a guarantee).

For example, let's say we have the list [1, 2, 3, 4].

Let's say 5 was added when the Iterator was at 3, and somehow, we get an Iterator that can resume the iteration from 4. However, there is no guarentee that 5 will come after 4. The iteration order may be [5, 1, 2, 3, 4] -- then the iterator will still miss the element 5.

As there is no guarantee to the behavior, one cannot assume that things will happen in a certain way.

One alternative could be to have a separate Collection to which the newly created elements can be added to, and then iterating over those elements:

Collection<String> list = Arrays.asList(new String[]{"Hello", "World!"});
Collection<String> additionalList = new ArrayList<String>();

for (String s : list) {
    // Found a need to add a new element to iterate over,
    // so add it to another list that will be iterated later:
    additionalList.add(s);
}

for (String s : additionalList) {
    // Iterate over the elements that needs to be iterated over:
    System.out.println(s);
}

Edit

Elaborating on Avi's answer, it is possible to queue up the elements that we want to iterate over into a queue, and remove the elements while the queue has elements. This will allow the "iteration" over the new elements in addition to the original elements.

Let's look at how it would work.

Conceptually, if we have the following elements in the queue:

[1, 2, 3, 4]

And, when we remove 1, we decide to add 42, the queue will be as the following:

[2, 3, 4, 42]

As the queue is a FIFO (first-in, first-out) data structure, this ordering is typical. (As noted in the documentation for the Queue interface, this is not a necessity of a Queue. Take the case of PriorityQueue which orders the elements by their natural ordering, so that's not FIFO.)

The following is an example using a LinkedList (which is a Queue) in order to go through all the elements along with additional elements added during the dequeing. Similar to the example above, the element 42 is added when the element 2 is removed:

Queue<Integer> queue = new LinkedList<Integer>();
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);

while (!queue.isEmpty()) {
    Integer i = queue.remove();
    if (i == 2)
        queue.add(42);

    System.out.println(i);
}

The result is the following:

1
2
3
4
42

As hoped, the element 42 which was added when we hit 2 appeared.

htons() function in socket programing

It has to do with the order in which bytes are stored in memory. The decimal number 5001 is 0x1389 in hexadecimal, so the bytes involved are 0x13 and 0x89. Many devices store numbers in little-endian format, meaning that the least significant byte comes first. So in this particular example it means that in memory the number 5001 will be stored as

0x89 0x13

The htons() function makes sure that numbers are stored in memory in network byte order, which is with the most significant byte first. It will therefore swap the bytes making up the number so that in memory the bytes will be stored in the order

0x13 0x89

On a little-endian machine, the number with the swapped bytes is 0x8913 in hexadecimal, which is 35091 in decimal notation. Note that if you were working on a big-endian machine, the htons() function would not need to do any swapping since the number would already be stored in the right way in memory.

The underlying reason for all this swapping has to do with the network protocols in use, which require the transmitted packets to use network byte order.

Python: Passing variables between functions

Your return is useless if you don't assign it

list=defineAList()

Saving a high resolution image in R

You can do the following. Add your ggplot code after the first line of code and end with dev.off().

tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()

res=300 specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.

Change width and height in the code above depending on the desired output.

Note that this also works for other R plots including plot, image, and pheatmap.

Other file formats

In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.

How to read a text-file resource into Java unit test?

With the use of Google Guava:

import com.google.common.base.Charsets;
import com.google.common.io.Resources;

public String readResource(final String fileName, Charset charset) throws Exception {
        try {
            return Resources.toString(Resources.getResource(fileName), charset);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
}

Example:

String fixture = this.readResource("filename.txt", Charsets.UTF_8)

What does "collect2: error: ld returned 1 exit status" mean?

The ld returned 1 exit status error is the consequence of previous errors. In your example there is an earlier error - undefined reference to 'clrscr' - and this is the real one. The exit status error just signals that the linking step in the build process encountered some errors. Normally exit status 0 means success, and exit status > 0 means errors.

When you build your program, multiple tools may be run as separate steps to create the final executable. In your case one of those tools is ld, which first reports the error it found (clrscr reference missing), and then it returns the exit status. Since the exit status is > 0, it means an error and is reported.

In many cases tools return as the exit status the number of errors they encountered. So if ld tool finds two errors, its exit status would be 2.

Volatile Vs Atomic

Volatile and Atomic are two different concepts. Volatile ensures, that a certain, expected (memory) state is true across different threads, while Atomics ensure that operation on variables are performed atomically.

Take the following example of two threads in Java:

Thread A:

value = 1;
done = true;

Thread B:

if (done)
  System.out.println(value);

Starting with value = 0 and done = false the rule of threading tells us, that it is undefined whether or not Thread B will print value. Furthermore value is undefined at that point as well! To explain this you need to know a bit about Java memory management (which can be complex), in short: Threads may create local copies of variables, and the JVM can reorder code to optimize it, therefore there is no guarantee that the above code is run in exactly that order. Setting done to true and then setting value to 1 could be a possible outcome of the JIT optimizations.

volatile only ensures, that at the moment of access of such a variable, the new value will be immediately visible to all other threads and the order of execution ensures, that the code is at the state you would expect it to be. So in case of the code above, defining done as volatile will ensure that whenever Thread B checks the variable, it is either false, or true, and if it is true, then value has been set to 1 as well.

As a side-effect of volatile, the value of such a variable is set thread-wide atomically (at a very minor cost of execution speed). This is however only important on 32-bit systems that i.E. use long (64-bit) variables (or similar), in most other cases setting/reading a variable is atomic anyways. But there is an important difference between an atomic access and an atomic operation. Volatile only ensures that the access is atomically, while Atomics ensure that the operation is atomically.

Take the following example:

i = i + 1;

No matter how you define i, a different Thread reading the value just when the above line is executed might get i, or i + 1, because the operation is not atomically. If the other thread sets i to a different value, in worst case i could be set back to whatever it was before by thread A, because it was just in the middle of calculating i + 1 based on the old value, and then set i again to that old value + 1. Explanation:

Assume i = 0
Thread A reads i, calculates i+1, which is 1
Thread B sets i to 1000 and returns
Thread A now sets i to the result of the operation, which is i = 1

Atomics like AtomicInteger ensure, that such operations happen atomically. So the above issue cannot happen, i would either be 1000 or 1001 once both threads are finished.

Shell script to copy files from one location to another location and rename add the current date to every file

You could use a script like the below. You would just need to change the date options to match the format you wanted.

#!/bin/bash

for i in `ls -l /directroy`
do
cp $i /newDirectory/$i.`date +%m%d%Y`
done

use of entityManager.createNativeQuery(query,foo.class)

Here is a DB2 Stored Procidure that receive a parameter

SQL

CREATE PROCEDURE getStateByName (IN StateName VARCHAR(128))
DYNAMIC RESULT SETS 1
P1: BEGIN
    -- Declare cursor
    DECLARE State_Cursor CURSOR WITH RETURN for
    -- #######################################################################
    -- # Replace the SQL statement with your statement.
    -- # Note: Be sure to end statements with the terminator character (usually ';')
    -- #
    -- # The example SQL statement SELECT NAME FROM SYSIBM.SYSTABLES
    -- # returns all names from SYSIBM.SYSTABLES.
    -- ######################################################################
    SELECT * FROM COUNTRY.STATE
    WHERE PROVINCE_NAME LIKE UPPER(stateName);
    -- Cursor left open for client application
    OPEN Province_Cursor;
END P1

Java

//Country is a db2 scheme

//Now here is a java Entity bean Method

public List<Province> getStateByName(String stateName) throws Exception {

    EntityManager em = this.em;
    List<State> states= null;
    try {
        Query query = em.createNativeQuery("call NGB.getStateByName(?1)", Province.class);
        query.setParameter(1, provinceName);
        states= (List<Province>) query.getResultList();
    } catch (Exception ex) {
        throw ex;
    }

    return states;
}

Freeze the top row for an html table only (Fixed Table Header Scrolling)

you can use two divs one for the headings and the other for the table. then use

#headings {
  position: fixed;
  top: 0px;
  width: 960px;
}

as @ptriek said this will only work for fixed width columns.

Mapping two integers to one, in a unique and deterministic way

What you suggest is impossible. You will always have collisions.

In order to map two objects to another single set, the mapped set must have a minimum size of the number of combinations expected:

Assuming a 32-bit integer, you have 2147483647 positive integers. Choosing two of these where order doesn't matter and with repetition yields 2305843008139952128 combinations. This does not fit nicely in the set of 32-bit integers.

You can, however fit this mapping in 61 bits. Using a 64-bit integer is probably easiest. Set the high word to the smaller integer and the low word to the larger one.

Query to select data between two dates with the format m/d/yyyy

select * from xxx where dates between '2012-10-10' and '2012-10-12'

I always use YYYY-MM-DD in my views and never had any issue. Plus, it is readable and non equivocal.
You should be aware that using BETWEEN might not return what you expect with a DATETIME field, since it would eliminate records dated '2012-10-12 08:00' for example.
I would rather use where dates >= '2012-10-10' and dates < '2012-10-13' (lower than next day)

How to synchronize a static variable among threads running different instances of a class in Java?

We can also use ReentrantLock to achieve the synchronization for static variables.

public class Test {

    private static int count = 0;
    private static final ReentrantLock reentrantLock = new ReentrantLock(); 
    public void foo() {  
        reentrantLock.lock();
        count = count + 1;
        reentrantLock.unlock();
    }  
}

Calling Javascript from a html form

Everything seems to be perfect in your code except the fact that handleClick() isn't working because this function lacks a parameter in its function call invocation(but the function definition within has an argument which makes a function mismatch to occur).

The following is a sample working code for calculating all semester's total marks and corresponding grade. It demonstrates the use of a JavaScript function(call) within a html file and also solves the problem you are facing.

<!DOCTYPE html>
<html>
<head>
    <title> Semester Results </title>
</head>
<body>
    <h1> Semester Marks </h1> <br> 
    <script type = "text/javascript">
        function checkMarks(total)
        {
            document.write("<h1> Final Result !!! </h1><br>");
            document.write("Total Marks = " + total + "<br><br>");
            var avg = total / 6.0;
            document.write("CGPA = " + (avg / 10.0).toFixed(2) + "<br><br>");
            if(avg >= 90)
                document.write("Grade = A");
            else if(avg >= 80)
                document.write("Grade = B");
            else if(avg >= 70)
                document.write("Grade = C");
            else if(avg >= 60)
                document.write("Grade = D");
            else if(avg >= 50)
                document.write("Grade = Pass");
            else
                document.write("Grade = Fail");
       }
    </script>
    <form name = "myform" action = "javascript:checkMarks(Number(s1.value) + Number(s2.value) + Number(s3.value) + Number(s4.value) + Number(s5.value) + Number(s6.value))"/>
        Semester 1:  <input type = "text" id = "s1"/> <br><br>
        Semester 2:  <input type = "text" id = "s2"/> <br><br>
        Semester 3:  <input type = "text" id = "s3"/> <br><br>
        Semester 4:  <input type = "text" id = "s4"/> <br><br>
        Semester 5:  <input type = "text" id = "s5"/> <br><br>
        Semester 6:  <input type = "text" id = "s6"/> <br><br><br>
        <input type = "submit" value = "Submit"/>
    </form>
</body>
</html>

jQuery Mobile how to check if button is disabled?

$('#StartButton:disabled') ..

Then check if it's undefined.

Concatenating bits in VHDL

The concatenation operator '&' is allowed on the right side of the signal assignment operator '<=', only

TypeError: 'module' object is not callable

Add to the main __init__.py in YourClassParentDir, e.g.:

from .YourClass import YourClass

Then, you will have an instance of your class ready when you import it into another script:

from YourClassParentDir import YourClass

'list' object has no attribute 'shape'

Use numpy.array to use shape attribute.

>>> import numpy as np
>>> X = np.array([
...     [[-9.035250067710876], [7.453250169754028], [33.34074878692627]],
...     [[-6.63700008392334], [5.132999956607819], [31.66075038909912]],
...     [[-5.1272499561309814], [8.251499891281128], [30.925999641418457]]
... ])
>>> X.shape
(3L, 3L, 1L)

NOTE X.shape returns 3-items tuple for the given array; [n, T] = X.shape raises ValueError.

Change NULL values in Datetime format to empty string

CASE and CAST should work:

CASE WHEN mycol IS NULL THEN '' ELSE CONVERT(varchar(50), mycol, 121) END

How to stop C# console applications from closing automatically?

You can just compile (start debugging) your work with Ctrl+F5.

Try it. I always do it and the console shows me my results open on it. No additional code is needed.

Where should I put the log4j.properties file?

Put log4j.properties in classpath. Here is the 2 cases that will help you to identify the proper location- 1. For web application the classpath is /WEB-INF/classes.

\WEB-INF      
    classes\
        log4j.properties
  1. To test from main / unit test the classpath is source directory

    \Project\
       src\
          log4j.properties
    

What is App.config in C#.NET? How to use it?

App.Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.

See this MSDN article on how to do that.

Java 8 lambda Void argument

You can create a sub-interface for that special case:

interface Command extends Action<Void, Void> {
  default Void execute(Void v) {
    execute();
    return null;
  }
  void execute();
}

It uses a default method to override the inherited parameterized method Void execute(Void), delegating the call to the simpler method void execute().

The result is that it's much simpler to use:

Command c = () -> System.out.println("Do nothing!");

How to stop PHP code execution?

You can use __halt_compiler function which will Halt the compiler execution

http://www.php.net/manual/en/function.halt-compiler.php

How to avoid .pyc files?

There actually IS a way to do it in Python 2.3+, but it's a bit esoteric. I don't know if you realize this, but you can do the following:

$ unzip -l /tmp/example.zip
 Archive:  /tmp/example.zip
   Length     Date   Time    Name
 --------    ----   ----    ----
     8467  11-26-02 22:30   jwzthreading.py
 --------                   -------
     8467                   1 file
$ ./python
Python 2.3 (#1, Aug 1 2003, 19:54:32) 
>>> import sys
>>> sys.path.insert(0, '/tmp/example.zip')  # Add .zip file to front of path
>>> import jwzthreading
>>> jwzthreading.__file__
'/tmp/example.zip/jwzthreading.py'

According to the zipimport library:

Any files may be present in the ZIP archive, but only files .py and .py[co] are available for import. ZIP import of dynamic modules (.pyd, .so) is disallowed. Note that if an archive only contains .py files, Python will not attempt to modify the archive by adding the corresponding .pyc or .pyo file, meaning that if a ZIP archive doesn't contain .pyc files, importing may be rather slow.

Thus, all you have to do is zip the files up, add the zipfile to your sys.path and then import them.

If you're building this for UNIX, you might also consider packaging your script using this recipe: unix zip executable, but note that you might have to tweak this if you plan on using stdin or reading anything from sys.args (it CAN be done without too much trouble).

In my experience performance doesn't suffer too much because of this, but you should think twice before importing any very large modules this way.

How Does Modulus Divison Work

modulus division is simply this : divide two numbers and return the remainder only

27 / 16 = 1 with 11 left over, therefore 27 % 16 = 11

ditto 43 / 16 = 2 with 11 left over so 43 % 16 = 11 too

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

Doing this would require to break the browser sandbox. Try to let your server do the lookup and request that from the client side via XmlHttp.

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

An attempt without using a play field.

  1. to win(your double)
  2. if not, not to lose(opponent's double)
  3. if not, do you already have a fork(have a double double)
  4. if not, if opponent has a fork
    1. search in blocking points for possible double and fork(ultimate win)
    2. if not search forks in blocking points(which gives the opponent the most losing possibilities )
    3. if not only blocking points(not to lose)
  5. if not search for double and fork(ultimate win)
  6. if not search only for forks which gives opponent the most losing possibilities
  7. if not search only for a double
  8. if not dead end, tie, random.
  9. if not(it means your first move)
    1. if it's the first move of the game;
      1. give the opponent the most losing possibility(the algorithm results in only corners which gives 7 losing point possibility to opponent)
      2. or for breaking boredom just random.
    2. if it's second move of the game;
      1. find only the not losing points(gives a little more options)
      2. or find the points in this list which has the best winning chance(it can be boring,cause it results in only all corners or adjacent corners or center)

Note: When you have double and forks, check if your double gives the opponent a double.if it gives, check if that your new mandatory point is included in your fork list.

Timeout a command in bash without unnecessary delay

You are probably looking for the timeout command in coreutils. Since it's a part of coreutils, it is technically a C solution, but it's still coreutils. info timeout for more details. Here's an example:

timeout 5 /path/to/slow/command with options

How to redirect to a 404 in Rails?

You could also use the render file:

render file: "#{Rails.root}/public/404.html", layout: false, status: 404

Where you can choose to use the layout or not.

Another option is to use the Exceptions to control it:

raise ActiveRecord::RecordNotFound, "Record not found."

How to delete a column from a table in MySQL

Use ALTER:

ALTER TABLE `tbl_Country` DROP COLUMN `column_name`;

What is the size of ActionBar in pixels?

With the new v7 support library (21.0.0) the name in R.dimen has changed to @dimen/abc_action_bar_default_height_material.

When upgrading from a previous version of the support lib you should therefore use that value as the actionbar's height

Returning JSON object as response in Spring Boot

use ResponseEntity<ResponseBean>

Here you can use ResponseBean or Any java bean as you like to return your api response and it is the best practice. I have used Enum for response. it will return status code and status message of API.

@GetMapping(path = "/login")
public ResponseEntity<ServiceStatus> restApiExample(HttpServletRequest request,
            HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        loginService.login(username, password, request);
        return new ResponseEntity<ServiceStatus>(ServiceStatus.LOGIN_SUCCESS,
                HttpStatus.ACCEPTED);
    }

for response ServiceStatus or(ResponseBody)

    public enum ServiceStatus {

    LOGIN_SUCCESS(0, "Login success"),

    private final int id;
    private final String message;

    //Enum constructor
    ServiceStatus(int id, String message) {
        this.id = id;
        this.message = message;
    }

    public int getId() {
        return id;
    }

    public String getMessage() {
        return message;
    }
}

Spring REST API should have below key in response

  1. Status Code
  2. Message

you will get final response below

{

   "StatusCode" : "0",

   "Message":"Login success"

}

you can use ResponseBody(java POJO, ENUM,etc..) as per your requirement.

File Upload in WebView

I found it necessary to define public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture), in Android 4.1. Then I followed Michel Olivier's solution.

How to disable scrolling temporarily?

Enabling the following CSS with JavaScript will help. I'm not as good as the others here but this worked for me.

body {
    position: fixed;
    overflow-y: scroll;
}

Adding a Button to a WPF DataGrid

Check this out:

XAML:

<DataGrid Name="DataGrid1">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Click="ChangeText">Show/Hide</Button>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Method:

private void ChangeText(object sender, RoutedEventArgs e)
{
    DemoModel model = (sender as Button).DataContext as DemoModel;
    model.DynamicText = (new Random().Next(0, 100).ToString());
}

Class:

class DemoModel : INotifyPropertyChanged
{
    protected String _text;
    public String Text
    {
        get { return _text; }
        set { _text = value; RaisePropertyChanged("Text"); }
    }

    protected String _dynamicText;
    public String DynamicText
    {
        get { return _dynamicText; }
        set { _dynamicText = value; RaisePropertyChanged("DynamicText"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler temp = PropertyChanged;
        if (temp != null)
        {
            temp(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Initialization Code:

ObservableCollection<DemoModel> models = new ObservableCollection<DemoModel>();
models.Add(new DemoModel() { Text = "Some Text #1." });
models.Add(new DemoModel() { Text = "Some Text #2." });
models.Add(new DemoModel() { Text = "Some Text #3." });
models.Add(new DemoModel() { Text = "Some Text #4." });
models.Add(new DemoModel() { Text = "Some Text #5." });
DataGrid1.ItemsSource = models;

Split string into list in jinja?

After coming back to my own question after 5 year and seeing so many people found this useful, a little update.

A string variable can be split into a list by using the split function (it can contain similar values, set is for the assignment) . I haven't found this function in the official documentation but it works similar to normal Python. The items can be called via an index, used in a loop or like Dave suggested if you know the values, it can set variables like a tuple.

{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}

or

{% set list1 = variable1.split(';') %}
{% for item in list1 %}
    <p>{{ item }}<p/>
{% endfor %} 

or

{% set item1, item2 = variable1.split(';') %}
The grass is {{ item1 }} and the boat is {{ item2 }}

Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error

According to wikipedia article on status codes. Nginx has a custom error code when http traffic is sent to https port(error code 497)

And according to nginx docs on error_page, you can define a URI that will be shown for a specific error.
Thus we can create a uri that clients will be sent to when error code 497 is raised.

nginx.conf

#lets assume your IP address is 89.89.89.89 and also 
#that you want nginx to listen on port 7000 and your app is running on port 3000

server {
    listen 7000 ssl;
 
    ssl_certificate /path/to/ssl_certificate.cer;
    ssl_certificate_key /path/to/ssl_certificate_key.key;
    ssl_client_certificate /path/to/ssl_client_certificate.cer;

    error_page 497 301 =307 https://89.89.89.89:7000$request_uri;

    location / {
        proxy_pass http://89.89.89.89:3000/;

        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Protocol $scheme;
    }
}

However if a client makes a request via any other method except a GET, that request will be turned into a GET. Thus to preserve the request method that the client came in via; we use error processing redirects as shown in nginx docs on error_page

And thats why we use the 301 =307 redirect.

Using the nginx.conf file shown here, we are able to have http and https listen in on the same port

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

If anyone has this error with seemingly well formed FK/PK relationships and you used the visual tool, try deleting the offending fk columns and re-adding them in the tool. I was continually getting this error until I redrew the connections which cleared up the issues.

How to alert using jQuery

$(".overdue").each( function() {
    alert("Your book is overdue.");
});

Note that ".addClass()" works because addClass is a function defined on the jQuery object. You can't just plop any old function on the end of a selector and expect it to work.

Also, probably a bad idea to bombard the user with n popups (where n = the number of books overdue).

Perhaps use the size function:

alert( "You have " + $(".overdue").size() + " books overdue." );

Matplotlib different size subplots

Another way is to use the subplots function and pass the width ratio with gridspec_kw:

import numpy as np
import matplotlib.pyplot as plt 

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
f, (a0, a1) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [3, 1]})
a0.plot(x, y)
a1.plot(y, x)

f.tight_layout()
f.savefig('grid_figure.pdf')

What key shortcuts are to comment and uncomment code?

Keyboard accelerators are configurable. You can find out which keyboard accelerators are bound to a command in Tools -> Options on the Environment -> Keyboard page.

These commands are named Edit.CommentSelection and Edit.UncommentSelection.

(With my settings, these are bound to Ctrl+K, Ctrl+C and Ctrl+K, Ctrl+U. I would guess that these are the defaults, at least in the C++ defaults, but I don't know for sure. The best way to find out is to check your settings.)

Using CRON jobs to visit url?

i use this commands

wget -q -O /dev/null "http://example.com/some/cron/job.php" > /dev/null 2>&1

Cron task:

* * * * * wget -q -O /dev/null "http://example.com/some/cron/job.php" > /dev/null 2>&1

Proper way to get page content

The wp_trim_words function can limit the characters too by changing the $num_words variable. For anyone who might find useful.

<?php 
$id=58; 
$post = get_post($id); 
$content = apply_filters('the_content', $post->post_content); 

$customExcerpt = wp_trim_words( $content, $num_words = 26, $more = '' );
echo $customExcerpt;  
?>

Is there a way to rollback my last push to Git?

First you need to determine the revision ID of the last known commit. You can use HEAD^ or HEAD~{1} if you know you need to reverse exactly one commit.

git reset --hard <revision_id_of_last_known_good_commit>
git push --force

Connecting to Oracle Database through C#?

You can use Oracle.ManagedDataAccess NuGet package too (.NET >= 4.0, database >= 10g Release 2).

How do I setup the InternetExplorerDriver so it works

public class NavigateUsingAllBrowsers {


public static void main(String[] args) {

WebDriver driverFF= new FirefoxDriver();
driverFF.navigate().to("http://www.firefox.com");


File file =new File("C:/Users/mkv/workspace/ServerDrivers/IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driverIE=new InternetExplorerDriver();
driverIE.navigate().to("http://www.msn.com");

// Download Chrome Driver from http://code.google.com/p/chromedriver/downloads/list

file =new File("C:/Users/mkv/workspace/ServerDrivers/ChromeDriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
WebDriver driverChrome=new ChromeDriver();
driverChrome.navigate().to("http://www.chrome.com");

}

}

Is it possible to use if...else... statement in React render function?

If you want to use If, else if, and else then use this method

           {this.state.value === 0 ? (
                <Component1 />
            ) : this.state.value === 1 ? (
              <Component2 />
            ) : (
              <Component3 />
            )}

How to grey out a button?

You should create a XML file for the disabled button (drawable/btn_disable.xml)

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/grey" />
    <corners android:radius="6dp" />
</shape>

And create a selector for the button (drawable/btn_selector.xml)

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/btn_disable" android:state_enabled="false"/>
    <item android:drawable="@drawable/btn_default" android:state_enabled="true"/>
    <item android:drawable="@drawable/btn_default" android:state_pressed="false" />

</selector>

Add the selector to your button

<style name="srp_button" parent="@android:style/Widget.Button">
    <item name="android:background">@drawable/btn_selector</item>
</style>

How to remove indentation from an unordered list item?

Live demo: https://jsfiddle.net/h8uxmoj4/

ol, ul {
  padding-left: 0;
}

li {
  list-style: none;
  padding-left: 1.25rem;
  position: relative;
}

li::before {
  left: 0;
  position: absolute;
}

ol {
  counter-reset: counter;
}

ol li::before {
  content: counter(counter) ".";
  counter-increment: counter;
}

ul li::before {
  content: "?";
}

Since the original question is unclear about its requirements, I attempted to solve this problem within the guidelines set by other answers. In particular:

  • Align list bullets with outside paragraph text
  • Align multiple lines within the same list item

I also wanted a solution that didn't rely on browsers agreeing on how much padding to use. I've added an ordered list for completeness.

Bash checking if string does not contain other string

Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.

fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf 
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"

How to call javascript function from asp.net button click event

You're already prepending the hash sign in your showDialog() function, and you're missing single quotes in your second code snippet. You should also return false from the handler to prevent a postback from occurring. Try:

<asp:Button ID="ButtonAdd" runat="server" Text="Add"
    OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />

Passing multiple variables to another page in url

Use & for this. Using & you can put as many variables as you want!

$url = "http://localhost/main.php?event_id=".$event_id."&email=".$email;

Private properties in JavaScript ES6 classes

I realize there are dozens of answers here. I want to share my solution, which ensures true private variables in ES6 classes and in older JS.

var MyClass = (function() {
    var $ = new WeakMap();
    function priv(self) {
       var r = $.get(self);
       if (!r) $.set(self, r={});
       return r;
    }

    return class { /* use $(this).prop inside your class */ } 
}();

Privacy is ensured by the fact that the outside world don't get access to $.

When the instance goes away, the WeakMap will release the data.

This definitely works in plain Javascript, and I believe they work in ES6 classes but I haven't tested that $ will be available inside the scope of member methods.

How to insert array of data into mysql using php

I would avoid to do a query for each entry.

if(is_array($EMailArr)){

    $sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) values ";

    $valuesArr = array();
    foreach($EMailArr as $row){

        $R_ID = (int) $row['R_ID'];
        $email = mysql_real_escape_string( $row['email'] );
        $name = mysql_real_escape_string( $row['name'] );

        $valuesArr[] = "('$R_ID', '$email', '$name')";
    }

    $sql .= implode(',', $valuesArr);

    mysql_query($sql) or exit(mysql_error()); 
}

How do I specify a password to 'psql' non-interactively?

I tend to prefer passing a URL to psql:

psql "postgresql://$DB_USER:$DB_PWD@$DB_SERVER/$DB_NAME"

This gives me the freedom to name my environment variables as I wish and avoids creating unnecessary files.

This requires libpq. The documentation can be found here.

Android video streaming example

I was facing the same problem and found a solution to get the code to work.

The code given in the android-Sdk/samples/android-?/ApiDemos works fine. Copy paste each folder in the android project and then in the MediaPlayerDemo_Video.java put the path of the video you want to stream in the path variable. It is left blank in the code.

The following video stream worked for me: http://www.pocketjourney.com/downloads/pj/video/famous.3gp

I know that RTSP protocol is to be used for streaming, but mediaplayer class supports http for streaming as mentioned in the code.

I googled for the format of the video and found that the video if converted to mp4 or 3gp using Quicktime Pro works fine for streaming.

I tested the final apk on android 2.1. The application dosent work on emulators well. Try it on devices.

I hope this helps..

good postgresql client for windows?

I heartily recommended dbVis. The client runs on Mac, Windows and Linux and supports a variety of database servers, including PostgreSQL.

Counting words in string

Try these before reinventing the wheels

from Count number of words in string using JavaScript

function countWords(str) {
  return str.trim().split(/\s+/).length;
}

from http://www.mediacollege.com/internet/javascript/text/count-words.html

function countWords(s){
    s = s.replace(/(^\s*)|(\s*$)/gi,"");//exclude  start and end white-space
    s = s.replace(/[ ]{2,}/gi," ");//2 or more space to 1
    s = s.replace(/\n /,"\n"); // exclude newline with a start spacing
    return s.split(' ').filter(function(str){return str!="";}).length;
    //return s.split(' ').filter(String).length; - this can also be used
}

from Use JavaScript to count words in a string, WITHOUT using a regex - this will be the best approach

function WordCount(str) {
     return str.split(' ')
            .filter(function(n) { return n != '' })
            .length;
}

Notes From Author:

You can adapt this script to count words in whichever way you like. The important part is s.split(' ').length — this counts the spaces. The script attempts to remove all extra spaces (double spaces etc) before counting. If the text contains two words without a space between them, it will count them as one word, e.g. "First sentence .Start of next sentence".

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.

I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.

  1. Go to the "Manage NuGet Packages"
  2. Select the Installed Package "Microsoft ASP.NET Web API 2.1"
  3. Click Manage and check the projects that I manually added before.

Store select query's output in one array in postgres

I had exactly the same problem. Just one more working modification of the solution given by Denis (the type must be specified):

SELECT ARRAY(
SELECT column_name::text
FROM information_schema.columns
WHERE table_name='aean'
)

How to read a PEM RSA private key from .NET

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

under Cryptography Application Block.

Don't know if you will get your answer, but it's worth a try.

Edit after Comment.

Ok then check this code.

using System.Security.Cryptography;


public static string DecryptEncryptedData(stringBase64EncryptedData, stringPathToPrivateKeyFile) { 
    X509Certificate2 myCertificate; 
    try{ 
        myCertificate = new X509Certificate2(PathToPrivateKeyFile); 
    } catch{ 
        throw new CryptographicException("Unable to open key file."); 
    } 

    RSACryptoServiceProvider rsaObj; 
    if(myCertificate.HasPrivateKey) { 
         rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey; 
    } else 
        throw new CryptographicException("Private key not contained within certificate."); 

    if(rsaObj == null) 
        return String.Empty; 

    byte[] decryptedBytes; 
    try{ 
        decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false); 
    } catch { 
        throw new CryptographicException("Unable to decrypt data."); 
    } 

    //    Check to make sure we decrpyted the string 
   if(decryptedBytes.Length == 0) 
        return String.Empty; 
    else 
        return System.Text.Encoding.UTF8.GetString(decryptedBytes); 
} 

Loading inline content using FancyBox

The solution is very simple, but took me about 2 hours and half the hair on my head to find it.

Simply wrap your content with a (redundant) div that has display: none and Bob is your uncle.

<div style="display: none">
    <div id="content-div">Some content here</div>
</div>

Voila

Implements vs extends: When to use? What's the difference?

Classes and Interfaces are both contracts. They provide methods and properties other parts of an application relies on.

You define an interface when you are not interested in the implementation details of this contract. The only thing to care about is that the contract (the interface) exists.

In this case you leave it up to the class which implements the interface to care about the details how the contract is fulfilled. Only classes can implement interfaces.

extends is used when you would like to replace details of an existing contract. This way you replace one way to fulfill a contract with a different way. Classes can extend other classes, and interfaces can extend other interfaces.

Click outside menu to close in jquery

Use the ':visible' selector. Where .menuitem is the to-hide element(s) ...

$('body').click(function(){
  $('.menuitem:visible').hide('fast');
});

Or if you already have the .menuitem element(s) in a var ...

var menitems = $('.menuitem');
$('body').click(function(){
  menuitems.filter(':visible').hide('fast');
});

Why powershell does not run Angular commands?

I solved my problem by running below command

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

SQL query to get the deadlocks in SQL SERVER 2008

You can use a deadlock graph and gather the information you require from the log file.

The only other way I could suggest is digging through the information by using EXEC SP_LOCK (Soon to be deprecated), EXEC SP_WHO2 or the sys.dm_tran_locks table.

SELECT  L.request_session_id AS SPID, 
    DB_NAME(L.resource_database_id) AS DatabaseName,
    O.Name AS LockedObjectName, 
    P.object_id AS LockedObjectId, 
    L.resource_type AS LockedResource, 
    L.request_mode AS LockType,
    ST.text AS SqlStatementText,        
    ES.login_name AS LoginName,
    ES.host_name AS HostName,
    TST.is_user_transaction as IsUserTransaction,
    AT.name as TransactionName,
    CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
    JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
    JOIN sys.objects O ON O.object_id = P.object_id
    JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
    JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
    JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
    JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
    CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

http://www.sqlmag.com/article/sql-server-profiler/gathering-deadlock-information-with-deadlock-graph

http://weblogs.sqlteam.com/mladenp/archive/2008/04/29/SQL-Server-2005-Get-full-information-about-transaction-locks.aspx

How to insert a line break in a SQL Server VARCHAR/NVARCHAR string

This is always cool, because when you get exported lists from, say Oracle, then you get records spanning several lines, which in turn can be interesting for, say, cvs files, so beware.

Anyhow, Rob's answer is good, but I would advise using something else than @, try a few more, like §§@@§§ or something, so it will have a chance for some uniqueness. (But still, remember the length of the varchar/nvarchar field you are inserting into..)

Redirecting to a page after submitting form in HTML

What you could do is, a validation of the values, for example:

if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.

_x000D_
_x000D_
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");

// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");

// Form
let contactForm = document.getElementById("form");

// Event listener
contactForm.addEventListener("submit", function (e) {
  let messageName = [];
  let messageAddress = [];
  
    if (fullname.value === "" || fullname.value === null) {
    messageName.push("* This field is required");
  }

  if (address.value === "" || address.value === null) {
    messageAddress.push("* This field is required");
  }

  // Statement to shows the errors
  if (messageName.length || messageAddress.length > 0) {
    e.preventDefault();
    errorElement.innerText = messageName;
    errorElementAddress.innerText = messageAddress;
  }
  
   // if the values length is filled and it's greater than 2 then redirect to this page
    if (
    (fullname.value.length > 2,
    address.value.length > 2)
  ) {
    e.preventDefault();
    window.location.assign("https://www.google.com");
  }

});
_x000D_
.error {
  color: #000;
}

.input-container {
  display: flex;
  flex-direction: column;
  margin: 1rem auto;
}
_x000D_
<html>
  <body>
    <form id="form" method="POST">
    <div class="input-container">
    <label>Full name:</label>
      <input type="text" id="fullname" name="fullname">
      <div class="error" id="name_error"></div>
      </div>
      
      <div class="input-container">
      <label>Address:</label>
      <input type="text" id="address" name="address">
      <div class="error" id="address_error"></div>
      </div>
      <button type="submit" id="submit_button" value="Submit request" >Submit</button>
    </form>
  </body>
</html>
_x000D_
_x000D_
_x000D_

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

Also, don't forget to escape variables if you want to pick them up from the destination host.

This has caught me out in the past.

For example:

user@host> ssh user2@host2 "echo \$HOME"

prints out /home/user2

while

user@host> ssh user2@host2 "echo $HOME"

prints out /home/user

Another example:

user@host> ssh user2@host2 "echo hello world | awk '{print \$1}'"

prints out "hello" correctly.

jQuery: Get height of hidden element in jQuery

I try to find working function for hidden element but I realize that CSS is much complex than everyone think. There are a lot of new layout techniques in CSS3 that might not work for all previous answers like flexible box, grid, column or even element inside complex parent element.

flexibox example enter image description here

I think the only sustainable & simple solution is real-time rendering. At that time, browser should give you that correct element size.

Sadly, JavaScript does not provide any direct event to notify when element is showed or hidden. However, I create some function based on DOM Attribute Modified API that will execute callback function when visibility of element is changed.

$('[selector]').onVisibleChanged(function(e, isVisible)
{
    var realWidth = $('[selector]').width();
    var realHeight = $('[selector]').height();

    // render or adjust something
});

For more information, Please visit at my project GitHub.

https://github.com/Soul-Master/visible.event.js

demo: http://jsbin.com/ETiGIre/7

Why does the html input with type "number" allow the letter 'e' to be entered in the field?

The best way to force the use of a number composed of digits only:

_x000D_
_x000D_
<input type="number" onkeydown="javascript: return event.keyCode === 8 ||_x000D_
event.keyCode === 46 ? true : !isNaN(Number(event.key))" />
_x000D_
_x000D_
_x000D_

this avoids 'e', '-', '+', '.' ... all characters that are not numbers !

To allow number keys only:

isNaN(Number(event.key))

but accept "Backspace" (keyCode: 8) and "Delete" (keyCode: 46) ...

What is the "right" JSON date format?

I believe that the best format for universal interoperability is not the ISO-8601 string, but rather the format used by EJSON:

{ "myDateField": { "$date" : <ms-since-epoch> } }

As described here: https://docs.meteor.com/api/ejson.html

Benefits

  1. Parsing performance: If you store dates as ISO-8601 strings, this is great if you are expecting a date value under that particular field, but if you have a system which must determine value types without context, you're parsing every string for a date format.
  2. No Need for Date Validation: You need not worry about validation and verification of the date. Even if a string matches ISO-8601 format, it may not be a real date; this can never happen with an EJSON date.
  3. Unambiguous Type Declaration: as far as generic data systems go, if you wanted to store an ISO string as a string in one case, and a real system date in another, generic systems adopting the ISO-8601 string format will not allow this, mechanically (without escape tricks or similar awful solutions).

Conclusion

I understand that a human-readable format (ISO-8601 string) is helpful and more convenient for 80% of use cases, and indeed no-one should ever be told not to store their dates as ISO-8601 strings if that's what their applications understand, but for a universally accepted transport format which should guarantee certain values to for sure be dates, how can we allow for ambiguity and need for so much validation?

How to get config parameters in Symfony2 Twig Templates

In confing.yml

# app/config/config.yml
twig:
  globals:
    version: '%app.version%'

In Twig view

# twig view
{{ version }}

Responsive css background images

Try using background-size but using TWO ARGUMENTS One for the width and the other one for the height

background-image:url('../images/bg.png'); 
background-repeat:no-repeat;
background-size: 100% 100%; // Here the first argument will be the width 
// and the second will be the height.
background-position:center;

Using awk to print all columns from the nth to the last

Because of a wrong most upvoted anwser with 340 votes, I just lost 5 minutes of my life! Did anybody try this answer out before upvoting this? Apparantly not. Completely useless.

I have a log where after $5 with an IP address can be more text or no text. I need everything from the IP address to the end of the line should there be anything after $5. In my case, this is actualy withn an awk program, not an awk oneliner so awk must solve the problem. When I try to remove the first 4 fields using the most upvoted but completely wrong answer:

echo "  7 27.10.16. Thu 11:57:18 37.244.182.218" | awk '{$1=$2=$3=$4=""; printf "[%s]\n", $0}'

it spits out wrong and useless response (I added [..] to demonstrate):

[    37.244.182.218 one two three]

There are even some sugestions to combine substr with this wrong answer. Like that complication is an improvement.

Instead, if columns are fixed width until the cut point and awk is needed, the correct answer is:

echo "  7 27.10.16. Thu 11:57:18 37.244.182.218" | awk '{printf "[%s]\n", substr($0,28)}'

which produces the desired output:

[37.244.182.218 one two three]

How do you get the length of a list in the JSF expression language?

You can get the length using the following EL:

#{Bean.list.size()}

Display rows with one or more NaN values in pandas dataframe

Suppose gamma1 and gamma2 are two such columns for which df.isnull().any() gives True value , the following code can be used to print the rows.

bool1 = pd.isnull(df['gamma1'])
bool2 = pd.isnull(df['gamma2'])
df[bool1]
df[bool2]

Android: how to handle button click

To make things easier asp Question 2 stated, you can make use of lambda method like this to save variable memory and to avoid navigating up and down in your view class

//method 1
findViewById(R.id.buttonSend).setOnClickListener(v -> {
          // handle click
});

but if you wish to apply click event to your button at once in a method.

you can make use of Question 3 by @D. Tran answer. But do not forget to implement your view class with View.OnClickListener.

In other to use Question #3 properly

x86 Assembly on a Mac

After installing any version of Xcode targeting Intel-based Macs, you should be able to write assembly code. Xcode is a suite of tools, only one of which is the IDE, so you don't have to use it if you don't want to. (That said, if there are specific things you find clunky, please file a bug at Apple's bug reporter - every bug goes to engineering.) Furthermore, installing Xcode will install both the Netwide Assembler (NASM) and the GNU Assembler (GAS); that will let you use whatever assembly syntax you're most comfortable with.

You'll also want to take a look at the Compiler & Debugging Guides, because those document the calling conventions used for the various architectures that Mac OS X runs on, as well as how the binary format and the loader work. The IA-32 (x86-32) calling conventions in particular may be slightly different from what you're used to.

Another thing to keep in mind is that the system call interface on Mac OS X is different from what you might be used to on DOS/Windows, Linux, or the other BSD flavors. System calls aren't considered a stable API on Mac OS X; instead, you always go through libSystem. That will ensure you're writing code that's portable from one release of the OS to the next.

Finally, keep in mind that Mac OS X runs across a pretty wide array of hardware - everything from the 32-bit Core Single through the high-end quad-core Xeon. By coding in assembly you might not be optimizing as much as you think; what's optimal on one machine may be pessimal on another. Apple regularly measures its compilers and tunes their output with the "-Os" optimization flag to be decent across its line, and there are extensive vector/matrix-processing libraries that you can use to get high performance with hand-tuned CPU-specific implementations.

Going to assembly for fun is great. Going to assembly for speed is not for the faint of heart these days.

Shortcut to open file in Vim

:find is another option.

I open vim from the root of my project and have the path set to there.

Then, I can open files located anywhere in the tree using:

:find **/filena< tab >

Tab will autocomplete through various matches. (** tells it to search recursively through the path).

Android Firebase, simply get one child object's data

You don't directly read a value. You can set it with .setValue(), but there is no .getValue() on the reference object.

You have to use a listener. If you just want to read the value once, you use ref.addListenerForSingleValueEvent().

Example:

Firebase ref = new Firebase("YOUR-URL-HERE/PATH/TO/YOUR/STUFF");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
       String value = (String) dataSnapshot.getValue();

       // do your stuff here with value

   }

   @Override
   public void onCancelled(FirebaseError firebaseError) {

   }
});

Source: https://www.firebase.com/docs/android/guide/retrieving-data.html#section-reading-once

PHP-FPM and Nginx: 502 Bad Gateway

For anyone else struggling to get to the bottom of this, I tried adjusting timeouts as suggested as I didn't want to stop using Unix sockets...after lots of troubleshooting and not much to go on I found that this issue was being caused by the APC extension that I'd enabled in php-fpm a few months back. Disabling this extension resolved the intermittent 502 errors, easiest way to do this was by commenting out the following line :

;extension = apc.so

This did the trick for me!

awk - concatenate two string variable and assign to a third

Could use sprintf to accomplish this:

awk '{str = sprintf("%s %s", $1, $2)} END {print str}' file

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))