Programs & Examples On #Jboss5.x

The JBoss tag is for questions relating specifically to the 5.x releases of JBoss Application Server.

How to deploy a war file in JBoss AS 7?

Just copy war file to standalone/deployments/ folder, it should deploy it automatically. It'll also create your_app_name.deployed file, when your application is deployed. Also be sure that you start server with bin/standalone.sh script.

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

How to change RGB color to HSV?

The EasyRGB has many color space conversions. Here is the code for the RGB->HSV conversion.

What tools do you use to test your public REST API?

If you're just testing your APIs manually, we've found RestClient 2.3 or the Poster add-on for Firefox to be pretty helpful. Both of these let you build requests that GET, PUT, POST, or DELETE. You can save these requests to rerun later.

For simple automated testing try the Linux (or Cygwin) 'curl' command in a shell script.

From something more industrial strength you can move up to Apache JMeter. JMeter is great for load testing.

31 October 2014: HTTPRequester is now a better choice for Firefox.

July 2015: Postman is a good choice for Chrome

Restart node upon changing a file

Follow the steps:

  1. npm install --save-dev nodemon

  2. Add the following two lines to "script" section of package.json:

"start": "node ./bin/www",
"devstart": "nodemon ./bin/www"

as shown below:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node ./bin/www",
    "devstart": "nodemon ./bin/www"
}
  1. npm run devstart

https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website

R legend placement in a plot

Building on @P-Lapointe solution, but making it extremely easy, you could use the maximum values from your data using max() and then you re-use those maximum values to set the legend xy coordinates. To make sure you don't get beyond the borders, you set up ylim slightly over the maximum values.

a=c(rnorm(1000))
b=c(rnorm(1000))
par(mfrow=c(1,2))
plot(a,ylim=c(0,max(a)+1))
legend(x=max(a)+0.5,legend="a",pch=1)
plot(a,b,ylim=c(0,max(b)+1),pch=2)
legend(x=max(b)-1.5,y=max(b)+1,legend="b",pch=2)

enter image description here

How to change text color of cmd with windows batch script every 1 second

echo off & cls
title   never buy these they're so easy to make... hmu for source code             

    -%pinging:IP%-
color 0D

echo =================================================================
echo i flex on my unhittable ovh, you flex on an easy to hit trash ovh
echo =================================================================
set /p IP=Enter IP:
:top
title :: this skid's boutta get slammed FeelsGoodMan ::    -%pinging:IP%-
PING -n 1 %IP% | FIND "TTL="
IF ERRORLEVEL (echo stop flexing on ovh's i down them with ease, mine on the other hand is unhittable.):
set /a num=(%Random%%%9)+1
color %num%IP   ping -t 2 0 10 127.0.0.1 >nul
GoTo top

This is an ip pinging that has custom timed out messages for if something such as a website or server is down, also, can use for if booting people offline, I can make a tool that opens files and individual pingers dependant on your input, and a built in geo-location tool.

Launch an event when checking a checkbox in Angular2

StackBlitz

Template: You can either use the native change event or NgModel directive's ngModelChange.

<input type="checkbox" (change)="onNativeChange($event)"/>

or

<input type="checkbox" ngModel (ngModelChange)="onNgModelChange($event)"/>

TS:

onNativeChange(e) { // here e is a native event
  if(e.target.checked){
    // do something here
  }
}

onNgModelChange(e) { // here e is a boolean, true if checked, otherwise false
  if(e){
    // do something here
  }
}

MySQL: Insert datetime into other datetime field

Try

    UPDATE products SET former_date=20111218131717 WHERE id=1

Alternatively, you might want to look at using the STR_TO_DATE (see STR_TO_DATE(str,format)) function.

How to sort a NSArray alphabetically?

The other answers provided here mention using @selector(localizedCaseInsensitiveCompare:) This works great for an array of NSString, however if you want to extend this to another type of object, and sort those objects according to a 'name' property, you should do this instead:

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
sortedArray=[anArray sortedArrayUsingDescriptors:@[sort]];

Your objects will be sorted according to the name property of those objects.

If you want the sorting to be case insensitive, you would need to set the descriptor like this

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

I run into the same error with you when i run the jconsole command at remote. I want to modify a parameter at jconsole that run on a remote Linux host, i can login the host use the secureCRT, the terminal throw this error information. Fortunately, when use the Putty, it's ok. Weird....

how to remove new lines and returns from php string?

$str = "Hello World!\n\n";
echo chop($str);

output : Hello World!

case-insensitive matching in xpath?

for selenium xpath lower-case will not work ... Translate will help Case 1 :

  1. using Attribute //*[translate(@id,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='login_field']
  2. Using any attribute //[translate(@,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='login_field']

Case 2 : (with contains) //[contains(translate(@id,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),'login_field')]

case 3 : for Text property //*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),'username')]


QA Automator is automation management tool on cloud platform , where you can create, execute and maintenance the automation test scripts https://www.youtube.com/watch?v=iFk1Na_627U&t=53s

Sharing a variable between multiple different threads

Both T1 and T2 can refer to a class containing this variable.
You can then make this variable volatile, and this means that
Changes to that variable are immediately visible in both threads.

See this article for more info.

Volatile variables share the visibility features of synchronized but none of the atomicity features. This means that threads will automatically see the most up-to-date value for volatile variables. They can be used to provide thread safety, but only in a very restricted set of cases: those that do not impose constraints between multiple variables or between a variable's current value and its future values.

And note the pros/cons of using volatile vs more complex means of sharing state.

Convert UTC/GMT time to local time

I had the problem with it being in a data set being pushed across the wire (webservice to client) that it would automatically change because the DataColumn's DateType field was set to local. Make sure you check what the DateType is if your pushing DataSets across.

If you don't want it to change, set it to Unspecified

How to transform numpy.matrix or array to scipy sparse matrix

There are several sparse matrix classes in scipy.

bsr_matrix(arg1[, shape, dtype, copy, blocksize]) Block Sparse Row matrix
coo_matrix(arg1[, shape, dtype, copy]) A sparse matrix in COOrdinate format.
csc_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Column matrix
csr_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Row matrix
dia_matrix(arg1[, shape, dtype, copy]) Sparse matrix with DIAgonal storage
dok_matrix(arg1[, shape, dtype, copy]) Dictionary Of Keys based sparse matrix.
lil_matrix(arg1[, shape, dtype, copy]) Row-based linked list sparse matrix

Any of them can do the conversion.

import numpy as np
from scipy import sparse
a=np.array([[1,0,1],[0,0,1]])
b=sparse.csr_matrix(a)
print(b)

(0, 0)  1
(0, 2)  1
(1, 2)  1

See http://docs.scipy.org/doc/scipy/reference/sparse.html#usage-information .

How to return multiple objects from a Java method?

Why not create a WhateverFunctionResult object that contains your results, and the logic required to parse these results, iterate over then etc. It seems to me that either:

  1. These results objects are intimately tied together/related and belong together, or:
  2. they are unrelated, in which case your function isn't well defined in terms of what it's trying to do (i.e. doing two different things)

I see this sort of issue crop up again and again. Don't be afraid to create your own container/result classes that contain the data and the associated functionality to handle this. If you simply pass the stuff around in a HashMap or similar, then your clients have to pull this map apart and grok the contents each time they want to use the results.

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.

Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload

How to Handle Button Click Events in jQuery?

<script type="text/javascript">

    $(document).ready(function() {

    $("#Button1").click(function() {

        alert("hello");

    });

    }
    );

</script>

Is there a way to make Firefox ignore invalid ssl-certificates?

I ran into this issue when trying to get to one of my companies intranet sites. Here is the solution I used:

  1. enter about:config into the firefox address bar and agree to continue.
  2. search for the preference named security.ssl.enable_ocsp_stapling.
  3. double-click this item to change its value to false.

This will lower your security as you will be able to view sites with invalid certs. Firefox will still prompt you that the cert is invalid and you have the choice to proceed forward, so it was worth the risk for me.

How to skip a iteration/loop in while-loop

While you could use a continue, why not just inverse the logic in your if?

while(rs.next())
{
    if(!f.exists() || f.isDirectory()){
    //proceed
    }
}

You don't even need an else {continue;} as it will continue anyway if the if conditions are not satisfied.

Calculate distance between two latitude-longitude points? (Haversine formula)

As this is the most popular discussion of the topic I'll add my experience from late 2019-early 2020 here. To add to the existing answers - my focus was to find an accurate AND fast (i.e. vectorized) solution.

Let's start with what is mostly used by answers here - the Haversine approach. It is trivial to vectorize, see example in python below:

def haversine(lat1, lon1, lat2, lon2):
    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)

    All args must be of equal length.
    Distances are in meters.
    
    Ref:
    https://stackoverflow.com/questions/29545704/fast-haversine-approximation-python-pandas
    https://ipython.readthedocs.io/en/stable/interactive/magics.html
    """
    Radius = 6.371e6
    lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])

    dlon = lon2 - lon1
    dlat = lat2 - lat1

    a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2

    c = 2 * np.arcsin(np.sqrt(a))
    s12 = Radius * c
    
    # initial azimuth in degrees
    y = np.sin(lon2-lon1) * np.cos(lat2)
    x = np.cos(lat1)*np.sin(lat2) - np.sin(lat1)*np.cos(lat2)*np.cos(dlon)
    azi1 = np.arctan2(y, x)*180./math.pi

    return {'s12':s12, 'azi1': azi1}

Accuracy-wise, it is least accurate. Wikipedia states 0.5% of relative deviation on average without any sources. My experiments show less of a deviation. Below is the comparison ran on 100,000 random points vs my library, which should be accurate to millimeter levels:

np.random.seed(42)
lats1 = np.random.uniform(-90,90,100000)
lons1 = np.random.uniform(-180,180,100000)
lats2 = np.random.uniform(-90,90,100000)
lons2 = np.random.uniform(-180,180,100000)
r1 = inverse(lats1, lons1, lats2, lons2)
r2 = haversine(lats1, lons1, lats2, lons2)
print("Max absolute error: {:4.2f}m".format(np.max(r1['s12']-r2['s12'])))
print("Mean absolute error: {:4.2f}m".format(np.mean(r1['s12']-r2['s12'])))
print("Max relative error: {:4.2f}%".format(np.max((r2['s12']/r1['s12']-1)*100)))
print("Mean relative error: {:4.2f}%".format(np.mean((r2['s12']/r1['s12']-1)*100)))

Output:

Max absolute error: 26671.47m
Mean absolute error: -2499.84m
Max relative error: 0.55%
Mean relative error: -0.02%

So on average 2.5km deviation on 100,000 random pairs of coordinates, which may be good for majority of cases.

Next option is Vincenty's formulae which is accurate up to millimeters, depending on convergence criteria and can be vectorized as well. It does have the issue with convergence near antipodal points. You can make it converge at those points by relaxing convergence criteria, but accuracy drops to 0.25% and more. Outside of antipodal points Vincenty will provide results close to Geographiclib within relative error of less than 1.e-6 on average.

Geographiclib, mentioned here, is really the current golden standard. It has several implementations and fairly fast, especially if you are using C++ version.

Now, if you are planning to use Python for anything above 10k points I'd suggest to consider my vectorized implementation. I created a geovectorslib library with vectorized Vincenty routine for my own needs, which uses Geographiclib as fallback for near antipodal points. Below is the comparison vs Geographiclib for 100k points. As you can see it provides up to 20x improvement for inverse and 100x for direct methods for 100k points and the gap will grow with number of points. Accuracy-wise it will be within 1.e-5 rtol of Georgraphiclib.

Direct method for 100,000 points
94.9 ms ± 25 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
9.79 s ± 1.4 s per loop (mean ± std. dev. of 7 runs, 1 loop each)

Inverse method for 100,000 points
1.5 s ± 504 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
24.2 s ± 3.91 s per loop (mean ± std. dev. of 7 runs, 1 loop each)

Hiding axis text in matplotlib plots

I was not actually able to render an image without borders or axis data based on any of the code snippets here (even the one accepted at the answer). After digging through some API documentation, I landed on this code to render my image

plt.axis('off')
plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')
plt.savefig('foo.png', dpi=100, bbox_inches='tight', pad_inches=0.0)

I used the tick_params call to basically shut down any extra information that might be rendered and I have a perfect graph in my output file.

How can I make a UITextField move up when the keyboard is present - on starting to edit?

Try IQKeyboard library.

This will automatically move the text field's up.

Where are $_SESSION variables stored?

In my Ubuntu machine sessions are stored at

/var/lib/php/sessions

and you have to sudo ls in this directory only ls it will throw

ls: cannot open directory '.': Permission denied

And on my Windows Wamp server php sessions are stored in

C:\wamp64\tmp

and if you install standalone php on windows then there is no value set by default

session.save_path => no value => no value

Calculating days between two dates with Java

Simplest way:

public static long getDifferenceDays(Date d1, Date d2) {
    long diff = d2.getTime() - d1.getTime();
    return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}

Getting the first character of a string with $str[0]

It'll vary depending on resources, but you could run the script bellow and see for yourself ;)

<?php
$tests = 100000;

for ($i = 0; $i < $tests; $i++)
{
    $string = md5(rand());
    $position = rand(0, 31);

    $start1 = microtime(true);
    $char1 = $string[$position];
    $end1 = microtime(true);
    $time1[$i] = $end1 - $start1;

    $start2 = microtime(true);
    $char2 = substr($string, $position, 1);
    $end2 = microtime(true);
    $time2[$i] = $end2 - $start2;

    $start3 = microtime(true);
    $char3 = $string{$position};
    $end3 = microtime(true);
    $time3[$i] = $end3 - $start3;
}

$avg1 = array_sum($time1) / $tests;
echo 'the average float microtime using "array[]" is '. $avg1 . PHP_EOL;

$avg2 = array_sum($time2) / $tests;
echo 'the average float microtime using "substr()" is '. $avg2 . PHP_EOL;

$avg3 = array_sum($time3) / $tests;
echo 'the average float microtime using "array{}" is '. $avg3 . PHP_EOL;
?>

Some reference numbers (on an old CoreDuo machine)

$ php 1.php 
the average float microtime using "array[]" is 1.914701461792E-6
the average float microtime using "substr()" is 2.2536706924438E-6
the average float microtime using "array{}" is 1.821768283844E-6

$ php 1.php 
the average float microtime using "array[]" is 1.7251944541931E-6
the average float microtime using "substr()" is 2.0931363105774E-6
the average float microtime using "array{}" is 1.7225742340088E-6

$ php 1.php 
the average float microtime using "array[]" is 1.7293763160706E-6
the average float microtime using "substr()" is 2.1037721633911E-6
the average float microtime using "array{}" is 1.7249774932861E-6

It seems that using the [] or {} operators is more or less the same.

How to call a SOAP web service on Android

To call a web service from a mobile device (especially on an Android phone), I have used a very simple way to do it. I have not used any web service client API in attempt to call the web service. My approach is as follows to make a call.

  1. Create a simple HTTP connection by using the Java standard API HttpURLConnection.
  2. Form a SOAP request. (You can make help of SOAPUI to make a SOAP request.)
  3. Set doOutPut flag as true.
  4. Set HTTP header values like content-length, Content type, and User-agent. Do not forget to set Content-length value as it is a mandatory.
  5. Write entire the SOAP request to the output stream.
  6. Call the method to make a connection and receive the response (In my case I used getResonseCode).
  7. If your received response code as
    1. It means you are succeeded to call web service.
  8. Now take an input stream on the same HTTP connection and receive the string object. This string object is a SOAP response.
  9. If the response code is other than 200 then take a ErrorInput stream on same HTTPobject and receive the error if any.
  10. Parse the received response using SAXParser (in my case) or DOMParaser or any other parsing mechanism.

I have implemented this procedure for the Android phone, and it is successfully running. I am able to parse the response even if it is more than 700 KB.

Is it possible to use an input value attribute as a CSS selector?

You can use Css3 attribute selector or attribute value selector.

/This will make all input whose value is defined to red/

input[value]{
color:red;
}

/This will make conditional selection depending on input value/

input[value="United States"]{
color:red;
} 

There are other attribute selector like attribute contains value selector,

input[value="United S"]{
color: red;
}

This will still make any input with United state as red text.

Than we attribute value starts with selector

input[value^='united']{
color: red;
}

Any input text starts with 'united' will have font color red

And the last one is attribute value ends with selector

input[value$='States']{
color:red;
}

Any input value ends with 'States' will have font color red

XML parsing of a variable string in JavaScript

Marknote is a nice lightweight cross-browser JavaScript XML parser. It's object-oriented and it's got plenty of examples, plus the API is documented. It's fairly new, but it has worked nicely in one of my projects so far. One thing I like about it is that it will read XML directly from strings or URLs and you can also use it to convert the XML into JSON.

Here's an example of what you can do with Marknote:

var str = '<books>' +
          '  <book title="A Tale of Two Cities"/>' +
          '  <book title="1984"/>' +
          '</books>';

var parser = new marknote.Parser();
var doc = parser.parse(str);

var bookEls = doc.getRootElement().getChildElements();

for (var i=0; i<bookEls.length; i++) {
    var bookEl = bookEls[i];
    // alerts "Element name is 'book' and book title is '...'"
    alert("Element name is '" + bookEl.getName() + 
        "' and book title is '" + 
        bookEl.getAttributeValue("title") + "'"
    );
}

compareTo() vs. equals()

equals() should be the method of choice in the case of the OP.

Looking at the implementation of equals() and compareTo() in java.lang.String on grepcode, we can easily see that equals is better if we are just concerned with the equality of two Strings:

equals():

1012  public boolean equals(Object anObject) {
1013 if (this == anObject) {
1014 return true;
1015 }
1016 if (anObject instanceof String) {
1017 String anotherString = (String)anObject;
1018 int n = count;
1019 if (n == anotherString.count) {
1020 char v1[] = value;
1021 char v2[] = anotherString.value;
1022 int i = offset;
1023 int j = anotherString.offset;
1024 while (n-- != 0) {
1025 if (v1[i++] != v2[j++])
1026 return false;
1027 }
1028 return true;
1029 }
1030 }
1031 return false;
1032 }

and compareTo():

1174  public int compareTo(String anotherString) {
1175 int len1 = count;
1176 int len2 = anotherString.count;
1177 int n = Math.min(len1, len2);
1178 char v1[] = value;
1179 char v2[] = anotherString.value;
1180 int i = offset;
1181 int j = anotherString.offset;
1183 if (i == j) {
1184 int k = i;
1185 int lim = n + i;
1186 while (k < lim) {
1187 char c1 = v1[k];
1188 char c2 = v2[k];
1189 if (c1 != c2) {
1190 return c1 - c2;
1191 }
1192 k++;
1193 }
1194 } else {
1195 while (n-- != 0) {
1196 char c1 = v1[i++];
1197 char c2 = v2[j++];
1198 if (c1 != c2) {
1199 return c1 - c2;
1200 }
1201 }
1202 }
1203 return len1 - len2;
1204 }

When one of the strings is a prefix of another, the performance of compareTo() is worse as it still needs to determine the lexicographical ordering while equals() won't worry any more and return false immediately.

In my opinion, we should use these two as they were intended:

  • equals() to check for equality, and
  • compareTo() to find the lexical ordering.

Comparing strings in Java

Using the == operator will compare the references to the strings not the string themselves.

Ok, you have to toString() the Editable. I loaded up some of the code I had before that dealt with this situation.

String passwd1Text = passw1.getText().toString();
String passwd2Text = passw2.getText().toString();

if (passwd1Text.equals(passwd2Text))
{
}

IntelliJ does not show project folders

I had to quit Intellij and remove the .idea folder (I stashed it first, just in case). I then re-opened the project and that worked for me. Don't forget to save your configuration (e.g. debug / run configurations) before that, because they will also be deleted.

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

Exporting the credential also work, In linux:

export AWS_SECRET_ACCESS_KEY="XXXXXXXXXXXX"
export AWS_ACCESS_KEY_ID="XXXXXXXXXXX"

SSL cert "err_cert_authority_invalid" on mobile chrome only

I had this same problem while hosting a web site via Parse and using a Comodo SSL cert resold by NameCheap.

You will receive two cert files inside of a zip folder: www_yourdomain_com.ca-bundle www_yourdomain_com.crt

You can only upload one file to Parse: Parse SSL Cert Input Box

In terminal combine the two files using:

cat www_yourdomain_com.crt www_yourdomain_com.ca-bundle > www_yourdomain_com_combine.crt

Then upload to Parse. This should fix the issue with Android Chrome and Firefox browsers. You can verify that it worked by testing it at https://www.sslchecker.com/sslchecker

remove item from stored array in angular 2

I think the Angular 2 way of doing this is the filter method:

this.data = this.data.filter(item => item !== data_item);

where data_item is the item that should be deleted

proper name for python * operator?

For a colloquial name there is "splatting".

For arguments (list type) you use single * and for keyword arguments (dictionary type) you use double **.

Both * and ** is sometimes referred to as "splatting".

See for reference of this name being used: https://stackoverflow.com/a/47875892/14305096

IOS - How to segue programmatically using swift

If your segue exists in the storyboard with a segue identifier between your two views, you can just call it programmatically using:

performSegue(withIdentifier: "mySegueID", sender: nil)

For older versions:

performSegueWithIdentifier("mySegueID", sender: nil)

You could also do:

presentViewController(nextViewController, animated: true, completion: nil)

Or if you are in a Navigation controller:

self.navigationController?.pushViewController(nextViewController, animated: true)

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

No, it's not possible.

Passing by reference implies that the function might change the value of the parameter. If the parameter is not provided by the caller and comes from the default constant, what is the function supposed to change?

ggplot2 plot area margins?

You can adjust the plot margins with plot.margin in theme() and then move your axis labels and title with the vjust argument of element_text(). For example :

library(ggplot2)
library(grid)
qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.title.x=element_text(vjust=-2)) +
    theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
    theme(plot.title=element_text(size=15, vjust=3)) +
    theme(plot.margin = unit(c(1,1,1,1), "cm"))

will give you something like this :

enter image description here

If you want more informations about the different theme() parameters and their arguments, you can just enter ?theme at the R prompt.

How to replace spaces in file names using a bash script

A find/rename solution. rename is part of util-linux.

You need to descend depth first, because a whitespace filename can be part of a whitespace directory:

find /tmp/ -depth -name "* *" -execdir rename " " "_" "{}" ";"

Error 1053 the service did not respond to the start or control request in a timely fashion

I have just tried this code locally in .Net 4.5 and the service starts and stops correctly for me. I suspect your problem may be around creating the EventLog source.

The method:

EventLog.SourceExists("MySource")

requires that the user running the code must be an administrator, as per the documentation here:

http://msdn.microsoft.com/en-us/library/x7y6sy21(v=vs.110).aspx

Check that the service is running as a user that has administrator privileges.

How to document a method with parameter(s)?

Docstrings are only useful within interactive environments, e.g. the Python shell. When documenting objects that are not going to be used interactively (e.g. internal objects, framework callbacks), you might as well use regular comments. Here’s a style I use for hanging indented comments off items, each on their own line, so you know that the comment is applying to:

def Recomputate \
  (
    TheRotaryGyrator,
      # the rotary gyrator to operate on
    Computrons,
      # the computrons to perform the recomputation with
    Forthwith,
      # whether to recomputate forthwith or at one's leisure
  ) :
  # recomputates the specified rotary gyrator with
  # the desired computrons.
  ...
#end Recomputate

You can’t do this sort of thing with docstrings.

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

Set Content-Type to application/json in jsp file

You can do via Page directive.

For example:

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8"%>
  • contentType="mimeType [ ;charset=characterSet ]" | "text/html;charset=ISO-8859-1"

The MIME type and character encoding the JSP file uses for the response it sends to the client. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.

Redirecting from HTTP to HTTPS with PHP

On my AWS beanstalk server, I don't see $_SERVER['HTTPS'] variable. I do see $_SERVER['HTTP_X_FORWARDED_PROTO'] which can be either 'http' or 'https' so if you're hosting on AWS, use this:

if ($_SERVER['HTTP_HOST'] != 'localhost' and $_SERVER['HTTP_X_FORWARDED_PROTO'] != "https") {
    $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $location);
    exit;
}

Installing a local module using npm?

Missing the main property?

As previous people have answered npm --save ../location-of-your-packages-root-directory. The ../location-of-your-packages-root-directory however must have two things in order for it to work.

1) package.json in that directory pointed towards

2) main property in the package.json must be set and working i.g. "main": "src/index.js", if the entry file for ../location-of-your-packages-root-directory is ../location-of-your-packages-root-directory/src/index.js

How to save a git commit message from windows cmd?

Press Shift-zz. Saves changes and Quits. Escape didn't work for me.

I am using Git Bash in windows. And couldn't get past this either. My commit messages are simple so I dont want to add another editor atm.

Regex select all text between tags

_x000D_
_x000D_
var str = "Lorem ipsum <pre>text 1</pre> Lorem ipsum <pre>text 2</pre>";_x000D_
    str.replace(/<pre>(.*?)<\/pre>/g, function(match, g1) { console.log(g1); });
_x000D_
_x000D_
_x000D_

Since accepted answer is without javascript code, so adding that:

How to debug .htaccess RewriteRule not working

To answer the first question of the three asked, a simple way to see if the .htaccess file is working or not is to trigger a custom error at the top of the .htaccess file:

ErrorDocument 200 "Hello. This is your .htaccess file talking."
RewriteRule ^ - [L,R=200]

On to your second question, if the .htaccess file is not being read it is possible that the server's main Apache configuration has AllowOverride set to None. Apache's documentation has troubleshooting tips for that and other cases that may be preventing the .htaccess from taking effect.

Finally, to answer your third question, if you need to debug specific variables you are referencing in your rewrite rule or are using an expression that you want to evaluate independently of the rule you can do the following:

Output the variable you are referencing to make sure it has the value you are expecting:

ErrorDocument 200 "Request: %{THE_REQUEST} Referrer: %{HTTP_REFERER} Host: %{HTTP_HOST}"
RewriteRule ^ - [L,R=200]

Test the expression independently by putting it in an <If> Directive. This allows you to make sure your expression is written properly or matching when you expect it to:

<If "%{REQUEST_URI} =~ /word$/">
    ErrorDocument 200 "Your expression is priceless!"
    RewriteRule ^ - [L,R=200]
</If>

Happy .htaccess debugging!

C# Regex for Guid

Most basic regex is following:

(^([0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})$) 

or you could paste it here.

Hope this saves you some time.

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

I had this error. I have a main python script which calls in functions from another, 2nd, python script. At the end of the first script I had a comment block designated with ''' '''. I was getting this error because of this commenting code block. I repeated the error multiple times once I found it to ensure this was the error, & it was. I am still unsure why.

Is it possible only to declare a variable without assigning any value in Python?

First of all, my response to the question you've originally asked

Q: How do I discover if a variable is defined at a point in my code?

A: Read up in the source file until you see a line where that variable is defined.

But further, you've given a code example that there are various permutations of that are quite pythonic. You're after a way to scan a sequence for elements that match a condition, so here are some solutions:

def findFirstMatch(sequence):
    for value in sequence:
        if matchCondition(value):
            return value

    raise LookupError("Could not find match in sequence")

Clearly in this example you could replace the raise with a return None depending on what you wanted to achieve.

If you wanted everything that matched the condition you could do this:

def findAllMatches(sequence):
    matches = []
    for value in sequence:
        if matchCondition(value):
            matches.append(value)

    return matches

There is another way of doing this with yield that I won't bother showing you, because it's quite complicated in the way that it works.

Further, there is a one line way of achieving this:

all_matches = [value for value in sequence if matchCondition(value)]

How to terminate a window in tmux?

Generally:

tmux kill-window -t window-number

So for example, if you are in window 1 and you want to kill window 9:

tmux kill-window -t 9

Sorting int array in descending order

    Comparator<Integer> comparator = new Comparator<Integer>() {

        @Override
        public int compare(Integer o1, Integer o2) {
            return o2.compareTo(o1);
        }
    };

    // option 1
    Integer[] array = new Integer[] { 1, 24, 4, 4, 345 };
    Arrays.sort(array, comparator);

    // option 2
    int[] array2 = new int[] { 1, 24, 4, 4, 345 };
    List<Integer>list = Ints.asList(array2);
    Collections.sort(list, comparator);
    array2 = Ints.toArray(list);

Get top most UIViewController

Based on Dianz answer, the Objective-C version

- (UIViewController *) topViewController {
   UIViewController *baseVC = UIApplication.sharedApplication.keyWindow.rootViewController;
   if ([baseVC isKindOfClass:[UINavigationController class]]) {
       return ((UINavigationController *)baseVC).visibleViewController;
   }

   if ([baseVC isKindOfClass:[UITabBarController class]]) {
       UIViewController *selectedTVC = ((UITabBarController*)baseVC).selectedViewController;
       if (selectedTVC) {
           return selectedTVC;
       }
   }

   if (baseVC.presentedViewController) {
       return baseVC.presentedViewController;
   }
   return baseVC;
}

How to fix Error: this class is not key value coding-compliant for the key tableView.'

You have your storyboard set up to expect an outlet called tableView but the actual outlet name is myTableView.

If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.

What value could I insert into a bit type column?

If you're using SQL Server, you can set the value of bit fields with 0 and 1

or

'true' and 'false' (yes, using strings)

...your_bit_field='false'... => equivalent to 0

wamp server mysql user id and password

WAMP Server – MySQL – Resetting the Root Password (Windows)

  1. Log on to your system as Administrator.

  2. Click on the Wamp server icon > MySQL > MySQL Console

  3. Enter password: LEAVE BLANK AND HIT ENTER

  4. mysql> UPDATE mysql.user SET Password=PASSWORD(‘MyNewPass’) WHERE User=’root’; ENTER Query OK

  5. mysql>FLUSH PRIVILEGES; ENTER mysql>quit ENTER mysql>bye

  6. Edit phpmyadmin file called “config.inc.php” enter ‘MyNewPass’ ($cfg['Servers'][$i]['password'] = ‘MyNewPass‘;)

  7. Restart all services

  8. Clear all cookies – I got the No password error and it was because of the cookies. (ERROR 1045: Access denied for user: ‘root@localhost’ (Using password: NO))

Absolute Positioning & Text Alignment

The div doesn't take up all the available horizontal space when absolutely positioned. Explicitly setting the width to 100% will solve the problem:

HTML

<div id="my-div">I want to be centered</div>?

CSS

#my-div {
   position: absolute;
   bottom: 15px;
   text-align: center;
   width: 100%;
}

?

How to map and remove nil values in Ruby

Definitely compact is the best approach for solving this task. However, we can achieve the same result just with a simple subtraction:

[1, nil, 3, nil, nil] - [nil]
 => [1, 3]

Two arrays in foreach loop

if(isset($_POST['doors'])=== true){
$doors = $_POST['doors'];
}else{$doors = 0;}

if(isset($_POST['windows'])=== true){
$windows = $_POST['windows'];
}else{$windows = 0;}

foreach($doors as $a => $b){

Now you can use $a for each array....

$doors[$a]
$windows[$a]
....
}

How do you set the title color for the new Toolbar?

I struggled with this for a few hours today because all of these answers are kind of out of date now what with MDC and the new theming capabilities I just could not see how to override app:titleTextColor app wide as a style.

The answer is that titleTextColor is available in the styles.xml is you are overriding something that inherits from Widget.AppCompat.Toolbar. Today I think the best choice is supposed to be Widget.MaterialComponents.Toolbar:

<style name="Widget.LL.Toolbar" parent="@style/Widget.MaterialComponents.Toolbar">
     <item name="titleTextAppearance">@style/TextAppearance.LL.Toolbar</item>
     <item name="titleTextColor">@color/white</item>
     <item name="android:background">?attr/colorSecondary</item>
</style>

<style name="TextAppearance.LL.Toolbar" parent="@style/TextAppearance.Widget.AppCompat.Toolbar.Title">
     <item name="android:textStyle">bold</item>
</style>

And in your app theme, specify the toolbarStyle:

<item name="toolbarStyle">@style/Widget.LL.Toolbar</item>

Now you can leave the xml where you specify the tool bar unchanged. For a long time I thought changing the android:textColor in the toolbar title text appearance should be working, but for some reason it does not.

Horizontal line using HTML/CSS

you could also do it this way, in my case i use it before and after an h1 (brute force it ehehehe)

.titleImage::before {
content: "--------";
letter-spacing: -3px;
}

.titreImage::after {
content: "--------";
letter-spacing: -3px;
}

If the letter spacing makes it so the line get in the text just use a margin to push it away!

MySQL error #1054 - Unknown column in 'Field List'

You have an error in your OrderQuantity column. It is named "OrderQuantity" in the INSERT statement and "OrderQantity" in the table definition.

Also, I don't think you can use NOW() as default value in OrderDate. Try to use the following:

 OrderDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

Example Fiddle

How to dynamically build a JSON object with Python?

  • json.loads take a string as input and returns a dictionary as output.
  • json.dumps take a dictionary as input and returns a string as output.

If you need to convert JSON data into a python object, it can do so with Python3, in one line without additional installations, using SimpleNamespace and object_hook:

from string

import json
from types import SimpleNamespace

string = '{"foo":3, "bar":{"x":1, "y":2}}'

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(string, object_hook=lambda d: SimpleNamespace(**d))

print(x.foo)
print(x.bar.x)
print(x.bar.y)

output:

3
1
2

from file:

JSON object: data.json

{
    "foo": 3,
    "bar": {
        "x": 1,
        "y": 2
    }
}
import json
from types import SimpleNamespace

with open("data.json") as fh:
    string = fh.read()

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(string, object_hook=lambda d: SimpleNamespace(**d))

print(x.foo)
print(x.bar.x)
print(x.bar.y)

output:

3
1
2

from requests

import json
from types import SimpleNamespace
import requests

r = requests.get('https://api.github.com/users/MilovanTomasevic')

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(r.text, object_hook=lambda d: SimpleNamespace(**d))

print(x.name)
print(x.company)
print(x.blog)

output:

Milovan Tomaševic
NLB
milovantomasevic.com

For more beautiful and faster access to JSON response from API, take a look at this response.

Make element fixed on scroll

You can go to LESS CSS website http://lesscss.org/

Their dockable menu is light and performs well. The only caveat is that the effect takes place after the scroll is complete. Just do a view source to see the js.

How to detect the swipe left or Right in Android?

If you want to catch the event from the starting of the swipe you can use MotionEvent.ACTION_MOVE and store the first value to compare

private float upX1;
private float upX2;
private float upY1;
private float upY2;
private boolean isTouchCaptured = false;
static final int min_distance = 100;


        viewObject.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE: {
                        downX = event.getX();
                        downY = event.getY();

                        if (!isTouchCaptured) {
                            upX1 = event.getX();
                            upY1 = event.getY();
                            isTouchCaptured = true;
                        } else {
                            upX2 = event.getX();
                            upY2 = event.getY();

                            float deltaX = upX1 - upX2;
                            float deltaY = upY1 - upY2;
                            //HORIZONTAL SCROLL
                            if (Math.abs(deltaX) > Math.abs(deltaY)) {
                                if (Math.abs(deltaX) > min_distance) {
                                    // left or right
                                    if (deltaX < 0) {

                                        return true;
                                    }
                                    if (deltaX > 0) {
                                        return true;
                                    }
                                } else {
                                    //not long enough swipe...
                                    return false;
                                }
                            }
                            //VERTICAL SCROLL
                            else {
                                if (Math.abs(deltaY) > min_distance) {
                                    // top or down
                                    if (deltaY < 0) {

                                        return false;
                                    }
                                    if (deltaY > 0) {

                                        return false;
                                    }
                                } else {
                                    //not long enough swipe...
                                    return false;
                                }
                            }
                        }
                        return false;
                    }
                    case MotionEvent.ACTION_UP: {
                        isTouchCaptured = false;
                    }
                }
                return false;

            }
        });

How to position a div scrollbar on the left hand side?

Kind of an old question, but I thought I should throw in a method which wasn't widely available when this question was asked.

You can reverse the side of the scrollbar in modern browsers using transform: scaleX(-1) on a parent <div>, then apply the same transform to reverse a child, "sleeve" element.

HTML

<div class="parent">
  <div class="sleeve">
    <!-- content -->
  </div>
</div>

CSS

.parent {
  overflow: auto;
  transform: scaleX(-1); //Reflects the parent horizontally
}

.sleeve {
  transform: scaleX(-1); //Flips the child back to normal
}

Note: You may need to use an -ms-transform or -webkit-transform prefix for browsers as old as IE 9. Check CanIUse and click "show all" to see older browser requirements.

How to make a <ul> display in a horizontal row

You could also set them to float to the right.

#ul_top_hypers li {
    float: right;
}

This allows them to still be block level, but will appear on the same line.

Combination of async function + await + setTimeout

Update 2020

You can await setTimeout with Node.js 15 or above:

const timersPromises = require('timers/promises');

(async () => {
  const result = await timersPromises.setTimeout(2000, 'resolved')
  // Executed after 2 seconds
  console.log(result); // "resolved"
})()

Timers Promises API: https://nodejs.org/api/timers.html#timers_timers_promises_api (library already built in Node)


Note: Stability: 1 - Use of the feature is not recommended in production environments.

How to get the unique ID of an object which overrides hashCode()?

// looking for that last hex?
org.joda.DateTime@57110da6

If you're looking into the hashcode Java types when you do a .toString() on an object the underlying code is this:

Integer.toHexString(hashCode())

rsync copy over only certain types of files using include option

The answer by @chepner will copy all the sub-directories irrespective of the fact if it contains the file or not. If you need to exclude the sub-directories that dont contain the file and still retain the directory structure, use

rsync -zarv  --prune-empty-dirs --include "*/"  --include="*.sh" --exclude="*" "$from" "$to"

How do I calculate a trendline for a graph?

Thanks to all for your help - I was off this issue for a couple of days and just came back to it - was able to cobble this together - not the most elegant code, but it works for my purposes - thought I'd share if anyone else encounters this issue:

public class Statistics
{
    public Trendline CalculateLinearRegression(int[] values)
    {
        var yAxisValues = new List<int>();
        var xAxisValues = new List<int>();

        for (int i = 0; i < values.Length; i++)
        {
            yAxisValues.Add(values[i]);
            xAxisValues.Add(i + 1);
        }

        return new Trendline(yAxisValues, xAxisValues);
    }
}

public class Trendline
{
    private readonly IList<int> xAxisValues;
    private readonly IList<int> yAxisValues;
    private int count;
    private int xAxisValuesSum;
    private int xxSum;
    private int xySum;
    private int yAxisValuesSum;

    public Trendline(IList<int> yAxisValues, IList<int> xAxisValues)
    {
        this.yAxisValues = yAxisValues;
        this.xAxisValues = xAxisValues;

        this.Initialize();
    }

    public int Slope { get; private set; }
    public int Intercept { get; private set; }
    public int Start { get; private set; }
    public int End { get; private set; }

    private void Initialize()
    {
        this.count = this.yAxisValues.Count;
        this.yAxisValuesSum = this.yAxisValues.Sum();
        this.xAxisValuesSum = this.xAxisValues.Sum();
        this.xxSum = 0;
        this.xySum = 0;

        for (int i = 0; i < this.count; i++)
        {
            this.xySum += (this.xAxisValues[i]*this.yAxisValues[i]);
            this.xxSum += (this.xAxisValues[i]*this.xAxisValues[i]);
        }

        this.Slope = this.CalculateSlope();
        this.Intercept = this.CalculateIntercept();
        this.Start = this.CalculateStart();
        this.End = this.CalculateEnd();
    }

    private int CalculateSlope()
    {
        try
        {
            return ((this.count*this.xySum) - (this.xAxisValuesSum*this.yAxisValuesSum))/((this.count*this.xxSum) - (this.xAxisValuesSum*this.xAxisValuesSum));
        }
        catch (DivideByZeroException)
        {
            return 0;
        }
    }

    private int CalculateIntercept()
    {
        return (this.yAxisValuesSum - (this.Slope*this.xAxisValuesSum))/this.count;
    }

    private int CalculateStart()
    {
        return (this.Slope*this.xAxisValues.First()) + this.Intercept;
    }

    private int CalculateEnd()
    {
        return (this.Slope*this.xAxisValues.Last()) + this.Intercept;
    }
}

Html Agility Pack get all elements by class

I used this extension method a lot in my project. Hope it will help one of you guys.

public static bool HasClass(this HtmlNode node, params string[] classValueArray)
    {
        var classValue = node.GetAttributeValue("class", "");
        var classValues = classValue.Split(' ');
        return classValueArray.All(c => classValues.Contains(c));
    }

<select> HTML element with height

You can also "center" the text with:

vertical-align: middle;

Android - SMS Broadcast receiver

android.provider.telephony.SMS_RECEIVED is not correct because Telephony is a class and it should be capital as in android.provider.Telephony.SMS_RECEIVED

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

Can I force a UITableView to hide the separator between empty cells?

You can achieve what you want by defining a footer for the tableview. See this answer for more details:Eliminate Extra separators below UITableView

best way to preserve numpy arrays on disk

savez() save data in a zip file, It may take some time to zip & unzip the file. You can use save() & load() function:

f = file("tmp.bin","wb")
np.save(f,a)
np.save(f,b)
np.save(f,c)
f.close()

f = file("tmp.bin","rb")
aa = np.load(f)
bb = np.load(f)
cc = np.load(f)
f.close()

To save multiple arrays in one file, you just need to open the file first, and then save or load the arrays in sequence.

How to append one DataTable to another DataTable

use loop

  for (int i = 0; i < dt1.Rows.Count; i++)
        {      
           dt2.Rows.Add(dt1.Rows[i][0], dt1.Rows[i][1], ...);//you have to insert all Columns...
        }

delete all record from table in mysql

truncate tableName

That is what you are looking for.

Truncate will delete all records in the table, emptying it.

"End of script output before headers" error in Apache

Internal error is due to a HIDDEN character at end of shebang line !! ie line #!/usr/bin/perl

By adding - or -w at end moves the character away from "perl" allowing the path to the perl processor to be found and script to execute.

HIDDEN character is created by the editor used to create the script

The identity used to sign the executable is no longer valid

I have tried many method to solve this problem.But they did not work. Including

  • restart my Xcode or my Mac.
  • delete invalid profiles and generate again.
  • reset Xcode > Preferences > Accounts.
  • update iOS version and Xcode version.

    What finally worked for me is:

register a new apple developer account and add to Xcode

I think maybe my developer account has some problem.

What is CMake equivalent of 'configure --prefix=DIR && make all install '?

Starting with CMake 3.15, the correct way of achieving this would be using:

cmake --install <dir> --prefix "/usr"

Official Documentation

Python write line by line to a text file

Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n and you use \n.

Is it possible to get element from HashMap by its position?

you can use below code to get key : String [] keys = (String[]) item.keySet().toArray(new String[0]);

and get object or list that insert in HashMap with key of this item like this : item.get(keys[position]);

Compare two files in Visual Studio

There is also a Visual Studio extension called CompareFiles, which does nothing else but adding the "Compare Files" entry to the solution explorer context menu. It invokes the built-in Visual Studio diff tool.

Just in case that someone (like me) doesn't want to install an all-in-one extension like VSCommands...

iOS - Calling App Delegate method from ViewController

If someone need the same in Xamarin (Xamarin.ios / Monotouch), this worked for me:

var myDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;

(Require using UIKit;)

org.apache.jasper.JasperException: Unable to compile class for JSP:

The problem is caused because you need to import the pageNumber.Member class in your JSP. Make sure to also include another packages and classes like java.util.List.

<%@ page import="pageNumber.*, java.util.*" %>

Still, you have a major problem by using scriptlets in your JSP. Refer to How to avoid Java Code in JSP-Files? and start practicing EL and JSTL and focusing more on a MVC solution instead.

How to make HTML element resizable using pure Javascript?

See my cross browser compatible resizer.

_x000D_
_x000D_
    <!doctype html>_x000D_
    <html xmlns="http://www.w3.org/1999/xhtml">_x000D_
    <head>_x000D_
        <title>resizer</title>_x000D_
        <meta name="author" content="Andrej Hristoliubov [email protected]">_x000D_
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
        <script type="text/javascript" src="https://rawgit.com/anhr/resizer/master/Common.js"></script>_x000D_
        <script type="text/javascript" src="https://rawgit.com/anhr/resizer/master/resizer.js"></script>_x000D_
        <style>_x000D_
            .element {_x000D_
                border: 1px solid #999999;_x000D_
                border-radius: 4px;_x000D_
                margin: 5px;_x000D_
                padding: 5px;_x000D_
            }_x000D_
        </style>_x000D_
        <script type="text/javascript">_x000D_
            function onresize() {_x000D_
                var element1 = document.getElementById("element1");_x000D_
                var element2 = document.getElementById("element2");_x000D_
                var element3 = document.getElementById("element3");_x000D_
                var ResizerY = document.getElementById("resizerY");_x000D_
                ResizerY.style.top = element3.offsetTop - 15 + "px";_x000D_
                var topElements = document.getElementById("topElements");_x000D_
                topElements.style.height = ResizerY.offsetTop - 20 + "px";_x000D_
                var height = topElements.clientHeight - 32;_x000D_
                if (height < 0)_x000D_
                    height = 0;_x000D_
                height += 'px';_x000D_
                element1.style.height = height;_x000D_
                element2.style.height = height;_x000D_
            }_x000D_
            function resizeX(x) {_x000D_
                //consoleLog("mousemove(X = " + e.pageX + ")");_x000D_
                var element2 = document.getElementById("element2");_x000D_
                element2.style.width =_x000D_
                    element2.parentElement.clientWidth_x000D_
                    + document.getElementById('rezizeArea').offsetLeft_x000D_
                    - x_x000D_
                    + 'px';_x000D_
            }_x000D_
            function resizeY(y) {_x000D_
                //consoleLog("mousemove(Y = " + e.pageY + ")");_x000D_
                var element3 = document.getElementById("element3");_x000D_
                var height =_x000D_
                    element3.parentElement.clientHeight_x000D_
                    + document.getElementById('rezizeArea').offsetTop_x000D_
                    - y_x000D_
                ;_x000D_
                //consoleLog("mousemove(Y = " + e.pageY + ") height = " + height + " element3.parentElement.clientHeight = " + element3.parentElement.clientHeight);_x000D_
                if ((height + 100) > element3.parentElement.clientHeight)_x000D_
                    return;//Limit of the height of the elemtnt 3_x000D_
                element3.style.height = height + 'px';_x000D_
                onresize();_x000D_
            }_x000D_
            var emailSubject = "Resizer example error";_x000D_
        </script>_x000D_
    </head>_x000D_
    <body>_x000D_
        <div id='Message'></div>_x000D_
        <h1>Resizer</h1>_x000D_
        <p>Please see example of resizing of the HTML element by mouse dragging.</p>_x000D_
        <ul>_x000D_
            <li>Drag the red rectangle if you want to change the width of the Element 1 and Element 2</li>_x000D_
            <li>Drag the green rectangle if you want to change the height of the Element 1 Element 2 and Element 3</li>_x000D_
            <li>Drag the small blue square at the left bottom of the Element 2, if you want to resize of the Element 1 Element 2 and Element 3</li>_x000D_
        </ul>_x000D_
        <div id="rezizeArea" style="width:1000px; height:250px; overflow:auto; position: relative;" class="element">_x000D_
            <div id="topElements" class="element" style="overflow:auto; position:absolute; left: 0; top: 0; right:0;">_x000D_
                <div id="element2" class="element" style="width: 30%; height:10px; float: right; position: relative;">_x000D_
                    Element 2_x000D_
                    <div id="resizerXY" style="width: 10px; height: 10px; background: blue; position:absolute; left: 0; bottom: 0;"></div>_x000D_
                    <script type="text/javascript">_x000D_
                        resizerXY("resizerXY", function (e) {_x000D_
                                resizeX(e.pageX + 10);_x000D_
                                resizeY(e.pageY + 50);_x000D_
                            });_x000D_
                    </script>_x000D_
                </div>_x000D_
                <div id="resizerX" style="width: 10px; height:100%; background: red; float: right;"></div>_x000D_
                <script type="text/javascript">_x000D_
                    resizerX("resizerX", function (e) {_x000D_
                        resizeX(e.pageX + 25);_x000D_
                    });_x000D_
                </script>_x000D_
                <div id="element1" class="element" style="height:10px; overflow:auto;">Element 1</div>_x000D_
            </div>_x000D_
            <div id="resizerY" style="height:10px; position:absolute; left: 0; right:0; background: green;"></div>_x000D_
            <script type="text/javascript">_x000D_
                resizerY("resizerY", function (e) {_x000D_
                    resizeY(e.pageY + 25);_x000D_
                });_x000D_
            </script>_x000D_
            <div id="element3" class="element" style="height:100px; position:absolute; left: 0; bottom: 0; right:0;">Element 3</div>_x000D_
        </div>_x000D_
        <script type="text/javascript">_x000D_
            onresize();_x000D_
        </script>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Also see my example of resizer

Open page in new window without popup blocking

For the Submit button, add this code and then set your form target="newwin"

onclick=window.open("about:blank","newwin") 

Can we make unsigned byte in Java

If you have a function which must be passed a signed byte, what do you expect it to do if you pass an unsigned byte?

Why can't you use any other data type?

Unsually you can use a byte as an unsigned byte with simple or no translations. It all depends on how it is used. You would need to clarify what you indend to do with it.

Excel 2013 VBA Clear All Filters macro

This thread is ancient, but I wasn't happy with any of the given answers, and ended up writing my own. I'm sharing it now:

We start with:

  Sub ResetWSFilters(ws as worksheet)
             If ws.FilterMode Then   
     ws.ShowAllData   
     Else   
     End If  
    'This gets rid of "normal" filters - but tables will remain filtered
    For Each listObj In ws.ListObjects 
               If listObj.ShowHeaders Then   
                    listObj.AutoFilter.ShowAllData
                    listObj.Sort.SortFields.Clear    
               End If     
       Next listObj
        'And this gets rid of table filters
        End Sub

We can feed a specific worksheet to this macro which will unfilter just that one worksheet. Useful if you need to make sure just one worksheet is clear. However, I usually want to do the entire workbook

Sub ResetAllWBFilters(wb as workbook)
  Dim ws As Worksheet  
  Dim wb As Workbook  
  Dim listObj As ListObject    

       For Each ws In wb.Worksheets  
          If ws.FilterMode Then 
          ws.ShowAllData  
          Else   
          End If   
 'This removes "normal" filters in the workbook - however, it doesn't remove table filters           
   For Each listObj In ws.ListObjects 
        If listObj.ShowHeaders Then   
             listObj.AutoFilter.ShowAllData 
             listObj.Sort.SortFields.Clear    
        End If     
   Next listObj

        Next   
'And this removes table filters. You need both aspects to make it work.  
    End Sub

You can use this, by, for example, opening a workbook you need to deal with and resetting their filters before doing anything with it:

Sub ExampleOpen()
Set TestingWorkBook = Workbooks.Open("C:\Intel\......") 'The .open is assuming you need to open the workbook in question - different procedure if it's already open
Call ResetAllWBFilters(TestingWorkBook)
End Sub

The one I use the most: Resetting all filters in the workbook that the module is stored in:

Sub ResetFilters()
      Dim ws As Worksheet  
      Dim wb As Workbook  
      Dim listObj As ListObject  
       Set wb = ThisWorkbook  
       'Set wb = ActiveWorkbook
       'This is if you place the macro in your personal wb to be able to reset the filters on any wb you're currently working on. Remove the set wb = thisworkbook if that's what you need
           For Each ws In wb.Worksheets  
              If ws.FilterMode Then 
              ws.ShowAllData  
              Else   
              End If   
     'This removes "normal" filters in the workbook - however, it doesn't remove table filters           
       For Each listObj In ws.ListObjects 
            If listObj.ShowHeaders Then   
                 listObj.AutoFilter.ShowAllData 
                 listObj.Sort.SortFields.Clear    
            End If     
       Next listObj

            Next   
'And this removes table filters. You need both aspects to make it work.  
    End Sub

.htaccess rewrite to redirect root URL to subdirectory

I'll answer the original question not by pointing out another possible syntax (there are many amongst the other answers) but by pointing out something I have once had to deal with, that took me a while to figure out:

What am I doing wrong?

There is a possibility that %{HTTP_HOST} is not being populated properly, or at all. Although, I've only seen that occur in only one machine on a shared host, with some custom patched apache 2.2, it's a possibility nonetheless.

Append Char To String in C?

To append a char to a string in C, you first have to ensure that the memory buffer containing the string is large enough to accomodate an extra character. In your example program, you'd have to allocate a new, additional, memory block because the given literal string cannot be modified.

Here's a sample:

#include <stdlib.h>

int main()
{
    char *str = "blablabla";
    char c = 'H';

    size_t len = strlen(str);
    char *str2 = malloc(len + 1 + 1 ); /* one for extra char, one for trailing zero */
    strcpy(str2, str);
    str2[len] = c;
    str2[len + 1] = '\0';

    printf( "%s\n", str2 ); /* prints "blablablaH" */

    free( str2 );
}

First, use malloc to allocate a new chunk of memory which is large enough to accomodate all characters of the input string, the extra char to append - and the final zero. Then call strcpy to copy the input string into the new buffer. Finally, change the last two bytes in the new buffer to tack on the character to add as well as the trailing zero.

How to get absolute value from double - c-language

I have found that using cabs(double), cabsf(float), cabsl(long double), __cabsf(float), __cabs(double), __cabsf(long double) is the solution

SQLAlchemy: how to filter date field?

In fact, your query is right except for the typo: your filter is excluding all records: you should change the <= for >= and vice versa:

qry = DBSession.query(User).filter(
        and_(User.birthday <= '1988-01-17', User.birthday >= '1985-01-17'))
# or same:
qry = DBSession.query(User).filter(User.birthday <= '1988-01-17').\
        filter(User.birthday >= '1985-01-17')

Also you can use between:

qry = DBSession.query(User).filter(User.birthday.between('1985-01-17', '1988-01-17'))

How to preview an image before and after upload?

Try this: (For Preview)

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

<body>
    <form id="form1" runat="server">
        <input type="file" onchange="readURL(this);" />
        <img id="blah" src="#" alt="your image" />
    </form>
</body>

Working Demo here>

Platform.runLater and Task in JavaFX

One reason to use an explicite Platform.runLater() could be that you bound a property in the ui to a service (result) property. So if you update the bound service property, you have to do this via runLater():

In UI thread also known as the JavaFX Application thread:

...    
listView.itemsProperty().bind(myListService.resultProperty());
...

in Service implementation (background worker):

...
Platform.runLater(() -> result.add("Element " + finalI));
...

Excel formula to display ONLY month and year?

Very easy, trial and error. Go to the cell you want the month in. Type the Month, go to the next cell and type the year, something weird will come up but then go to your number section click on the little arrow in the right bottom and highlight text and it will change to the year you originally typed

What is the difference between a .cpp file and a .h file?

.h files, or header files, are used to list the publicly accessible instance variables and and methods in the class declaration. .cpp files, or implementation files, are used to actually implement those methods and use those instance variables.

The reason they are separate is because .h files aren't compiled into binary code while .cpp files are. Take a library, for example. Say you are the author and you don't want it to be open source. So you distribute the compiled binary library and the header files to your customers. That allows them to easily see all the information about your library's classes they can use without being able to see how you implemented those methods. They are more for the people using your code rather than the compiler. As was said before: it's the convention.

Adding System.Web.Script reference in class library

You need to add a reference to System.Web.Extensions.dll in project for System.Web.Script.Serialization error.

Make a VStack fill the width of the screen in SwiftUI

I know this will not work for everyone, but I thought it interesting that just adding a Divider solves for this.

struct DividerTest: View {
var body: some View {
    VStack(alignment: .leading) {
        Text("Foo")
        Text("Bar")
        Divider()
    }.background(Color.red)
  }
}

jQuery add class .active on menu

<script type="text/javascript">
    jQuery(document).ready(function($) {
    var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); 
    $("#navbar li a").each(function() {//alert('dsfgsdgfd');
    if(urlRegExp.test(this.href.replace(/\/$/,''))){
    $(this).addClass("active");}
});
}); 
</script>

How to find the foreach index?

It should be noted that you can call key() on any array to find the current key its on. As you can guess current() will return the current value and next() will move the array's pointer to the next element.

What is the best way to prevent session hijacking?

The SSL only helps with sniffing attacks. If an attacker has access to your machine I will assume they can copy your secure cookie too.

At the very least, make sure old cookies lose their value after a while. Even a successful hijaking attack will be thwarted when the cookie stops working. If the user has a cookie from a session that logged in more than a month ago, make them reenter their password. Make sure that whenever a user clicks on your site's "log out" link, that the old session UUID can never be used again.

I'm not sure if this idea will work but here goes: Add a serial number into your session cookie, maybe a string like this:

SessionUUID, Serial Num, Current Date/Time

Encrypt this string and use it as your session cookie. Regularly change the serial num - maybe when the cookie is 5 minutes old and then reissue the cookie. You could even reissue it on every page view if you wanted to. On the server side, keep a record of the last serial num you've issued for that session. If someone ever sends a cookie with the wrong serial number it means that an attacker may be using a cookie they intercepted earlier so invalidate the session UUID and ask the user to reenter their password and then reissue a new cookie.

Remember that your user may have more than one computer so they may have more than one active session. Don't do something that forces them to log in again every time they switch between computers.

Python: Get relative path from comparing two absolute paths

os.path.relpath:

Return a relative filepath to path either from the current directory or from an optional start point.

>>> from os.path import relpath
>>> relpath('/usr/var/log/', '/usr/var')
'log'
>>> relpath('/usr/var/log/', '/usr/var/sad/')
'../log'

So, if relative path starts with '..' - it means that the second path is not descendant of the first path.

In Python3 you can use PurePath.relative_to:

Python 3.5.1 (default, Jan 22 2016, 08:54:32)
>>> from pathlib import Path

>>> Path('/usr/var/log').relative_to('/usr/var/log/')
PosixPath('.')

>>> Path('/usr/var/log').relative_to('/usr/var/')
PosixPath('log')

>>> Path('/usr/var/log').relative_to('/etc/')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/pathlib.py", line 851, in relative_to
    .format(str(self), str(formatted)))
ValueError: '/usr/var/log' does not start with '/etc'

PreparedStatement with Statement.RETURN_GENERATED_KEYS

String query = "INSERT INTO ....";
PreparedStatement preparedStatement = connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);

preparedStatement.setXXX(1, VALUE); 
preparedStatement.setXXX(2, VALUE); 
....
preparedStatement.executeUpdate();  

ResultSet rs = preparedStatement.getGeneratedKeys();  
int key = rs.next() ? rs.getInt(1) : 0;

if(key!=0){
    System.out.println("Generated key="+key);
}

Make Vim show ALL white spaces as a character

You could use

:set list

to really see the structure of a line. You will see tabs and newlines explicitly. When you see a blank, it's really a blank.

Connection timeout for SQL server

Hmmm...

As Darin said, you can specify a higher connection timeout value, but I doubt that's really the issue.

When you get connection timeouts, it's typically a problem with one of the following:

  1. Network configuration - slow connection between your web server/dev box and the SQL server. Increasing the timeout may correct this, but it'd be wise to investigate the underlying problem.

  2. Connection string. I've seen issues where an incorrect username/password will, for some reason, give a timeout error instead of a real error indicating "access denied." This shouldn't happen, but such is life.

  3. Connection String 2: If you're specifying the name of the server incorrectly, or incompletely (for instance, mysqlserver instead of mysqlserver.webdomain.com), you'll get a timeout. Can you ping the server using the server name exactly as specified in the connection string from the command line?

  4. Connection string 3 : If the server name is in your DNS (or hosts file), but the pointing to an incorrect or inaccessible IP, you'll get a timeout rather than a machine-not-found-ish error.

  5. The query you're calling is timing out. It can look like the connection to the server is the problem, but, depending on how your app is structured, you could be making it all the way to the stage where your query is executing before the timeout occurs.

  6. Connection leaks. How many processes are running? How many open connections? I'm not sure if raw ADO.NET performs connection pooling, automatically closes connections when necessary ala Enterprise Library, or where all that is configured. This is probably a red herring. When working with WCF and web services, though, I've had issues with unclosed connections causing timeouts and other unpredictable behavior.

Things to try:

  1. Do you get a timeout when connecting to the server with SQL Management Studio? If so, network config is likely the problem. If you do not see a problem when connecting with Management Studio, the problem will be in your app, not with the server.

  2. Run SQL Profiler, and see what's actually going across the wire. You should be able to tell if you're really connecting, or if a query is the problem.

  3. Run your query in Management Studio, and see how long it takes.

Good luck!

Git - Ignore node_modules folder everywhere

it will automatically create a .gitignore file if not then create a file name .gitignore and add copy & paste the below code

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*

these below are all unnecessary files

See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

and save the .gitignore file and you can upload

WPF button click in C# code

The following should do the trick:

btn.Click += btn1_Click;

Is it possible to set UIView border properties from interface builder?

For Swift 3 and 4, if you're willing to use IBInspectables, there's this:

@IBDesignable extension UIView {
    @IBInspectable var borderColor:UIColor? {
        set {
            layer.borderColor = newValue!.cgColor
        }
        get {
            if let color = layer.borderColor {
                return UIColor(cgColor: color)
            }
            else {
                return nil
            }
        }
    }
    @IBInspectable var borderWidth:CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }
    @IBInspectable var cornerRadius:CGFloat {
        set {
            layer.cornerRadius = newValue
            clipsToBounds = newValue > 0
        }
        get {
            return layer.cornerRadius
        }
    }
}

Python error: AttributeError: 'module' object has no attribute

My solution is put those imports in __init__.py of lib:

in file: __init__.py
import mod1

Then,

import lib
lib.mod1

would work fine.

What is the best IDE to develop Android apps in?

Eclipse is the most widely used development environment for the Android platform. The reason is that even Google itself providing the plug-in to be added in eclipse and start developing the applications. I have tried installing it from the eclipse market place, it is very easy and simple to create the android application. set up also very simple.

What is the meaning of single and double underscore before an object name?

Since so many people are referring to Raymond's talk, I'll just make it a little easier by writing down what he said:

The intention of the double underscores was not about privacy. The intention was to use it exactly like this

class Circle(object):

    def __init__(self, radius):
        self.radius = radius

    def area(self):
        p = self.__perimeter()
        r = p / math.pi / 2.0
        return math.pi * r ** 2.0

    def perimeter(self):
        return 2.0 * math.pi * self.radius

    __perimeter = perimeter  # local reference


class Tire(Circle):

    def perimeter(self):
        return Circle.perimeter(self) * 1.25

It's actually the opposite of privacy, it's all about freedom. It makes your subclasses free to override any one method without breaking the others.

Say you don't keep a local reference of perimeter in Circle. Now, a derived class Tire overrides the implementation of perimeter, without touching area. When you call Tire(5).area(), in theory it should still be using Circle.perimeter for computation, but in reality it's using Tire.perimeter, which is not the intended behavior. That's why we need a local reference in Circle.

But why __perimeter instead of _perimeter? Because _perimeter still gives derived class the chance to override:

class Tire(Circle):

    def perimeter(self):
        return Circle.perimeter(self) * 1.25

    _perimeter = perimeter

Double underscores has name mangling, so there's a very little chance that the local reference in parent class get override in derived class. thus "makes your subclasses free to override any one method without breaking the others".

If your class won't be inherited, or method overriding does not break anything, then you simply don't need __double_leading_underscore.

How to erase the file contents of text file in Python?

Not a complete answer more of an extension to ondra's answer

When using truncate() ( my preferred method ) make sure your cursor is at the required position. When a new file is opened for reading - open('FILE_NAME','r') it's cursor is at 0 by default. But if you have parsed the file within your code, make sure to point at the beginning of the file again i.e truncate(0) By default truncate() truncates the contents of a file starting from the current cusror position.

A simple example

Cast Int to enum in Java

In Kotlin:

enum class Status(val id: Int) {
    NEW(0), VISIT(1), IN_WORK(2), FINISHED(3), CANCELLED(4), DUMMY(5);

    companion object {
        private val statuses = Status.values().associateBy(Status::id)

        fun getStatus(id: Int): Status? = statuses[id]
    }
}

Usage:

val status = Status.getStatus(1)!!

Align two inline-blocks left and right on same line

If you're already using JavaScript to center stuff when the screen is too small (as per your comment for your header), why not just undo floats/margins with JavaScript while you're at it and use floats and margins normally.

You could even use CSS media queries to reduce the amount JavaScript you're using.

How to put a jar in classpath in Eclipse?

Right click your project in eclipse, build path -> add external jars.

How to get TimeZone from android mobile?

I needed the offset that not only included day light savings time but as a numerial. Here is the code that I used in case someone is looking for an example.

I get a response of "3.5" (3:30') which is what I would expect in Tehran , Iran in winter and "4.5" (4:30') for summer .

I also needed it as a string so I could post it to a server so you may not need the last line.

for getting currect time zone :

TimeZone tz = TimeZone.getDefault();
Date now = new Date();
//Import part : x.0 for double number
double offsetFromUtc = tz.getOffset(now.getTime()) / 3600000.0;
String m2tTimeZoneIs = Double.parseDouble(offsetFromUtc);

How can I add a column that doesn't allow nulls in a Postgresql database?

You either need to define a default, or do what Sean says and add it without the null constraint until you've filled it in on the existing rows.

Set timeout for ajax (jQuery)

You could use the timeout setting in the ajax options like this:

$.ajax({
    url: "test.html",
    timeout: 3000,
    error: function(){
        //do something
    },
    success: function(){
        //do something
    }
});

Read all about the ajax options here: http://api.jquery.com/jQuery.ajax/

Remember that when a timeout occurs, the error handler is triggered and not the success handler :)

Responsive bootstrap 3 timepicker?

This is a slightly modified version of http://jdewit.github.io/bootstrap-timepicker/ which supports bootstrap 3. You can check it out here. https://github.com/m3wolf/bootstrap3-timepicker Let me know if it does not work and I will try to find an alternative.

Update. Here is another one based off of the same version, but modified for bootstrap 3. https://github.com/rendom/bootstrap-3-timepicker

Update 2. Here is yet another one. http://bootstrapformhelpers.com/timepicker/

Anaconda version with Python 3.5

According to the official docu it's recommended to downgrade the whole Python environment:

conda install python=3.5

Add text to Existing PDF using Python

I know this is an older post, but I spent a long time trying to find a solution. I came across a decent one using only ReportLab and PyPDF so I thought I'd share:

  1. read your PDF using PdfFileReader(), we'll call this input
  2. create a new pdf containing your text to add using ReportLab, save this as a string object
  3. read the string object using PdfFileReader(), we'll call this text
  4. create a new PDF object using PdfFileWriter(), we'll call this output
  5. iterate through input and apply .mergePage(*text*.getPage(0)) for each page you want the text added to, then use output.addPage() to add the modified pages to a new document

This works well for simple text additions. See PyPDF's sample for watermarking a document.

Here is some code to answer the question below:

packet = StringIO.StringIO()
can = canvas.Canvas(packet, pagesize=letter)
<do something with canvas>
can.save()
packet.seek(0)
input = PdfFileReader(packet)

From here you can merge the pages of the input file with another document.

Get first element from a dictionary

convert to Array

var array = like.ToArray();
var first = array[0];

How to add soap header in java

i was facing the same issue and solved it by removing the xmlns:wsu attribute.Try not adding it in the usernameToken.Hope this solves your issue too.

jquery, selector for class within id

Always use

//Super Fast
$('#my_id').find('.my_class'); 

instead of

// Fast:
$('#my_id .my_class');

Have look at JQuery Performance Rules.

Also at Jquery Doc

Trigger to fire only if a condition is met in SQL Server

CREATE TRIGGER
    [dbo].[SystemParameterInsertUpdate]
ON 
    [dbo].[SystemParameter]
FOR INSERT, UPDATE 
AS
  BEGIN
    SET NOCOUNT ON 

    DECLARE @StartRow int
    DECLARE @EndRow int
    DECLARE @CurrentRow int

    SET @StartRow = 1
    SET @EndRow = (SELECT count(*) FROM inserted)
    SET @CurrentRow = @StartRow

    WHILE @CurrentRow <= @EndRow BEGIN

        IF (SELECT Attribute FROM (SELECT ROW_NUMBER() OVER (ORDER BY Attribute ASC) AS 'RowNum', Attribute FROM inserted) AS INS WHERE RowNum = @CurrentRow) LIKE 'NoHist_%' BEGIN

            INSERT INTO SystemParameterHistory(
                Attribute,
                ParameterValue,
                ParameterDescription,
                ChangeDate)
            SELECT
                I.Attribute,
                I.ParameterValue,
                I.ParameterDescription,
                I.ChangeDate
            FROM
                (SELECT Attribute, ParameterValue, ParameterDescription, ChangeDate FROM (
                                                                                            SELECT ROW_NUMBER() OVER (ORDER BY Attribute ASC) AS 'RowNum', * 
                                                                                            FROM inserted)
                                                                                    AS I 
            WHERE RowNum = @CurrentRow

        END --END IF

    SET @CurrentRow = @CurrentRow + 1

    END --END WHILE
END --END TRIGGER

How do I configure php to enable pdo and include mysqli on CentOS?

You might just have to install the packages.

yum install php-pdo php-mysqli

After they're installed, restart Apache.

httpd restart

or

apachectl restart

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

Apparently this is by design. When Safari (OS X or iOS) is in private browsing mode, it appears as though localStorage is available, but trying to call setItem throws an exception.

store.js line 73
"QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

What happens is that the window object still exposes localStorage in the global namespace, but when you call setItem, this exception is thrown. Any calls to removeItem are ignored.

I believe the simplest fix (although I haven't tested this cross browser yet) would be to alter the function isLocalStorageNameSupported() to test that you can also set some value.

https://github.com/marcuswestin/store.js/issues/42

function isLocalStorageNameSupported() 
{
    var testKey = 'test', storage = window.sessionStorage;
    try 
    {
        storage.setItem(testKey, '1');
        storage.removeItem(testKey);
        return localStorageName in win && win[localStorageName];
    } 
    catch (error) 
    {
        return false;
    }
}

How do I bind a List<CustomObject> to a WPF DataGrid?

You should do it in the xaml code:

<DataGrid ItemsSource="{Binding list}" [...]>
  [...]
</DataGrid>

I would advise you to use an ObservableCollection as your backing collection, as that would propagate changes to the datagrid, as it implements INotifyCollectionChanged.

Java converting int to hex and back again

As Integer.toHexString(byte/integer) is not working when you are trying to convert signed bytes like UTF-16 decoded characters you have to use:

Integer.toString(byte/integer, 16);

or

String.format("%02X", byte/integer);

reverse you can use

Integer.parseInt(hexString, 16);

How to generate random number with the specific length in python

I really liked the answer of RichieHindle, however I liked the question as an exercise. Here's a brute force implementation using strings:)

import random
first = random.randint(1,9)
first = str(first)
n = 5

nrs = [str(random.randrange(10)) for i in range(n-1)]
for i in range(len(nrs))    :
    first += str(nrs[i])

print str(first)

How many bytes is unsigned long long?

The beauty of C++, like C, is that the sized of these things are implementation-defined, so there's no correct answer without your specifying the compiler you're using. Are those two the same? Yes. "long long" is a synonym for "long long int", for any compiler that will accept both.

Why doesn't CSS ellipsis work in table cell?

Check box-sizing css property of your td elements. I had problem with css template which sets it to border-box value. You need set box-sizing: content-box.

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

The way I solved it on different computers:

I have a Windows 7 32bit machine with Visual Studio 2012 which did not have the Access Database because I do not have the Office 2010. I copied the same source I had in my Windows 7 64bit machine.

So, I installed the AccessDatabaseEngine into this Windows 7 32 bit machine after downloading it per above suggestions from others here and everything worked fine.

I still had the problem on my Windows 7 64 bit machine which already has Office 2010 that already includes Access 2010. The way I solved on this computer was by going into the PROJECT, selected Properties, and at Platform target had Any CPU I checked Prefer 32-bit. Recompiled/Build and the Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine message was gone.

Safely casting long to int in Java

DONT: This is not a solution!

My first approach was:

public int longToInt(long theLongOne) {
  return Long.valueOf(theLongOne).intValue();
}

But that merely just casts the long to an int, potentially creating new Long instances or retrieving them from the Long pool.


The drawbacks

  1. Long.valueOf creates a new Long instance if the number is not within Long's pool range [-128, 127].

  2. The intValue implementation does nothing more than:

    return (int)value;
    

So this can be considered even worse than just casting the long to int.

Reading a UTF8 CSV file with Python

Also checkout the answer in this post: https://stackoverflow.com/a/9347871/1338557

It suggests use of library called ucsv.py. Short and simple replacement for CSV written to address the encoding problem(utf-8) for Python 2.7. Also provides support for csv.DictReader

Edit: Adding sample code that I used:

import ucsv as csv

#Read CSV file containing the right tags to produce
fileObj = open('awol_title_strings.csv', 'rb')
dictReader = csv.DictReader(fileObj, fieldnames = ['titles', 'tags'], delimiter = ',', quotechar = '"')
#Build a dictionary from the CSV file-> {<string>:<tags to produce>}
titleStringsDict = dict()
for row in dictReader:
    titleStringsDict.update({unicode(row['titles']):unicode(row['tags'])})

How to compare dates in datetime fields in Postgresql?

Use the range type. If the user enter a date:

select *
from table
where
    update_date
    <@
    tsrange('2013-05-03', '2013-05-03'::date + 1, '[)');

If the user enters timestamps then you don't need the ::date + 1 part

http://www.postgresql.org/docs/9.2/static/rangetypes.html

http://www.postgresql.org/docs/9.2/static/functions-range.html

Twitter Bootstrap Responsive Background-Image inside Div

The way to do this is by using background-size so in your case:

background-size: 50% 50%;

or

You can set the width and the height of the elements to percentages as well

How to use ADB to send touch events to device using sendevent command?

Android comes with an input command-line tool that can simulate miscellaneous input events. To simulate tapping, it's:

input tap x y

You can use the adb shell ( > 2.3.5) to run the command remotely:

adb shell input tap x y

How to select the first, second, or third element with a given class name?

You probably finally realized this between posting this question and today, but the very nature of selectors makes it impossible to navigate through hierarchically unrelated HTML elements.

Or, to put it simply, since you said in your comment that

there are no uniform parent containers

... it's just not possible with selectors alone, without modifying the markup in some way as shown by the other answers.

You have to use the jQuery .eq() solution.

Couldn't connect to server 127.0.0.1:27017

1.Create new folder in d drive D:/data/db

2.Open terminal on D:/data/db

3.Type mongod and enter.

4.Type mongo and enter.

and your mongodb has strated............

TABLOCK vs TABLOCKX

Quite an old article on mssqlcity attempts to explain the types of locks:

Shared locks are used for operations that do not change or update data, such as a SELECT statement.

Update locks are used when SQL Server intends to modify a page, and later promotes the update page lock to an exclusive page lock before actually making the changes.

Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or DELETE.

What it doesn't discuss are Intent (which basically is a modifier for these lock types). Intent (Shared/Exclusive) locks are locks held at a higher level than the real lock. So, for instance, if your transaction has an X lock on a row, it will also have an IX lock at the table level (which stops other transactions from attempting to obtain an incompatible lock at a higher level on the table (e.g. a schema modification lock) until your transaction completes or rolls back).


The concept of "sharing" a lock is quite straightforward - multiple transactions can have a Shared lock for the same resource, whereas only a single transaction may have an Exclusive lock, and an Exclusive lock precludes any transaction from obtaining or holding a Shared lock.

Expression must be a modifiable lvalue

You test k = M instead of k == M.
Maybe it is what you want to do, in this case, write if (match == 0 && (k = M))

Linux / Bash, using ps -o to get process by specific name?

This is a bit old, but I guess what you want is: ps -o pid -C PROCESS_NAME, for example:

ps -o pid -C bash

EDIT: Dependening on the sort of output you expect, pgrep would be more elegant. This, in my knowledge, is Linux specific and result in similar output as above. For example:

pgrep bash

Comments in .gitignore?

Yes, you may put comments in there. They however must start at the beginning of a line.

cf. http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Ignoring-Files

The rules for the patterns you can put in the .gitignore file are as follows:
- Blank lines or lines starting with # are ignored.
[…]

The comment character is #, example:

# no .a files
*.a

How to color System.out.println output?

No, but there are third party API's that can handle it

http://www.javaworld.com/javaworld/javaqa/2002-12/02-qa-1220-console.html

Edit: of course there are newer articles than that one I posted, the information is still viable though.

How to sleep the thread in node.js without affecting other threads?

When working with async functions or observables provided by 3rd party libraries, for example Cloud firestore, I've found functions the waitFor method shown below (TypeScript, but you get the idea...) to be helpful when you need to wait on some process to complete, but you don't want to have to embed callbacks within callbacks within callbacks nor risk an infinite loop.

This method is sort of similar to a while (!condition) sleep loop, but yields asynchronously and performs a test on the completion condition at regular intervals till true or timeout.

export const sleep = (ms: number) => {
    return new Promise(resolve => setTimeout(resolve, ms))
}
/**
 * Wait until the condition tested in a function returns true, or until 
 * a timeout is exceeded.
 * @param interval The frenequency with which the boolean function contained in condition is called.
 * @param timeout  The maximum time to allow for booleanFunction to return true
 * @param booleanFunction:  A completion function to evaluate after each interval. waitFor will return true as soon as the completion function returns true.   
 */
export const waitFor = async function (interval: number, timeout: number,
    booleanFunction: Function): Promise<boolean> {
    let elapsed = 1;
    if (booleanFunction()) return true;
    while (elapsed < timeout) {
        elapsed += interval;
        await sleep(interval);
        if (booleanFunction()) {
            return true;
        }
    }
    return false;
}

The say you have a long running process on your backend you want to complete before some other task is undertaken. For example if you have a function that totals a list of accounts, but you want to refresh the accounts from the backend before you calculate, you can do something like this:

async recalcAccountTotals() : number {
     this.accountService.refresh();   //start the async process.
     if (this.accounts.dirty) {
           let updateResult = await waitFor(100,2000,()=> {return !(this.accounts.dirty)})
     }
 if(!updateResult) { 
      console.error("Account refresh timed out, recalc aborted");
      return NaN;
    }
 return ... //calculate the account total. 
}

Get client IP address via third party web service

Checking your linked site, you may include a script tag passing a ?var=desiredVarName parameter which will be set as a global variable containing the IP address:

<script type="text/javascript" src="http://l2.io/ip.js?var=myip"></script>
                                                      <!-- ^^^^ -->
<script>alert(myip);</script>

Demo

I believe I don't have to say that this can be easily spoofed (through either use of proxies or spoofed request headers), but it is worth noting in any case.


HTTPS support

In case your page is served using the https protocol, most browsers will block content in the same page served using the http protocol (that includes scripts and images), so the options are rather limited. If you have < 5k hits/day, the Smart IP API can be used. For instance:

<script>
var myip;
function ip_callback(o) {
    myip = o.host;
}
</script>
<script src="https://smart-ip.net/geoip-json?callback=ip_callback"></script>
<script>alert(myip);</script>

Demo

Edit: Apparently, this https service's certificate has expired so the user would have to add an exception manually. Open its API directly to check the certificate state: https://smart-ip.net/geoip-json


With back-end logic

The most resilient and simple way, in case you have back-end server logic, would be to simply output the requester's IP inside a <script> tag, this way you don't need to rely on external resources. For example:

PHP:

<script>var myip = '<?php echo $_SERVER['REMOTE_ADDR']; ?>';</script>

There's also a more sturdy PHP solution (accounting for headers that are sometimes set by proxies) in this related answer.

C#:

<script>var myip = '<%= Request.UserHostAddress %>';</script>

Could not load file or assembly 'System.Data.SQLite'

This is very simple if you are not using SQLite:

You can delete the SQLite DLLs from your solution's bin folders, then from the folder where you reference ELMAH. Rebuild, and your app won't try to load this DLL that you are not using.

Counting inversions in an array

The easy O(n^2) answer is to use nested for-loops and increment a counter for every inversion

int counter = 0;

for(int i = 0; i < n - 1; i++)
{
    for(int j = i+1; j < n; j++)
    {
        if( A[i] > A[j] )
        {
            counter++;
        }
    }
}

return counter;

Now I suppose you want a more efficient solution, I'll think about it.

How to get script of SQL Server data?

BCP can dump your data to a file and in SQL Server Management Studio, right click on the table, and select "script table as" then "create to", then "file..." and it will produce a complete table script.

BCP info
https://web.archive.org/web/1/http://blogs.techrepublic%2ecom%2ecom/datacenter/?p=319
http://msdn.microsoft.com/en-us/library/aa174646%28SQL.80%29.aspx

Refresh Page and Keep Scroll Position

This might be useful for refreshing also. But if you want to keep track of position on the page before you click on a same position.. The following code will help.

Also added a data-confirm for prompting the user if they really want to do that..

Note: I'm using jQuery and js-cookie.js to store cookie info.

$(document).ready(function() {
    // make all links with data-confirm prompt the user first.
    $('[data-confirm]').on("click", function (e) {
        e.preventDefault();
        var msg = $(this).data("confirm");
        if(confirm(msg)==true) {
            var url = this.href;
            if(url.length>0) window.location = url;
            return true;
        }
        return false;
    });

    // on certain links save the scroll postion.
    $('.saveScrollPostion').on("click", function (e) {
        e.preventDefault();
        var currentYOffset = window.pageYOffset;  // save current page postion.
        Cookies.set('jumpToScrollPostion', currentYOffset);
        if(!$(this).attr("data-confirm")) {  // if there is no data-confirm on this link then trigger the click. else we have issues.
            var url = this.href;
            window.location = url;
            //$(this).trigger('click');  // continue with click event.
        }
    });

    // check if we should jump to postion.
    if(Cookies.get('jumpToScrollPostion') !== "undefined") {
        var jumpTo = Cookies.get('jumpToScrollPostion');
        window.scrollTo(0, jumpTo);
        Cookies.remove('jumpToScrollPostion');  // and delete cookie so we don't jump again.
    }
});

A example of using it like this.

<a href='gotopage.html' class='saveScrollPostion' data-confirm='Are you sure?'>Goto what the heck</a>

What is the simplest way to convert array to vector?

Use the vector constructor that takes two iterators, note that pointers are valid iterators, and use the implicit conversion from arrays to pointers:

int x[3] = {1, 2, 3};
std::vector<int> v(x, x + sizeof x / sizeof x[0]);
test(v);

or

test(std::vector<int>(x, x + sizeof x / sizeof x[0]));

where sizeof x / sizeof x[0] is obviously 3 in this context; it's the generic way of getting the number of elements in an array. Note that x + sizeof x / sizeof x[0] points one element beyond the last element.

The APK file does not exist on disk

I got it to work by:

  1. Closing the project
  2. From the Android Studio Welcome Window (or File > New), click on Import Project.

I guess that forced it to reinstall the APK, and now everything is running fine.

How/When does Execute Shell mark a build as failure in Jenkins?

In my opinion, turning off the -e option to your shell is a really bad idea. Eventually one of the commands in your script will fail due to transient conditions like out of disk space or network errors. Without -e Jenkins won't notice and will continue along happily. If you've got Jenkins set up to do deployment, that may result in bad code getting pushed and bringing down your site.

If you have a line in your script where failure is expected, like a grep or a find, then just add || true to the end of that line. That ensures that line will always return success.

If you need to use that exit code, you can either hoist the command into your if statement:

grep foo bar; if [ $? == 0 ]; then ...    -->   if grep foo bar; then ...

Or you can capture the return code in your || clause:

grep foo bar || ret=$?

Compute mean and standard deviation by group for multiple variables in a data.frame

I add the dplyr solution.

set.seed(1)
df <- data.frame(ID=rep(1:3, 3), Obs_1=rnorm(9), Obs_2=rnorm(9), Obs_3=rnorm(9))

library(dplyr)
df %>% group_by(ID) %>% summarise_each(funs(mean, sd))

#      ID Obs_1_mean Obs_2_mean Obs_3_mean  Obs_1_sd  Obs_2_sd  Obs_3_sd
#   (int)      (dbl)      (dbl)      (dbl)     (dbl)     (dbl)     (dbl)
# 1     1  0.4854187 -0.3238542  0.7410611 1.1108687 0.2885969 0.1067961
# 2     2  0.4171586 -0.2397030  0.2041125 0.2875411 1.8732682 0.3438338
# 3     3 -0.3601052  0.8195368 -0.4087233 0.8105370 0.3829833 1.4705692

How to return history of validation loss in Keras

I have also found that you can use verbose=2 to make keras print out the Losses:

history = model.fit(X, Y, validation_split=0.33, nb_epoch=150, batch_size=10, verbose=2)

And that would print nice lines like this:

Epoch 1/1
 - 5s - loss: 0.6046 - acc: 0.9999 - val_loss: 0.4403 - val_acc: 0.9999

According to their documentation:

verbose: 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch.

What is the difference between an expression and a statement in Python?

Expressions only contain identifiers, literals and operators, where operators include arithmetic and boolean operators, the function call operator () the subscription operator [] and similar, and can be reduced to some kind of "value", which can be any Python object. Examples:

3 + 5
map(lambda x: x*x, range(10))
[a.x for a in some_iterable]
yield 7

Statements (see 1, 2), on the other hand, are everything that can make up a line (or several lines) of Python code. Note that expressions are statements as well. Examples:

# all the above expressions
print 42
if x: do_y()
return
a = 7

Representing Directory & File Structure in Markdown Syntax

I followed an example in another repository and wrapped the directory structure within a pair of triple backticks (```):

```
project
¦   README.md
¦   file001.txt    
¦
+---folder1
¦   ¦   file011.txt
¦   ¦   file012.txt
¦   ¦
¦   +---subfolder1
¦       ¦   file111.txt
¦       ¦   file112.txt
¦       ¦   ...
¦   
+---folder2
    ¦   file021.txt
    ¦   file022.txt
```

Installing R with Homebrew

As of 2017, it's just brew install r. See @Andrew's answer below.

As of 2014 (using an Yosemite), the method is the following:

brew tap homebrew/science
brew install Caskroom/cask/xquartz
brew install r

The gcc package (will be installed automatically as a required dependency) in the homebrew/science tap already contains the latest fortran compiler (gfortran), and most of all: the whole package is precompiled so it saves you a lot of compilation time.

This answer will also work for El Capitan and Mac OS Sierra.

In case you don't have XCode Command Line Tools (CLT), run from terminal:

xcode-select --install

MySQL check if a table exists without throwing an exception

As a "Show tables" might be slow on larger databases, I recommend using "DESCRIBE " and check if you get true/false as a result

$tableExists = mysqli_query("DESCRIBE `myTable`");

Eslint: How to disable "unexpected console statement" in Node.js?

Create a .eslintrc.js in the directory of your file, and put the following contents in it:

module.exports = {
    rules: {
        'no-console': 'off',
    },
};

How do you check what version of SQL Server for a database using TSQL?

Try

SELECT @@VERSION 

or for SQL Server 2000 and above the following is easier to parse :)

SELECT SERVERPROPERTY('productversion')
     , SERVERPROPERTY('productlevel')
     , SERVERPROPERTY('edition')

From: http://support.microsoft.com/kb/321185

how to convert JSONArray to List of Object using camel-jackson

I also faced the similar problem with JSON output format. This code worked for me with the above JSON format.

package com.test.ameba;

import java.util.List;

public class OutputRanges {
    public List<Range> OutputRanges;
    public String Message;
    public String Entity;

    /**
     * @return the outputRanges
     */
    public List<Range> getOutputRanges() {
        return OutputRanges;
    }

    /**
     * @param outputRanges the outputRanges to set
     */
    public void setOutputRanges(List<Range> outputRanges) {
        OutputRanges = outputRanges;
    }

    /**
     * @return the message
     */
    public String getMessage() {
        return Message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(String message) {
        Message = message;
    }

    /**
     * @return the entity
     */
    public String getEntity() {
        return Entity;
    }

    /**
     * @param entity the entity to set
     */
    public void setEntity(String entity) {
        Entity = entity;
    }
}

package com.test;


public class Range {
    public String Name;
    /**
     * @return the name
     */
    public String getName() {
        return Name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        Name = name;
    }

    public Object[] Value;
    /**
     * @return the value
     */
    public Object[] getValue() {
        return Value;
    }
    /**
     * @param value the value to set
     */
    public void setValue(Object[] value) {
        Value = value;
    }

}

package com.test.ameba;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String jsonString ="{\"OutputRanges\":[{\"Name\":\"ABF_MEDICAL_RELATIVITY\",\"Value\":[[1.3628407124839714]]},{\"Name\":\" ABF_RX_RELATIVITY\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_Unique_ID_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_FIRST_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_AMEBA_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_Effective_Date_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_AMEBA_MODEL\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_UC_ER_COPAY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_INN_OON_DED_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_COINSURANCE_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_PCP_SPEC_COPAY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_INN_OON_OOP_MAX_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_IP_OP_COPAY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_PHARMACY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_PLAN_ADMIN_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]}],\"Message\":\"\",\"Entity\":null}";
        ObjectMapper mapper = new ObjectMapper();
        OutputRanges OutputRanges=null;
        try {
            OutputRanges = mapper.readValue(jsonString, OutputRanges.class);
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("OutputRanges :: "+OutputRanges);;
        System.out.println("OutputRanges.getOutputRanges() :: "+OutputRanges.getOutputRanges());;
        for (Range r : OutputRanges.getOutputRanges()) {
            System.out.println(r.getName());
        }
    }

}

How to delete columns that contain ONLY NAs?

One way of doing it:

df[, colSums(is.na(df)) != nrow(df)]

If the count of NAs in a column is equal to the number of rows, it must be entirely NA.

Or similarly

df[colSums(!is.na(df)) > 0]

How do I detect when someone shakes an iPhone?

In iOS 8.3 (perhaps earlier) with Swift, it's as simple as overriding the motionBegan or motionEnded methods in your view controller:

class ViewController: UIViewController {
    override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent) {
        println("started shaking!")
    }

    override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
        println("ended shaking!")
    }
}

Stretch image to fit full container width bootstrap

This will do the same as many of the other answers, but will make sides flush with the window, so there is no scroll bars.

<div class="container-fluid">
  <div class="row">
    <div class="col" style="padding: 0;">
       <img src="example.jpg" class="img-responsive" alt="Example">  
    </div>
  </div>
</div>

Parse an HTML string with JS

const parse = Range.prototype.createContextualFragment.bind(document.createRange());

document.body.appendChild( parse('<p><strong>Today is:</strong></p>') ),
document.body.appendChild( parse(`<p style="background: #eee">${new Date()}</p>`) );


Only valid child Nodes within the parent Node (start of the Range) will be parsed. Otherwise, unexpected results may occur:

// <body> is "parent" Node, start of Range
const parseRange = document.createRange();
const parse = Range.prototype.createContextualFragment.bind(parseRange);

// Returns Text "1 2" because td, tr, tbody are not valid children of <body>
parse('<td>1</td> <td>2</td>');
parse('<tr><td>1</td> <td>2</td></tr>');
parse('<tbody><tr><td>1</td> <td>2</td></tr></tbody>');

// Returns <table>, which is a valid child of <body>
parse('<table> <td>1</td> <td>2</td> </table>');
parse('<table> <tr> <td>1</td> <td>2</td> </tr> </table>');
parse('<table> <tbody> <td>1</td> <td>2</td> </tbody> </table>');

// <tr> is parent Node, start of Range
parseRange.setStart(document.createElement('tr'), 0);

// Returns [<td>, <td>] element array
parse('<td>1</td> <td>2</td>');
parse('<tr> <td>1</td> <td>2</td> </tr>');
parse('<tbody> <td>1</td> <td>2</td> </tbody>');
parse('<table> <td>1</td> <td>2</td> </table>');

How to find which columns contain any NaN value in Pandas dataframe

In datasets having large number of columns its even better to see how many columns contain null values and how many don't.

print("No. of columns containing null values")
print(len(df.columns[df.isna().any()]))

print("No. of columns not containing null values")
print(len(df.columns[df.notna().all()]))

print("Total no. of columns in the dataframe")
print(len(df.columns))

For example in my dataframe it contained 82 columns, of which 19 contained at least one null value.

Further you can also automatically remove cols and rows depending on which has more null values
Here is the code which does this intelligently:

df = df.drop(df.columns[df.isna().sum()>len(df.columns)],axis = 1)
df = df.dropna(axis = 0).reset_index(drop=True)

Note: Above code removes all of your null values. If you want null values, process them before.

Argument of type 'X' is not assignable to parameter of type 'X'

This problem basically comes when your compiler gets failed to understand the difference between cast operator of the type string to Number.

you can use the Number object and pass your value to get the appropriate results for it by using Number(<<<<...Variable_Name......>>>>)

Printing image with PrintDocument. how to adjust the image to fit paper size

The solution provided by BBoy works fine. But in my case I had to use

e.Graphics.DrawImage(memoryImage, e.PageBounds);

This will print only the form. When I use MarginBounds it prints the entire screen even if the form is smaller than the monitor screen. PageBounds solved that issue. Thanks to BBoy!

How to check whether a str(variable) is empty or not?

string = "TEST"
try:
  if str(string):
     print "good string"
except NameError:
     print "bad string"

Select n random rows from SQL Server table

newid()/order by will work, but will be very expensive for large result sets because it has to generate an id for every row, and then sort them.

TABLESAMPLE() is good from a performance standpoint, but you will get clumping of results (all rows on a page will be returned).

For a better performing true random sample, the best way is to filter out rows randomly. I found the following code sample in the SQL Server Books Online article Limiting Results Sets by Using TABLESAMPLE:

If you really want a random sample of individual rows, modify your query to filter out rows randomly, instead of using TABLESAMPLE. For example, the following query uses the NEWID function to return approximately one percent of the rows of the Sales.SalesOrderDetail table:

SELECT * FROM Sales.SalesOrderDetail
WHERE 0.01 >= CAST(CHECKSUM(NEWID(),SalesOrderID) & 0x7fffffff AS float)
              / CAST (0x7fffffff AS int)

The SalesOrderID column is included in the CHECKSUM expression so that NEWID() evaluates once per row to achieve sampling on a per-row basis. The expression CAST(CHECKSUM(NEWID(), SalesOrderID) & 0x7fffffff AS float / CAST (0x7fffffff AS int) evaluates to a random float value between 0 and 1.

When run against a table with 1,000,000 rows, here are my results:

SET STATISTICS TIME ON
SET STATISTICS IO ON

/* newid()
   rows returned: 10000
   logical reads: 3359
   CPU time: 3312 ms
   elapsed time = 3359 ms
*/
SELECT TOP 1 PERCENT Number
FROM Numbers
ORDER BY newid()

/* TABLESAMPLE
   rows returned: 9269 (varies)
   logical reads: 32
   CPU time: 0 ms
   elapsed time: 5 ms
*/
SELECT Number
FROM Numbers
TABLESAMPLE (1 PERCENT)

/* Filter
   rows returned: 9994 (varies)
   logical reads: 3359
   CPU time: 641 ms
   elapsed time: 627 ms
*/    
SELECT Number
FROM Numbers
WHERE 0.01 >= CAST(CHECKSUM(NEWID(), Number) & 0x7fffffff AS float) 
              / CAST (0x7fffffff AS int)

SET STATISTICS IO OFF
SET STATISTICS TIME OFF

If you can get away with using TABLESAMPLE, it will give you the best performance. Otherwise use the newid()/filter method. newid()/order by should be last resort if you have a large result set.

Disable submit button when form invalid with AngularJS

We can create a simple directive and disable the button until all the mandatory fields are filled.

angular.module('sampleapp').directive('disableBtn',
function() {
 return {
  restrict : 'A',
  link : function(scope, element, attrs) {
   var $el = $(element);
   var submitBtn = $el.find('button[type="submit"]');
   var _name = attrs.name;
   scope.$watch(_name + '.$valid', function(val) {
    if (val) {
     submitBtn.removeAttr('disabled');
    } else {
     submitBtn.attr('disabled', 'disabled');
    }
   });
  }
 };
}
);

For More Info click here

DataTable, How to conditionally delete rows

Here's a one-liner using LINQ and avoiding any run-time evaluation of select strings:

someDataTable.Rows.Cast<DataRow>().Where(
    r => r.ItemArray[0] == someValue).ToList().ForEach(r => r.Delete());

Regarding C++ Include another class

The thing with compiling two .cpp files at the same time, it doesnt't mean they "know" about eachother. You will have to create a file, the "tells" your File1.cpp, there actually are functions and classes like ClassTwo. This file is called header-file and often doesn't include any executable code. (There are exception, e.g. for inline functions, but forget them at first) They serve a declarative need, just for telling, which functions are available.

When you have your File2.cpp and include it into your File1.cpp, you see a small problem: There is the same code twice: One in the File1.cpp and one in it's origin, File2.cpp.

Therefore you should create a header file, like File1.hpp or File1.h (other names are possible, but this is simply standard). It works like the following:

//File1.cpp

void SomeFunc(char c) //Definition aka Implementation
{
//do some stuff
}

//File1.hpp

void SomeFunc(char c); //Declaration aka Prototype

And for a matter of clean code you might add the following to the top of File1.cpp:

#include "File1.hpp"

And the following, surrounding File1.hpp's code:

#ifndef FILE1.HPP_INCLUDED
#define FILE1.HPP_INCLUDED
//
//All your declarative code
//
#endif

This makes your header-file cleaner, regarding to duplicate code.

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

To evaporate the warning, you can use libxml_use_internal_errors(true)

// create new DOMDocument
$document = new \DOMDocument('1.0', 'UTF-8');

// set error level
$internalErrors = libxml_use_internal_errors(true);

// load HTML
$document->loadHTML($html);

// Restore error level
libxml_use_internal_errors($internalErrors);

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

Overview of JSP Syntax Elements

First, to make things more clear, here is a short overview of JSP syntax elements:

  • Directives: These convey information regarding the JSP page as a whole.
  • Scripting elements: These are Java coding elements such as declarations, expressions, scriptlets, and comments.
  • Objects and scopes: JSP objects can be created either explicitly or implicitly and are accessible within a given scope, such as from anywhere in the JSP page or the session.
  • Actions: These create objects or affect the output stream in the JSP response (or both).

How content is included in JSP

There are several mechanisms for reusing content in a JSP file.

The following 4 mechanisms to include content in JSP can be categorized as direct reuse:
(for the first 3 mechanisms quoting from "Head First Servlets and JSP")

1) The include directive:

<%@ include file="header.html" %>

Static: adds the content from the value of the file attribute to the current page at translation time. The directive was originally intended for static layout templates, like HTML headers.

2) The <jsp:include> standard action:

<jsp:include page="header.jsp" />

Dynamic: adds the content from the value of the page attribute to the current page at request time. Was intended more for dynamic content coming from JSPs.

3) The <c:import> JSTL tag:

<c:import url=”http://www.example.com/foo/bar.html” />

Dynamic: adds the content from the value of the URL attribute to the current page, at request time. It works a lot like <jsp:include>, but it’s more powerful and flexible: unlike the other two includes, the <c:import> url can be from outside the web Container!

4) Preludes and codas:

Static: preludes and codas can be applied only to the beginnings and ends of pages.
You can implicitly include preludes (also called headers) and codas (also called footers) for a group of JSP pages by adding <include-prelude> and <include-coda> elements respectively within a <jsp-property-group> element in the Web application web.xml deployment descriptor. Read more here:
Configuring Implicit Includes at the Beginning and End of JSPs
Defining implicit includes


Tag File is an indirect method of content reuse, the way of encapsulating reusable content. A Tag File is a source file that contains a fragment of JSP code that is reusable as a custom tag.

The PURPOSE of includes and Tag Files is different.

Tag file (a concept introduced with JSP 2.0) is one of the options for creating custom tags. It's a faster and easier way to build custom tags. Custom tags, also known as tag extensions, are JSP elements that allow custom logic and output provided by other Java components to be inserted into JSP pages. The logic provided through a custom tag is implemented by a Java object known as a tag handler.

Some examples of tasks that can be performed by custom tags include operating on implicit objects, processing forms, accessing databases and other enterprise services such as email and directories, and implementing flow control.


Regarding your Edit

Maybe in your example (in your "Edit" paragraph), there is no difference between using direct include and a Tag File. But custom tags have a rich set of features. They can

  • Be customized by means of attributes passed from the calling page.

  • Pass variables back to the calling page.

  • Access all the objects available to JSP pages.

  • Communicate with each other. You can create and initialize a JavaBeans component, create a public EL variable that refers to that bean in one tag, and then use the bean in another tag.

  • Be nested within one another and communicate by means of private variables.

Also read this from "Pro JSP 2": Understanding JSP Custom Tags.


Useful reading.


Conclusion

Use the right tools for each task.

Use Tag Files as a quick and easy way of creating custom tags that can help you encapsulate reusable content.

As for the including content in JSP (quote from here):

  • Use the include directive if the file changes rarely. It’s the fastest mechanism. If your container doesn’t automatically detect changes, you can force the changes to take effect by deleting the main page class file.
  • Use the include action only for content that changes often, and if which page to include cannot be decided until the main page is requested.

I have never set any passwords to my keystore and alias, so how are they created?

when we run application in eclipse apk generate is sign by default Keystore which is provided by android .

But if you want to upload your application on play store you need to create your own keystore. Eclipse already provides GUI interface to create new keystore. And you also can create keystore through command line.

default alias is

androiddebugkey

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

Delete duplicate elements from an array

Try following from Removing duplicates from an Array(simple):

Array.prototype.removeDuplicates = function (){
  var temp=new Array();
  this.sort();
  for(i=0;i<this.length;i++){
    if(this[i]==this[i+1]) {continue}
    temp[temp.length]=this[i];
  }
  return temp;
} 

Edit:

This code doesn't need sort:

Array.prototype.removeDuplicates = function (){
  var temp=new Array();
  label:for(i=0;i<this.length;i++){
        for(var j=0; j<temp.length;j++ ){//check duplicates
            if(temp[j]==this[i])//skip if already present 
               continue label;      
        }
        temp[temp.length] = this[i];
  }
  return temp;
 } 

(But not a tested code!)

Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?

Well Heroku uses AWS in background, it all depends on the type of solution you need. If you are a core linux and devops guy you are not worried about creating vm from scratch like selecting ami choosing palcement options etc, you can go with AWS. If you want to do things on surface level without having those nettigrities you can go with heroku.

Perform .join on value in array of objects

I don't know if there's an easier way to do it without using an external library, but I personally love underscore.js which has tons of utilities for dealing with arrays, collections etc.

With underscore you could do this easily with one line of code:

_.pluck(arr, 'name').join(', ')

How to unpack and pack pkg file?

@shrx I've succeeded to unpack the BSD.pkg (part of the Yosemite installer) by using "pbzx" command.

pbzx <pkg> | cpio -idmu

The "pbzx" command can be downloaded from the following link:

How to add a ListView to a Column in Flutter?

return new MaterialApp(
    home: new Scaffold(
      appBar: new AppBar(
        title: new Text("Login / Signup"),
      ),
      body: new Container(
        child: new Center(
          child: ListView(
          //mainAxisAlignment: MainAxisAlignment.center,
          scrollDirection: Axis.vertical,
            children: <Widget>[
              new TextField(
                decoration: new InputDecoration(
                  hintText: "E M A I L    A D D R E S S"
                ),
              ),
              new Padding(padding: new EdgeInsets.all(15.00)),
              new TextField(obscureText: true,
                decoration: new InputDecoration(
                  hintText: "P A S S W O R D"
                ),
                ),
              new Padding(padding: new EdgeInsets.all(15.00)),
              new TextField(decoration: new InputDecoration(
                hintText: "U S E R N A M E"
              ),),
              new RaisedButton(onPressed: null,
              child:  new Text("SIGNUP"),),
              new Padding(padding: new EdgeInsets.all(15.00)),
              new RaisedButton(onPressed: null,
              child: new Text("LOGIN"),),
              new Padding(padding: new EdgeInsets.all(15.00)),
              new ListView(scrollDirection: Axis.horizontal,
              children: <Widget>[
                new RaisedButton(onPressed: null,
                child: new Text("Facebook"),),
                new Padding(padding: new EdgeInsets.all(5.00)),
                new RaisedButton(onPressed: null,
                child: new Text("Google"),)
              ],)

            ],
          ),
        ),
        margin: new EdgeInsets.all(15.00),
      ),
    ),
  );

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

For Jackson versions < 2.0 use this annotation on the class being serialized:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

Find records with a date field in the last 24 hours

SELECT * FROM news WHERE date > DATE_SUB(NOW(), INTERVAL 24 HOUR)

CSS scale height to match width - possibly with a formfactor

Try viewports

You can use the width data and calculate the height accordingly

This example is for an 150x200px image

width: calc(100vw / 2 - 30px);
height: calc((100vw/2 - 30px) * 1.34);

Pointer to a string in C?

The same notation is used for pointing at a single character or the first character of a null-terminated string:

char c = 'Z';
char a[] = "Hello world";

char *ptr1 = &c;
char *ptr2 = a;      // Points to the 'H' of "Hello world"
char *ptr3 = &a[0];  // Also points to the 'H' of "Hello world"
char *ptr4 = &a[6];  // Points to the 'w' of "world"
char *ptr5 = a + 6;  // Also points to the 'w' of "world"

The values in ptr2 and ptr3 are the same; so are the values in ptr4 and ptr5. If you're going to treat some data as a string, it is important to make sure it is null terminated, and that you know how much space there is for you to use. Many problems are caused by not understanding what space is available and not knowing whether the string was properly null terminated.

Note that all the pointers above can be dereferenced as if they were an array:

 *ptr1    == 'Z'
  ptr1[0] == 'Z'

 *ptr2    == 'H'
  ptr2[0] == 'H'
  ptr2[4] == 'o'

 *ptr4    == 'w'
  ptr4[0] == 'w'
  ptr4[4] == 'd'

  ptr5[0] ==   ptr3[6]
*(ptr5+0) == *(ptr3+6)

Late addition to question

What does char (*ptr)[N]; represent?

This is a more complex beastie altogether. It is a pointer to an array of N characters. The type is quite different; the way it is used is quite different; the size of the object pointed to is quite different.

char (*ptr)[12] = &a;

(*ptr)[0] == 'H'
(*ptr)[6] == 'w'

*(*ptr + 6) == 'w'

Note that ptr + 1 points to undefined territory, but points 'one array of 12 bytes' beyond the start of a. Given a slightly different scenario:

char b[3][12] = { "Hello world", "Farewell", "Au revoir" };

char (*pb)[12] = &b[0];

Now:

(*(pb+0))[0] == 'H'
(*(pb+1))[0] == 'F'
(*(pb+2))[5] == 'v'

You probably won't come across pointers to arrays except by accident for quite some time; I've used them a few times in the last 25 years, but so few that I can count the occasions on the fingers of one hand (and several of those have been answering questions on Stack Overflow). Beyond knowing that they exist, that they are the result of taking the address of an array, and that you probably didn't want it, you don't really need to know more about pointers to arrays.

How do you make websites with Java?

While a lot of others should be mentioned, Apache Wicket should be preferred.

Wicket doesn't just reduce lots of boilerplate code, it actually removes it entirely and you can work with excellent separation of business code and markup without mixing the two and a wide variety of other things you can read about from the website.