# Programs & Examples On #Factorial

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.

### What is the fastest factorial function in JavaScript?

short and easy recursive function (you could do it with a loop, too, but I don't think that would make any difference in performance):

``````function factorial (n){
if (n==0 || n==1){
return 1;
}
return factorial(n-1)*n;
}
``````

for a very large n, you could use the stirlings approximation - but that will only give you an approximate value.

EDIT: a comment on why I'm getting a downvote for this would have been nice...

EDIT2: this would be the soulution using a loop (which would be the better choice):

``````function factorial (n){
j = 1;
for(i=1;i<=n;i++){
j = j*i;
}
return j;
}
``````

I think the best solution would be to use the cached values, as Margus mentioned and use the stirlings approximation for larger values (assumed you have to be realy fast and don't have to be that exact on such big numbers).

### \$(window).height() vs \$(document).height

`\$(document).height:`if your device `height` was bigger. Your page has Not any scroll;

`\$(document).height:` assume you have not scroll and return this `height`;

`\$(window).height:` return your page `height` on your device.

### How to trigger the window resize event in JavaScript?

Where possible, I prefer to call the function rather than dispatch an event. This works well if you have control over the code you want to run, but see below for cases where you don't own the code.

``````window.onresize = doALoadOfStuff;

}
``````

In this example, you can call the `doALoadOfStuff` function without dispatching an event.

In your modern browsers, you can trigger the event using:

``````window.dispatchEvent(new Event('resize'));
``````

This doesn't work in Internet Explorer, where you'll have to do the longhand:

``````var resizeEvent = window.document.createEvent('UIEvents');
resizeEvent.initUIEvent('resize', true, false, window, 0);
window.dispatchEvent(resizeEvent);
``````

jQuery has the `trigger` method, which works like this:

``````\$(window).trigger('resize');
``````

And has the caveat:

Although `.trigger()` simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

You can also simulate events on a specific element...

``````function simulateClick(id) {
var event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});

var elem = document.getElementById(id);

return elem.dispatchEvent(event);
}
``````

### How to post JSON to PHP with curl

You should escape the quotes like this:

``````curl -i -X POST -d '{\"screencast\":{\"subject\":\"tools\"}}'  \
http://localhost:3570/index.php/trainingServer/screencast.json
``````

### How do you define a class of constants in Java?

Just use final class.

If you want to be able to add other values use an abstract class.

It doesn't make much sense using an interface, an interface is supposed to specify a contract. You just want to declare some constant values.

### unexpected T_VARIABLE, expecting T_FUNCTION

Use access modifier before the member definition:

``````    private \$connection;
``````

As you cannot use function call in member definition in PHP, do it in constructor:

`````` public function __construct() {
\$this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
}
``````

### Row count with PDO

When it is matter of mysql how to count or get how many rows in a table with PHP PDO I use this

``````// count total number of rows
\$query = "SELECT COUNT(*) as total_rows FROM sometable";
\$stmt = \$con->prepare(\$query);

// execute query
\$stmt->execute();

// get total rows
\$row = \$stmt->fetch(PDO::FETCH_ASSOC);
\$total_rows = \$row['total_rows'];
``````

credits goes to Mike @ codeofaninja.com

### 'too many values to unpack', iterating over a dict. key=>string, value=>list

You want to use iteritems. This returns an iterator over the dictionary, which gives you a tuple(key, value)

``````>>> for field, values in fields.iteritems():
...     print field, values
...
first_names ['foo', 'bar']
last_name ['gravy', 'snowman']
``````

Your problem was that you were looping over fields, which returns the keys of the dictionary.

``````>>> for field in fields:
...     print field
...
first_names
last_name
``````

### SQLAlchemy ORDER BY DESCENDING?

``````from sqlalchemy import desc
someselect.order_by(desc(table1.mycol))
``````

Usage from @jpmc26

### Check if two unordered lists are equal

What about getting the string representation of the lists and comparing them ?

``````>>> l1 = ['one', 'two', 'three']
>>> l2 = ['one', 'two', 'three']
>>> l3 = ['one', 'three', 'two']
>>> print str(l1) == str(l2)
True
>>> print str(l1) == str(l3)
False
``````

### How to get the size of a range in Excel

The overall dimensions of a range are in its `Width` and `Height` properties.

``````Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height
``````

### What is an optional value in Swift?

I made a short answer, that sums up most of the above, to clean the uncertainty that was in my head as a beginner:

Opposed to Objective-C, no variable can contain nil in Swift, so the Optional variable type was added (variables suffixed by "?"):

``````    var aString = nil //error
``````

The big difference is that the Optional variables don't directly store values (as a normal Obj-C variables would) they contain two states: "has a value" or "has nil":

``````    var aString: String? = "Hello, World!"
aString = nil //correct, now it contains the state "has nil"
``````

That being, you can check those variables in different situations:

``````if let myString = aString? {
println(myString)
}
else {
println("It's nil") // this will print in our case
}
``````

By using the "!" suffix, you can also access the values wrapped in them, only if those exist. (i.e it is not nil):

``````let aString: String? = "Hello, World!"
// var anotherString: String = aString //error
var anotherString: String = aString!

println(anotherString) //it will print "Hello, World!"
``````

That's why you need to use "?" and "!" and not use all of them by default. (this was my biggest bewilderment)

I also agree with the answer above: Optional type cannot be used as a boolean.

### Excel formula to get ranking position

You can use the RANK function in Excel without necessarily sorting the data. Type =RANK(C2,\$C\$2:\$C\$7). Excel will find the relative position of the data in C2 and display the answer. Copy the formula through to C7 by dragging the small node at the right end of the cell cursor.

### Use tnsnames.ora in Oracle SQL Developer

• In SQLDeveloper browse `Tools --> Preferences`, as shown in below image.

• In the Preferences options `expand Database --> select Advanced --> under "Tnsnames Directory" --> Browse the directory` where tnsnames.ora present.
• Then click on Ok, as shown in below diagram.
tnsnames.ora available at `Drive:\oracle\product\10x.x.x\client_x\NETWORK\ADMIN`

Now you can connect via the TNSnames options.

### Format of the initialization string does not conform to specification starting at index 0

I had typo in my connection strings "Database==PESitecore1_master"

``````<add name="master" connectionString="user id=sa;password=xxxxx;Data Source=APR9038KBD\SQL2014;Database==PESitecore1_master"/>
``````

### JQuery \$.each() JSON array object iteration

Assign the second variable for the `\$.each function()` as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

``````\$.each(json, function(arrayID,group) {
console.log('<a href="'+group.GROUP_ID+'">');
\$.each(group.EVENTS, function(eventID,eventData) {
console.log('<p>'+eventData.SHORT_DESC+'</p>');
});
});
``````

Should print out everything you were trying in your question.

http://jsfiddle.net/niklasvh/hZsQS/

edit renamed the variables to make it bit easier to understand what is what.

### VBA to copy a file from one directory to another

Use the appropriate methods in Scripting.FileSystemObject. Then your code will be more portable to VBScript and VB.net. To get you started, you'll need to include:

``````Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
``````

Then you could use

``````Call fso.CopyFile(source, destination[, overwrite] )
``````

where source and destination are the full names (including paths) of the file.

### SQL server stored procedure return a table

Consider creating a function which can return a table and be used in a query.

https://msdn.microsoft.com/en-us/library/ms186755.aspx

The main difference between a function and a procedure is that a function makes no changes to any table. It only returns a value.

In this example I'm creating a query to give me the counts of all the columns in a given table which aren't null or empty.

There are probably many ways to clean this up. But it illustrates a function well.

``````USE Northwind

CREATE FUNCTION usp_listFields(@schema VARCHAR(50), @table VARCHAR(50))
RETURNS @query TABLE (
FieldName VARCHAR(255)
)
BEGIN
INSERT @query
SELECT
'SELECT ''' + @table+'~'+RTRIM(COLUMN_NAME)+'~''+CONVERT(VARCHAR, COUNT(*)) '+
'FROM '+@schema+'.'+@table+' '+
' WHERE isnull("'+RTRIM(COLUMN_NAME)+'",'''')<>'''' UNION'
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table and TABLE_SCHEMA = @schema
RETURN
END
``````

Then executing the function with

``````SELECT * FROM usp_listFields('Employees')
``````

produces a number of rows like:

``````SELECT 'Employees~EmployeeID~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees  WHERE isnull("EmployeeID",'')<>'' UNION
SELECT 'Employees~LastName~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees  WHERE isnull("LastName",'')<>'' UNION
SELECT 'Employees~FirstName~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees  WHERE isnull("FirstName",'')<>'' UNION
``````

### LogisticRegression: Unknown label type: 'continuous' using sklearn in python

I struggled with the same issue when trying to feed floats to the classifiers. I wanted to keep floats and not integers for accuracy. Try using regressor algorithms. For example:

``````import numpy as np
from sklearn import linear_model
from sklearn import svm

classifiers = [
svm.SVR(),
linear_model.SGDRegressor(),
linear_model.BayesianRidge(),
linear_model.LassoLars(),
linear_model.ARDRegression(),
linear_model.PassiveAggressiveRegressor(),
linear_model.TheilSenRegressor(),
linear_model.LinearRegression()]

trainingData    = np.array([ [2.3, 4.3, 2.5],  [1.3, 5.2, 5.2],  [3.3, 2.9, 0.8],  [3.1, 4.3, 4.0]  ])
trainingScores  = np.array( [3.4, 7.5, 4.5, 1.6] )
predictionData  = np.array([ [2.5, 2.4, 2.7],  [2.7, 3.2, 1.2] ])

for item in classifiers:
print(item)
clf = item
clf.fit(trainingData, trainingScores)
print(clf.predict(predictionData),'\n')
``````

### while EOF in JAVA?

``````while(inFile.hasNext())
``````

This is correct in java programming language

### Sending mail from Python using SMTP

Based on this example I made following function:

``````import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_email(host, port, user, pwd, recipients, subject, body, html=None, from_=None):
https://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python#12424439
returns None if all ok, but if problem then returns exception object
"""

PORT_LIST = (25, 587, 465)

FROM = from_ if from_ else user
TO = recipients if isinstance(recipients, (list, tuple)) else [recipients]
SUBJECT = subject
TEXT = body.encode("utf8") if isinstance(body, unicode) else body
HTML = html.encode("utf8") if isinstance(html, unicode) else html

if not html:
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
else:
# https://stackoverflow.com/questions/882712/sending-html-email-using-python#882770
msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = FROM
msg['To'] = ", ".join(TO)

# Record the MIME types of both parts - text/plain and text/html.
# utf-8 -> https://stackoverflow.com/questions/5910104/python-how-to-send-utf-8-e-mail#5910530
part1 = MIMEText(TEXT, 'plain', "utf-8")
part2 = MIMEText(HTML, 'html', "utf-8")

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)

message = msg.as_string()

try:
if port not in PORT_LIST:
raise Exception("Port %s not one of %s" % (port, PORT_LIST))

if port in (465,):
server = smtplib.SMTP_SSL(host, port)
else:
server = smtplib.SMTP(host, port)

# optional
server.ehlo()

if port in (587,):
server.starttls()

server.sendmail(FROM, TO, message)
server.close()
# logger.info("SENT_EMAIL to %s: %s" % (recipients, subject))
except Exception, ex:
return ex

return None
``````

if you pass only `body` then plain text mail will be sent, but if you pass `html` argument along with `body` argument, html email will be sent (with fallback to text content for email clients that don't support html/mime types).

Example usage:

``````ex = send_email(
host        = 'smtp.gmail.com'
#, port        = 465 # OK
, port        = 587  #OK
, user        = "[email protected]"
, pwd         = "xxx"
, from_       = '[email protected]'
, recipients  = ['[email protected]']
, subject     = "Test from python"
, body        = "Test from python - body"
)
if ex:
print("Mail sending failed: %s" % ex)
else:
print("OK - mail sent"
``````

Btw. If you want to use gmail as testing or production SMTP server, enable temp or permanent access to less secured apps:

### Creating a ZIP archive in memory using System.IO.Compression

``````       private void button6_Click(object sender, EventArgs e)
{

//create With Input FileNames
new ZipItem(@"E:\b\2.txt",@"text\2.txt")}, @"C:\test.zip");

//create with input stream

//Create Archive And Return StreamZipFile
MemoryStream GetStreamZipFile = AddFileToArchive(new ZipItem[]{ new ZipItem( @"E:\b\1.jpg",@"images\1.jpg"),
new ZipItem(@"E:\b\2.txt",@"text\2.txt")});

//Extract in memory
ZipItem[] ListitemsWithBytes = ExtractItems(@"C:\test.zip");

//Choese Files For Extract To memory
List<string> ListFileNameForExtract = new List<string>(new string[] { @"images\1.jpg", @"text\2.txt" });
ListitemsWithBytes = ExtractItems(@"C:\test.zip", ListFileNameForExtract);

// Choese Files For Extract To Directory
ExtractItems(@"C:\test.zip", ListFileNameForExtract, "c:\\extractFiles");

}

public struct ZipItem
{
string _FileNameSource;
string _PathinArchive;
byte[] _Bytes;
public ZipItem(string __FileNameSource, string __PathinArchive)
{
_Bytes=null ;
_FileNameSource = __FileNameSource;
_PathinArchive = __PathinArchive;
}
public ZipItem(byte[] __Bytes, string __PathinArchive)
{
_Bytes = __Bytes;
_FileNameSource = "";
_PathinArchive = __PathinArchive;

}
public string FileNameSource
{
set
{
FileNameSource = value;
}
get
{
return _FileNameSource;
}
}
public string PathinArchive
{
set
{
_PathinArchive = value;
}
get
{
return _PathinArchive;
}
}
public byte[] Bytes
{
set
{
_Bytes = value;
}
get
{
return _Bytes;
}
}
}

public void AddFileToArchive(ZipItem[] ZipItems, string SeveToFile)
{

MemoryStream memoryStream = new MemoryStream();

//Create Empty Archive
ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

foreach (ZipItem item in ZipItems)
{

//Create Path File in Archive
ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);

//Open File in Archive For Write
var OpenFileInArchive = FileInArchive.Open();

byte[] ReadAllbytes = new byte[4096];//Capcity buffer
{

//Write Bytes
}
OpenFileInArchive.Close();

}
archive.Dispose();

using (var fileStream = new FileStream(SeveToFile, FileMode.Create))
{
memoryStream.Seek(0, SeekOrigin.Begin);
memoryStream.CopyTo(fileStream);
}

}
{

MemoryStream memoryStream = new MemoryStream();

//Create Empty Archive
ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

foreach (ZipItem item in ZipItems)
{

//Create Path File in Archive
ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);

//Open File in Archive For Write
var OpenFileInArchive = FileInArchive.Open();

byte[] ReadAllbytes = new byte[4096];//Capcity buffer
{

//Write Bytes
}
OpenFileInArchive.Close();

}
archive.Dispose();

return memoryStream;

}

public void AddFileToArchive_InputByte(ZipItem[] ZipItems, string SeveToFile)
{

MemoryStream memoryStream = new MemoryStream();

//Create Empty Archive
ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

foreach (ZipItem item in ZipItems)
{

//Create Path File in Archive
ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);

//Open File in Archive For Write
var OpenFileInArchive = FileInArchive.Open();

byte[] ReadAllbytes = new byte[4096];//Capcity buffer
int ReadByte = 4096 ;int  TotalWrite=0;
while (TotalWrite != item.Bytes.Length)
{

if(TotalWrite+4096>item.Bytes.Length)

//Write Bytes
}

OpenFileInArchive.Close();

}
archive.Dispose();

using (var fileStream = new FileStream(SeveToFile, FileMode.Create))
{
memoryStream.Seek(0, SeekOrigin.Begin);
memoryStream.CopyTo(fileStream);
}

}
{

MemoryStream memoryStream = new MemoryStream();

//Create Empty Archive
ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

foreach (ZipItem item in ZipItems)
{

//Create Path File in Archive
ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);

//Open File in Archive For Write
var OpenFileInArchive = FileInArchive.Open();

byte[] ReadAllbytes = new byte[4096];//Capcity buffer
int ReadByte = 4096 ;int  TotalWrite=0;
while (TotalWrite != item.Bytes.Length)
{

if(TotalWrite+4096>item.Bytes.Length)

//Write Bytes
}

OpenFileInArchive.Close();

}
archive.Dispose();

return memoryStream;
}

public void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName)
{
//Opens the zip file up to be read
{
if (Directory.Exists(destinationDirectoryName)==false )
Directory.CreateDirectory(destinationDirectoryName);

//Loops through each file in the zip file
archive.ExtractToDirectory(destinationDirectoryName);

}
}
public void   ExtractItems(string sourceArchiveFileName,List< string> _PathFilesinArchive, string destinationDirectoryName)
{

//Opens the zip file up to be read
{

//Loops through each file in the zip file
foreach (ZipArchiveEntry file in archive.Entries)
{
int PosResult = _PathFilesinArchive.IndexOf(file.FullName);
if (PosResult != -1)
{
//Create Folder
if (Directory.Exists( destinationDirectoryName + "\\" +Path.GetDirectoryName( _PathFilesinArchive[PosResult])) == false)
Directory.CreateDirectory(destinationDirectoryName + "\\" + Path.GetDirectoryName(_PathFilesinArchive[PosResult]));

Stream OpenFileGetBytes = file.Open();

FileStream   FileStreamOutput = new FileStream(destinationDirectoryName + "\\" + _PathFilesinArchive[PosResult], FileMode.Create);

byte[] ReadAllbytes = new byte[4096];//Capcity buffer
{

//Write Bytes
}

FileStreamOutput.Close();
OpenFileGetBytes.Close();

_PathFilesinArchive.RemoveAt(PosResult);
}

if (_PathFilesinArchive.Count == 0)
break;
}
}

}

public ZipItem[] ExtractItems(string sourceArchiveFileName)
{
List<  ZipItem> ZipItemsReading = new List<ZipItem>();
//Opens the zip file up to be read
{

//Loops through each file in the zip file
foreach (ZipArchiveEntry file in archive.Entries)
{
Stream OpenFileGetBytes = file.Open();

MemoryStream memstreams = new MemoryStream();
byte[] ReadAllbytes = new byte[4096];//Capcity buffer
{

//Write Bytes
}

memstreams.Position = 0;
OpenFileGetBytes.Close();
memstreams.Dispose();

}
}

}
public ZipItem[] ExtractItems(string sourceArchiveFileName,List< string> _PathFilesinArchive)
{
List<  ZipItem> ZipItemsReading = new List<ZipItem>();
//Opens the zip file up to be read
{

//Loops through each file in the zip file
foreach (ZipArchiveEntry file in archive.Entries)
{
int PosResult = _PathFilesinArchive.IndexOf(file.FullName);
if (PosResult!= -1)
{
Stream OpenFileGetBytes = file.Open();

MemoryStream memstreams = new MemoryStream();
byte[] ReadAllbytes = new byte[4096];//Capcity buffer
{

//Write Bytes
}

//Create item

OpenFileGetBytes.Close();
memstreams.Dispose();

_PathFilesinArchive.RemoveAt(PosResult);
}

if (_PathFilesinArchive.Count == 0)
break;

}
}

}
``````

### Pythonic way to check if a file exists?

It seems to me that all other answers here (so far) fail to address the race-condition that occurs with their proposed solutions.

Any code where you first check for the files existence, and then, a few lines later in your program, you create it, runs the risk of the file being created while you weren't looking and causing you problems (or you causing the owner of "that other file" problems).

If you want to avoid this sort of thing, I would suggest something like the following (untested):

``````import os

def open_if_not_exists(filename):
try:
fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except OSError, e:
if e.errno == 17:
print e
return None
else:
raise
else:
return os.fdopen(fd, 'w')
``````

This should open your file for writing if it doesn't exist already, and return a file-object. If it does exists, it will print "Ooops" and return None (untested, and based solely on reading the python documentation, so might not be 100% correct).

### Get Value From Select Option in Angular 4

``````    //in html file
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">Country</label>
<select class="form-control" formControlName="country" (change)="onCountryChange(\$event.target.value)">
<option disabled selected value [ngValue]="null"> -- Select Country  -- </option>
<option *ngFor="let country of countries" [value]="country.id">{{country.name}}</option>
<div *ngIf="isEdit">
<option></option>
</div>
</select>
</div>
</div>
</div>
<div class="help-block" *ngIf="studentForm.get('country').invalid && studentForm.get('country').touched">
<div *ngIf="studentForm.get('country').errors.required">*country is required</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">State</label>
<select class="form-control" formControlName="state" (change)="onStateChange(\$event.target.value)">
<option disabled selected value [ngValue]="null"> -- Select State -- </option>
<option *ngFor="let state of states" [value]="state.id">{{state.state_name}}</option>
</select>
</div>
</div>
</div>
<div class="help-block" *ngIf="studentForm.get('state').invalid && studentForm.get('state').touched">
<div *ngIf="studentForm.get('state').errors.required">*state is enter code hererequired</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">City</label>
<select class="form-control" formControlName="city">
<option disabled selected value [ngValue]="null"> -- Select City -- </option>
<option *ngFor="let city of cities" [value]="city.id" >{{city.city_name}}</option>
</select>
</div>
</div>
</div>
<div class="help-block" *ngIf="studentForm.get('city').invalid && studentForm.get('city').touched">
<div *ngIf="studentForm.get('city').errors.required">*city is required</div>
</div>
//then in component
onCountryChange(countryId:number){
this.studentServive.getSelectedState(countryId).subscribe(resData=>{
this.states = resData;
});
}
onStateChange(stateId:number){
this.studentServive.getSelectedCity(stateId).subscribe(resData=>{
this.cities = resData;
});
}`enter code here`
``````

### Writing List of Strings to Excel CSV File in Python

I know I'm a little late, but something I found that works (and doesn't require using `csv`) is to write a for loop that writes to your file for every element in your list.

``````# Define Data
RESULTS = ['apple','cherry','orange','pineapple','strawberry']

# Open File
resultFyle = open("output.csv",'w')

# Write data to file
for r in RESULTS:
resultFyle.write(r + "\n")
resultFyle.close()
``````

I don't know if this solution is any better than the ones already offered, but it more closely reflects your original logic so I thought I'd share.

### Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

TL;DR: In Dual Boot systems, turn off Fast Startup for Windows

I was having this issue in my dual boot Ubuntu/Windows system. I couldn't write anything in any of the partitions that are shared with Windows (NTFS partitions).

I recently reinstalled both and forgot to turn of the "Fast Startup" in Windows. Everything went back to normal after I rebooted in windows and turned that feature off and restarted again.

### Can someone provide an example of a \$destroy event for scopes in AngularJS?

Here I have created handle-destroy directive.

``````ctrl.directive('handleDestroy', function() {
return function(scope, tElement, attributes) {
scope.\$on('\$destroy', function() {
});
};
});
``````

### Move an item inside a list?

Use the `insert` method of a list:

``````l = list(...)
l.insert(index, item)
``````

Alternatively, you can use a slice notation:

``````l[index:index] = [item]
``````

If you want to move an item that's already in the list to the specified position, you would have to delete it and insert it at the new position:

``````l.insert(newindex, l.pop(oldindex))
``````

### Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

For swift 3.0 and above

``````public static func getTopViewController() -> UIViewController?{
if var topController = UIApplication.shared.keyWindow?.rootViewController
{
while (topController.presentedViewController != nil)
{
topController = topController.presentedViewController!
}
}
return nil}
``````

### QUERY syntax using cell reference

I only have a workaround here. In this special case, I would use the `FILTER` function instead of `QUERY`:

``````=FILTER(Responses!B:B,Responses!G:G=B1)
``````

Assuming that your data is on the "Responses" sheet, but your condition (cell reference) is in the actual sheet's B1 cell.

Hope it helps.

UPDATE:

After some search for the original question: The problem with your formula is definitely the second `&` sign which assumes that you would like to concatenate something more to your `WHERE` statement. Try to remove it. If it still doesn't work, then try this:

`=QUERY(Responses!B1:I, "Select B where G matches '^.\*(\$" & B1 & ").\*\$'")` - I have not tried it, but it helped in another post: Query with range of values for WHERE clause?

### SQL join on multiple columns in same tables

You want to join on condition 1 AND condition 2, so simply use the AND keyword as below

``````ON a.userid = b.sourceid AND a.listid = b.destinationid;
``````

### How to recover stashed uncommitted changes

``````git stash pop
``````

will get everything back in place

as suggested in the comments, you can use `git stash branch newbranch` to apply the stash to a new branch, which is the same as running:

``````git checkout -b newbranch
git stash pop
``````

### Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

Important - Answer work only for REACT-NATIVE VS CODE Terminal

In VisualStudio code, you have to run like below then that warning will be omitted.

react-native run-android warning-mode=all

If you run below then you will get the error in terminal When running react-native run-android --warning-mode all I get error: unknown option --warning-mode'

### What is the best way to programmatically detect porn images?

This is a nudity detector. I haven't tried it. It's the only OSS one I could find.

### Python: TypeError: object of type 'NoneType' has no len()

`shuffle(names)` is an in-place operation. Drop the assignment.

This function returns `None` and that's why you have the error:

``````TypeError: object of type 'NoneType' has no len()
``````

### Spring @PropertySource using YAML

1) Add the property bean with SpringBootApplication start up as follows

``````@SpringBootApplication
@ComponentScan({"com.example.as.*"})
public class TestApplication {

public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}

@Bean
@Profile("dev")
public PropertySourcesPlaceholderConfigurer propertiesStage() {
return properties("dev");
}

@Bean
@Profile("stage")
public PropertySourcesPlaceholderConfigurer propertiesDev() {
return properties("stage");
}

@Bean
@Profile("default")
public PropertySourcesPlaceholderConfigurer propertiesDefault() {
return properties("default");

}
/**
* Update custom specific yml file with profile configuration.
* @param profile
* @return
*/
public static PropertySourcesPlaceholderConfigurer properties(String profile) {
PropertySourcesPlaceholderConfigurer propertyConfig = null;
YamlPropertiesFactoryBean yaml  = null;

propertyConfig  = new PropertySourcesPlaceholderConfigurer();
yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ClassPathResource("env_config/test-service-config.yml"));
propertyConfig.setProperties(yaml.getObject());
return propertyConfig;
}
}
``````

2) Config the Java pojo object as follows

``````@Component
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
@ConfigurationProperties(prefix = "test-service")
public class TestConfig {

@JsonProperty("id")
private  String id;

@JsonProperty("name")
private String name;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}
``````

3) Create the custom yml (and place it under resource path as follows, YML File name : test-service-config.yml

Eg Config in the yml file.

``````test-service:
id: default_id
name: Default application config
---
spring:
profiles: dev

test-service:
id: dev_id
name: dev application config

---
spring:
profiles: stage

test-service:
id: stage_id
name: stage application config
``````

### Passing a URL with brackets to curl

Never mind, I found it in the docs:

``````-g/--globoff
This  option  switches  off  the "URL globbing parser". When you set this option, you can
specify URLs that contain the letters {}[] without having them being interpreted by  curl
itself.  Note  that  these  letters  are not normal legal URL contents but they should be
encoded according to the URI standard.
``````

### Android ACTION_IMAGE_CAPTURE Intent

I had the same problem where the OK button in camera app did nothing, both on emulator and on nexus one.

The problem went away after specifying a safe filename that is without white spaces, without special characters, in `MediaStore.EXTRA_OUTPUT` Also, if you are specifying a file that resides in a directory that has not yet been created, you have to create it first. Camera app doesn't do mkdir for you.

### How to query data out of the box using Spring data JPA by both Sort and Pageable?

Spring Pageable has a Sort included. So if your request has the values it will return a sorted pageable.

request: `domain.com/endpoint?sort=[FIELDTOSORTBY]&[FIELDTOSORTBY].dir=[ASC|DESC]&page=0&size=20`

That should return a sorted pageable by field provided in the provided order.

### Unix - copy contents of one directory to another

To make an exact copy, permissions, ownership, and all use "-a" with "cp". "-r" will copy the contents of the files but not necessarily keep other things the same.

cp -av Source/* Dest/

(make sure Dest/ exists first)

If you want to repeatedly update from one to the other or make sure you also copy all dotfiles, `rsync` is a great help:

rsync -av --delete Source/ Dest/

This is also "recoverable" in that you can restart it if you abort it while copying. I like "-v" because it lets you watch what is going on but you can omit it.

### How to trim a string to N chars in Javascript?

Copying Will's comment into an answer, because I found it useful:

``````var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ?
string.substring(0, length - 3) + "..." :
string;
``````

Thanks Will.

And a jsfiddle for anyone who cares https://jsfiddle.net/t354gw7e/ :)

### Select objects based on value of variable in object using jq

Adapted from this post on Processing JSON with jq, you can use the `select(bool)` like this:

``````\$ jq '.[] | select(.location=="Stockholm")' json
{
"location": "Stockholm",
"name": "Walt"
}
{
"location": "Stockholm",
"name": "Donald"
}
``````

### One liner to check if element is in the list

There is a boolean contains(Object obj) method within the List interface.

You should be able to say:

``````if (list.contains("a")) {
System.out.println("It's there");
}
``````

```boolean contains(Object o)
```Returns true if this list contains the specified element.
More formally, returns true if and only if this list contains at
least one element e such that (o==null ? e==null : o.equals(e)).
``````

### How to clear jQuery validation error messages?

For those using Bootstrap 3 code below will clean whole form: messages, icons and colors...

``````\$('.form-group').each(function () { \$(this).removeClass('has-success'); });
\$('.form-group').each(function () { \$(this).removeClass('has-error'); });
\$('.form-group').each(function () { \$(this).removeClass('has-feedback'); });
\$('.help-block').each(function () { \$(this).remove(); });
\$('.form-control-feedback').each(function () { \$(this).remove(); });
``````

### Why do I keep getting Delete 'cr' [prettier/prettier]?

In my windows machine, I solved this by adding the below code snippet in `rules` object of `.eslintrc.js` file present in my current project's directory.

``````    "prettier/prettier": [
"error",
{
"endOfLine": "auto"
},
],
``````

This worked on my Mac as well

### Chrome dev tools fails to show response even the content returned has header Content-Type:text/html; charset=UTF-8

"Failed to show response data" can also happen if you are doing crossdomain requests and the remote host is not properly handling the CORS headers. Check your js console for errors.

### How do I capture the output of a script if it is being ran by the task scheduler?

To supplement @user2744787's answer, here is a screenshot to show how to use `cmd` with arguments in a Scheduled Task:

Program/script: `cmd`

Add arguments: `/c run_with_default_port.bat > IMQuantWebServices.log`

### How can I force users to access my page over HTTPS instead of HTTP?

I just created a .htaccess file and added :

``````RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
``````

Simple !

### What are the uses of "using" in C#?

It also can be used for creating scopes for Example:

``````class LoggerScope:IDisposable {
private LoggerScope previous;

public bool WithTime{get;}

public LoggerScope(bool withTime){
WithTime=withTime;
}

public void Dispose(){
}
}

class Program {
public static void Main(params string[] args){
new Program().Run();
}

public void Run(){
log("something happend!");
using(new LoggerScope(false)){
log("the quick brown fox jumps over the lazy dog!");
using(new LoggerScope(true)){
log("nested scope!");
}
}
}

void log(string message){
if(LoggerScope.Current!=null){
Console.WriteLine(message);
if(LoggerScope.Current.WithTime){
Console.WriteLine(DateTime.Now);
}
}
}

}
``````

### use video as background for div

#### Pure CSS method

It is possible to center a video inside an element just like a `cover` sized `background-image` without JS using the `object-fit` attribute or `CSS Transforms`.

As pointed in the comments, it is possible to achieve the same result without `CSS transform`, but using `object-fit`, which I think it's an even better option for the same result:

_x000D_
_x000D_
``````.video-container {
height: 300px;
width: 300px;
position: relative;
}

.video-container video {
width: 100%;
height: 100%;
position: absolute;
object-fit: cover;
z-index: 0;
}

/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
z-index: 1;
position: relative;
text-align: center;
color: #dc0000;
}``````
_x000D_
``````<div class="video-container">
<video autoplay muted loop>
</video>
<div class="caption">
</div>
</div>``````
_x000D_
_x000D_
_x000D_

You can set a video as a background to any HTML element easily thanks to `transform` CSS property.

Note that you can use the `transform` technique to center vertically and horizontally any HTML element.

_x000D_
_x000D_
``````.video-container {
height: 300px;
width: 300px;
overflow: hidden;
position: relative;
}

.video-container video {
min-width: 100%;
min-height: 100%;
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}

/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
z-index: 1;
position: relative;
text-align: center;
color: #dc0000;
}``````
_x000D_
``````<div class="video-container">
<video autoplay muted loop>
</video>
<div class="caption">
</div>
</div>``````
_x000D_
_x000D_
_x000D_

### What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

ObjectId is composed of following things.

1. a 4-byte value representing the seconds since the Unix epoch
2. a 5-byte random value (Machine ID 3 bytes and Processor id 2 bytes)
3. a 3-byte counter, starting with a random value.

Correct way to validate if the objectId is valid is by using static method from ObjectId class itself.

``````mongoose.Types.ObjectId.isValid(sample_object_id)
``````

### How can I decrease the size of Ratingbar?

`````` <RatingBar     android:id="@+id/id_tv_rating_bar"
style="@style/Widget.AppCompat.RatingBar.Small"
android:layout_width="wrap_content"
android:layout_height="@dimen/_20sdp"
android:layout_marginLeft="@dimen/_80sdp"
android:numStars="5"
android:rating="5" />
``````

Just use `style="@style/Widget.AppCompat.RatingBar.Small"` it'll work for Sure!

### tkinter: how to use after method

I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.

Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as `frame.after(500, function=None)`)

### Add timer to a Windows Forms application

Something like this in your form main. Double click the form in the visual editor to create the form load event.

`````` Timer Clock=new Timer();
Clock.Interval=2700000; // not sure if this length of time will work
Clock.Start();
Clock.Tick+=new EventHandler(Timer_Tick);
``````

Then add an event handler to do something when the timer fires.

``````  public void Timer_Tick(object sender,EventArgs eArgs)
{
if(sender==Clock)
{
// do something here
}
}
``````

### How to connect to LocalDB in Visual Studio Server Explorer?

#### Use SQL Server Object Explorer (SSOX) Instead

Unlike the other answers, this approach uses:
- No special commands.
- No complicated configurations.
Just use the SQL Server Object Explorer

It's pretty straightforward...

• From the View menu, open SQL Server Object Explorer.

• Right click on the `{YourTableName}` table > View Designer

Done.

### Get only the Date part of DateTime in mssql

This may also help:

``````SELECT convert(varchar, getdate(), 100) -- mon dd yyyy hh:mmAM (or PM)
-- Oct  2 2008 11:01AM
SELECT convert(varchar, getdate(), 101) -- mm/dd/yyyy - 10/02/2008
SELECT convert(varchar, getdate(), 102) -- yyyy.mm.dd – 2008.10.02
SELECT convert(varchar, getdate(), 103) -- dd/mm/yyyy
SELECT convert(varchar, getdate(), 104) -- dd.mm.yyyy
SELECT convert(varchar, getdate(), 105) -- dd-mm-yyyy
SELECT convert(varchar, getdate(), 106) -- dd mon yyyy
SELECT convert(varchar, getdate(), 107) -- mon dd, yyyy
SELECT convert(varchar, getdate(), 108) --  hh:mm:ss
SELECT convert(varchar, getdate(), 109) -- mon dd yyyy hh:mm:ss:mmmAM (or PM)
-- Oct  2 2008 11:02:44:013AM
SELECT convert(varchar, getdate(), 110) -- mm-dd-yyyy
SELECT convert(varchar, getdate(), 111) -- yyyy/mm/dd
SELECT convert(varchar, getdate(), 112) -- yyyymmdd
SELECT convert(varchar, getdate(), 113) -- dd mon yyyy hh:mm:ss:mmm
--  02 Oct 2008 11:02:07:577
SELECT convert(varchar, getdate(), 114) -- hh:mm:ss:mmm(24h)
SELECT convert(varchar, getdate(), 120) -- yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) --  yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) -- yyyy-mm-ddThh:mm:ss.mmm
--  2008-10-02T10:52:47.513
-- SQL create different date styles with t-sql string functions
SELECT replace(convert(varchar, getdate(), 111), '/', ' ') -- yyyy mm dd
SELECT convert(varchar(7), getdate(), 126)                 -- yyyy-mm
SELECT right(convert(varchar, getdate(), 106), 8)          -- mon yyyy
``````

The Source

### JavaScript: filter() for Objects

If you're willing to use underscore or lodash, you can use `pick` (or its opposite, `omit`).

Examples from underscore's docs:

``````_.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age');
// {name: 'moe', age: 50}
``````

Or with a callback (for lodash, use pickBy):

``````_.pick({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {
return _.isNumber(value);
});
// {age: 50}
``````

# `AtomicBoolean`

The succinct Answer by NPE sums up your three options. I'll add some example code for the second item listed there: `AtomicBoolean`.

You can think of the `AtomicBoolean` class as providing some thread-safety wrapping around a `boolean` value.

If you instantiate the `AtomicBoolean` only once, then you need not worry about the visibility issue in the Java Memory Model that requires `volatile` as a solution (the first item in that other Answer). Also, you need not concern yourself with synchronization (the third item in that other Answer) because `AtomicBoolean` performs that function of protecting multi-threaded access to its internal boolean value.

Let's look at some example code.

Firstly, in modern Java we generally do not address the `Thread` class directly. We now have the Executors framework to simplify handling of threads.

This code below is using Project Loom technology, coming to a future version of Java. Preliminary builds available now, built on early-access Java 16. This makes for simpler coding, with `ExecutorService` being `AutoCloseable` for convenient use with try-with-resources syntax. But Project Loom is not related to the point of this Answer; it just makes for simpler code that is easier to understand as “structured concurrency”.

The idea here is that we have three threads: the original thread, plus a `ExecutorService` that will create two more threads. The two new threads both report the value of our `AtomicBoolean`. The first new thread does so immediately, while the other waits 10 seconds before reporting. Meanwhile, our main thread sleeps for 5 seconds, wakes, changes the `AtomicBoolean` object’s contained value, and then waits for that second thread to wake and complete its work the report on the now-altered `AtomicBoolean` contained value. While we are installing seconds between each event, this is merely for dramatic demonstration. The real point is that these threads could coincidently try to access the `AtomicBoolean` simultaneously, but that object will protect access to its internal boolean value in a thread-safe manner. Protecting against simultaneous access is the job of the `Atomic…` classes.

``````try (
)
{
AtomicBoolean flag = new AtomicBoolean( true );

// This task, when run, will immediately report the flag.
Runnable task1 = ( ) -> System.out.println( "First task reporting flag = " + flag.get() + ". " + Instant.now() );

// This task, when run, will wait several seconds, then report the flag. Meanwhile, code below waits a shorter time before *changing* the flag.
Runnable task2 = ( ) -> {
try { Thread.sleep( Duration.ofSeconds( 10 ) ); } catch ( InterruptedException e ) { e.printStackTrace(); }
System.out.println( "Second task reporting flag = " + flag.get() + ". " + Instant.now() );
};

// Wait for first task to complete, so sleep here briefly. But wake before the sleeping second task awakens.
try { Thread.sleep( Duration.ofSeconds( 5 ) ); } catch ( InterruptedException e ) { e.printStackTrace(); }
System.out.println( "INFO - Original thread waking up, and setting flag to false. " + Instant.now() );
flag.set( false );
}
// At this point, with Project Loom technology, the flow-of-control blocks until the submitted tasks are done.
// Also, the `ExecutorService` is automatically closed/shutdown by this point, via try-with-resources syntax.
System.out.println( "INFO - Tasks on background threads are done. The `AtomicBoolean` and threads are gone." + Instant.now() );
``````

Methods such as `AtomicBoolean#get` and `AtomicBoolean#set` are built to be thread-safe, to internally protect access to the boolean value nested within. Read up on the various other methods as well.

When run:

``````First task reporting flag = true. 2021-01-05T06:42:17.367337Z
INFO - Original thread waking up, and setting flag to false. 2021-01-05T06:42:22.367456Z
Second task reporting flag = false. 2021-01-05T06:42:27.369782Z
``````

Pro Tip: When engaging in threaded code in Java, always study the excellent book, Java Concurrency in Practice by Brian Goetz et al.

### Check status of one port on remote host

Press Windows + R type `cmd` and Enter

In command prompt type

``````telnet "machine name/ip" "port number"
``````

If port is not open, this message will display:

``````"Connecting To "machine name"...Could not open connection to the host, on port "port number":
``````

Otherwise you will be take in to opened port (empty screen will display)

### Getting the name / key of a JToken with JSON.net

`JToken` is the base class for `JObject`, `JArray`, `JProperty`, `JValue`, etc. You can use the `Children<T>()` method to get a filtered list of a JToken's children that are of a certain type, for example `JObject`. Each `JObject` has a collection of `JProperty` objects, which can be accessed via the `Properties()` method. For each `JProperty`, you can get its `Name`. (Of course you can also get the `Value` if desired, which is another `JToken`.)

Putting it all together we have:

``````JArray array = JArray.Parse(json);

foreach (JObject content in array.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
Console.WriteLine(prop.Name);
}
}
``````

Output:

``````MobileSiteContent
PageContent
``````

### jQuery .on('change', function() {} not triggering for dynamically created inputs

You should provide a selector to the `on` function:

``````\$(document).on('change', 'input', function() {
// Does some stuff and logs the event to the console
});
``````

In that case, it will work as you expected. Also, it is better to specify some element instead of document.

### Hibernate dialect for Oracle Database 11g?

Add org.hibernate.dialect.OracleDialect for Oracle11g database. It will resolve this error.

### What does getActivity() mean?

getActivity()- Return the Activity this fragment is currently associated with.

### C/C++ check if one bit is set in, i.e. int variable

The precedent answers show you how to handle bit checks, but more often then not, it is all about flags encoded in an integer, which is not well defined in any of the precedent cases.

In a typical scenario, flags are defined as integers themselves, with a bit to 1 for the specific bit it refers to. In the example hereafter, you can check if the integer has ANY flag from a list of flags (multiple error flags concatenated) or if EVERY flag is in the integer (multiple success flags concatenated).

Following an example of how to handle flags in an integer.

Live example available here: https://rextester.com/XIKE82408

``````//g++  7.4.0

#include <iostream>
#include <stdint.h>

inline bool any_flag_present(unsigned int value, unsigned int flags) {
return bool(value & flags);
}

inline bool all_flags_present(unsigned int value, unsigned int flags) {
return (value & flags) == flags;
}

enum: unsigned int {
ERROR_1 = 1U,
ERROR_2 = 2U, // or 0b10
ERROR_3 = 4U, // or 0b100
SUCCESS_1 = 8U,
SUCCESS_2 = 16U,
OTHER_FLAG = 32U,
};

int main(void)
{
unsigned int value = 0b101011; // ERROR_1, ERROR_2, SUCCESS_1, OTHER_FLAG
unsigned int all_error_flags = ERROR_1 | ERROR_2 | ERROR_3;
unsigned int all_success_flags = SUCCESS_1 | SUCCESS_2;

std::cout << "Was there at least one error: " << any_flag_present(value, all_error_flags) << std::endl;
std::cout << "Are all success flags enabled: " << all_flags_present(value, all_success_flags) << std::endl;
std::cout << "Is the other flag enabled with eror 1: " << all_flags_present(value, ERROR_1 | OTHER_FLAG) << std::endl;
return 0;
}
``````

### How to center absolute div horizontally using CSS?

Centering div with position: absolute and width: unknown:

HTML:

``````<div class="center">
<span></span>

<div>
content...
</div>

</div>
``````

CSS:

``````.center{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: grid;
grid-template-columns: auto auto;
overflow: auto;
}
``````

### Generating UNIQUE Random Numbers within a range

This is how I would do it.

``````\$randnum1 = mt_rand(1,20);

\$nomatch = 0;

while(\$nomatch == 0){

\$randnum2 = mt_rand(1,20);

if(\$randnum2 != \$randnum1){

\$nomatch = 1;

}

}

\$nomatch = 0;

while(\$nomatch == 0){

\$randnum3 = mt_rand(1,20);

if((\$randnum3 != \$randnum1)and(\$randnum3 != \$randnum2)){

\$nomatch = 1;

}

}
``````

Then you can echo the results to check

``````echo "Random numbers are " . \$randnum1 . "," . \$randnum2 . ", and " . \$randnum3 . "\n";
``````

### Getting HTTP headers with Node.js

Try to look at http.get and response headers.

``````var http = require("http");

var options = {
host: 'stackoverflow.com',
port: 80,
path: '/'
};

http.get(options, function(res) {
console.log("Got response: " + res.statusCode);

console.log(item + ": " + res.headers[item]);
}
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
``````

### DataTrigger where value is NOT null?

Stop! No converter! I dont want to "sell" the library of this guy, but I hated the fact of doing converter everytime I wanted to compare stuff in XAML.

So with this library : https://github.com/Alex141/CalcBinding

you can do that [and a lot more] :

First, In the declaration of the windows/userControl :

``````<Windows....
xmlns:conv="clr-namespace:CalcBinding;assembly=CalcBinding"
>
``````

then, in the textblock

``````<TextBlock>
<TextBlock.Style>
<Style.Triggers>
<DataTrigger Binding="{conv:Binding 'MyValue==null'}" Value="false">
<Setter Property="Background" Value="#FF80C983"></Setter>
</DataTrigger>
</Style.Triggers>
</TextBlock.Style>
</TextBlock>
``````

The magic part is the conv:Binding 'MYValue==null'. In fact, you could set any condition you wanted [look at the doc].

note that I am not a fan of third party. but this library is Free, and little impact (just add 2 .dll to the project).

### Spring MVC - Why not able to use @RequestBody and @RequestParam together

You could also just change the @RequestParam default required status to false so that HTTP response status code 400 is not generated. This will allow you to place the Annotations in any order you feel like.

``````@RequestParam(required = false)String name
``````

### Converting string to double in C#

There are 3 problems.

1) Incorrect decimal separator

Different cultures use different decimal separators (namely `,` and `.`).

If you replace `.` with `,` it should work as expected:

``````Console.WriteLine(Convert.ToDouble("52,8725945"));
``````

You can parse your doubles using overloaded method which takes culture as a second parameter. In this case you can use `InvariantCulture` (What is the invariant culture) e.g. using `double.Parse`:

``````double.Parse("52.8725945", System.Globalization.CultureInfo.InvariantCulture);
``````

You should also take a look at `double.TryParse`, you can use it with many options and it is especially useful to check wheter or not your string is a valid `double`.

2) You have an incorrect double

One of your values is incorrect, because it contains two dots:

`15.5859949000000662452.23862099999999`

3) Your array has an empty value at the end, which is an incorrect double

You can use overloaded `Split` which removes empty values:

```string[] someArray = a.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries); ```

### How to check if PHP array is associative or sequential?

Best function to detect associative array (hash array)

``````<?php
function is_assoc(\$arr) { return (array_values(\$arr) !== \$arr); }
?>
``````

### \$apply already in progress error

I call \$scope.\$apply like this to ignored call multiple in one times.

``````      var callApplyTimeout = null;
function callApply(callback) {
if (!callback) callback = function () { };
if (callApplyTimeout) \$timeout.cancel(callApplyTimeout);

callApplyTimeout = \$timeout(function () {
callback();
\$scope.\$apply();
var d = new Date();
var m = d.getMilliseconds();
console.log('\$scope.\$apply(); call ' + d.toString() + ' ' + m);
}, 300);
}
``````

simply call

``````callApply();
``````

### Something better than .NET Reflector?

I am not sure what you really want here. If you want to see the .NET framework source code, you may try Netmassdownloader. It's free.

If you want to see any assembly's code (not just .NET), you can use ReSharper. Although it's not free.

### Beautiful Soup and extracting a div and its contents by ID

I used:

``````soup.findAll('tag', attrs={'attrname':"attrvalue"})
``````

As my syntax for find/findall; that said, unless there are other optional parameters between the tag and attribute list, this shouldn't be different.

### How to top, left justify text in a <td> cell that spans multiple rows

``````td[rowspan] {
vertical-align: top;
text-align: left;
}
``````

### Serializing list to JSON

You can use pure Python to do it:

``````import json
list = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4)
json.dumps(list) # '[1, 2, [3, 4]]'
``````

### JavaScript dictionary with names

An easier, native and more efficient way of emulating a dict in JavaScript than a hash table:

It also exploits that JavaScript is weakly typed. Rather type inference.

Here's how (an excerpt from Google Chrome's console):

``````var myDict = {};

myDict.one = 1;
1

myDict.two = 2;
2

if (myDict.hasOwnProperty('three'))
{
console.log(myDict.two);
}
else
{
console.log('Key does not exist!');
}
Key does not exist! VM361:8

if (myDict.hasOwnProperty('two'))
{
console.log(myDict.two);
}
else
{
console.log('Key does not exist!');
}
2 VM362:4

Object.keys(myDict);
["one", "two"]

delete(myDict.two);
true

myDict.hasOwnProperty('two');
false

myDict.two
undefined

myDict.one
1
``````

### Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

``````/link/mybackend/?field1=value1&field2=value2&field3=value3
``````

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via `request.GET`.

``````url(r'^link/(?P<backend>\w+?)/\$', my_function)
``````

and the view would look like:

``````def my_function(request, backend):
data = request.GET
``````

and the reverse would be (after importing `urllib`):

``````return "%s?%s" % (redirect('my_function', args=(backend,)),
urllib.urlencode(form.cleaned_data))
``````

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

``````request.session['temp_data'] = form.cleaned_data
``````

### jQuery Validate - Enable validation for hidden fields

This worked for me within an ASP.NET site. To enable validation on some hidden fields use this code

`\$("form").data("validator").settings.ignore = ":hidden:not(#myitem)";`

To enable validation for all elements of form use this one `\$("form").data("validator").settings.ignore = "";`

Note that use them within `\$(document).ready(function() { })`

### What is the precise meaning of "ours" and "theirs" in git?

I'll post my memo here, because I have to come back here again and again.

SCENARIO 1. Normal developer: You are developer who can't merge to `master` and have to play with `feature` branches only.

Case 1: master is a king. You want to refresh your `feature` branch (= rebase to `master`), because `master` contains new updates of dependencies and you want to overwrite your modest changes.

``````git checkout master
git pull

git checkout feature
git rebase -X ours master
``````

Case 2: you are a king. You want to rebase your `feature` branch to `master` changes. But you did more than your colleagues had and want to use your own changes in a priority.

``````git checkout master
git pull

git checkout feature
git rebase -X theirs master
``````

IMPORTANT: As you can see normal developers should prefer `rebase` and repeat it every morning like exercises/coffee.

SCENARIO 2. Merging-sensei: You are a team-lead and want to merge other branches and push a merged result directly to a master. `master` is a branch you will change.

Case 1: master is a king You want to merge third-party branch, but `master` is a priority. `feature` is a branch that your senior did.

``````git checkout feature
git pull

git checkout master
git merge -X ours feature
``````

Case 2: new changes is a king When your senior developer released a cool `feature` and you want to overwrite the old s**t in the `master` branch.

``````git checkout feature
git pull

git checkout master
git merge -X theirs feature
``````

REMEMBER: To remember in a midnight which one to choose: `master` is `ours` ALWAYS. And `theirs` is a `feature` that theirs have done.

### Why doesn't calling a Python string method do anything unless you assign its output?

All string functions as `lower`, `upper`, `strip` are returning a string without modifying the original. If you try to modify a string, as you might think `well it is an iterable`, it will fail.

``````x = 'hello'
x[0] = 'i' #'str' object does not support item assignment
``````

There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them

### How do I disable log messages from the Requests library?

In case you came here looking for a way to modify logging of any (possibly deeply nested) module, use `logging.Logger.manager.loggerDict` to get a dictionary of all of the logger objects. The returned names can then be used as the argument to `logging.getLogger`:

``````import requests
import logging
for key in logging.Logger.manager.loggerDict:
print(key)
# requests.packages.urllib3.connectionpool
# requests.packages.urllib3.util
# requests.packages
# requests.packages.urllib3
# requests.packages.urllib3.util.retry
# requests
# requests.packages.urllib3.poolmanager

logging.getLogger('requests').setLevel(logging.CRITICAL)
# Could also use the dictionary directly:
# logging.Logger.manager.loggerDict['requests'].setLevel(logging.CRITICAL)
``````

Per user136036 in a comment, be aware that this method only shows you the loggers that exist at the time you run the above snippet. If, for example, a module creates a new logger when you instantiate a class, then you must put this snippet after creating the class in order to print its name.

### build maven project with propriatery libraries included

Why not run something like Nexus, your own maven repo that you can upload 3rd party proprietary jar files, and also proxy other public repositories, to save on bandwith?

This also has some good reasons to run your own maven repository manager.

### How to validate a credit card number

You define the variable name `re16digit` but later refer to it as `re10digit`, which will throw an error. To simplify your code, you should use `RegExp.prototype.test()` rather than `String.prototype.search()`:

``````function validate_creditcardnumber() {
var re16digit = /^\d{16}\$/;
if (!re16digit.test(document.myform.CreditCardNumber.value)) {
return false;
}
}
``````

Working demo: http://jsfiddle.net/Dxjkh/

As others have mentioned, you may be better off using a JavaScript implementation of the Luhn Algorithm. It's also worth mentioning that a check for 16 digits will fail for American Express (15 digits) and Diners (14 digits) cards.

### More Pythonic Way to Run a Process X Times

There is not a really pythonic way of repeating something. However, it is a better way:

``````map(lambda index:do_something(), xrange(10))
``````

If you need to pass the index then:

``````map(lambda index:do_something(index), xrange(10))
``````

Consider that it returns the results as a collection. So, if you need to collect the results it can help.

### Convert a number into a Roman Numeral in javaScript

I tried to do this by mapping an array of the arabic numerals to an array of pairs of roman. The nasty 3-level ternaries could be replaced by if() {} else{} blocks to make it more readable. It works from 1 to 3999 but could be extended:

``````function romanize(num) {
if(num > 3999 || num < 1) return 'outside range!';
const roman = [ ['M', ''], [ 'C', 'D' ], [ 'X', 'L' ], [ 'I', 'V' ] ];
return arabic.map((e, i) => {
return (
e < 9 ? roman[i][1].repeat(Math.floor(e / 5)) : ''
) + (
e % 5 < 4
? roman[i][0].repeat(Math.floor(e % 5))
: e % 5 === 4 && Math.floor(e / 5) === 0
? roman[i][0] + roman[i][1]
: Math.floor(e / 5) === 1
? roman[i][0] + roman[i - 1][0]
: ''
);
}).join('');
}
``````

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

High performance - every `Double` object wraps a single `double` value. If you want to store all these values into a `double[]` array, then you have to iterate over the collection of `Double` instances. A `O(1)` mapping is not possible, this should be the fastest you can get:

`````` double[] target = new double[doubles.size()];
for (int i = 0; i < target.length; i++) {
target[i] = doubles.get(i).doubleValue();  // java 1.4 style
// or:
target[i] = doubles.get(i);                // java 1.5+ style (outboxing)
}
``````

Thanks for the additional question in the comments ;) Here's the sourcecode of the fitting `ArrayUtils#toPrimitive` method:

``````public static double[] toPrimitive(Double[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_DOUBLE_ARRAY;
}
final double[] result = new double[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].doubleValue();
}
return result;
}
``````

(And trust me, I didn't use it for my first answer - even though it looks ... pretty similiar :-D )

By the way, the complexity of Marcelos answer is O(2n), because it iterates twice (behind the scenes): first to make a `Double[]` from the list, then to unwrap the `double` values.

### C# Iterate through Class properties

Yes, you could make an indexer on your Record class that maps from the property name to the correct property. This would keep all the binding from property name to property in one place eg:

``````public class Record
{
public string ItemType { get; set; }

public string this[string propertyName]
{
set
{
switch (propertyName)
{
case "itemType":
ItemType = value;
break;
// etc
}
}
}
}
``````

Alternatively, as others have mentioned, use reflection.

### What is git tag, How to create tags & How to checkout git remote tag(s)

This is bit out of context but in case you are here because you want to tag a specific commit like i do

Here's a command to do that :-

Example:

``````git tag -a v1.0 7cceb02 -m "Your message here"
``````

Where `7cceb02` is the beginning part of the commit id.

You can then push the tag using `git push origin v1.0`.

You can do `git log` to show all the commit id's in your current branch.

### How to delete columns in numpy.array

In your situation, you can extract the desired data with:

``````a[:, -z]
``````

"-z" is the logical negation of the boolean array "z". This is the same as:

``````a[:, logical_not(z)]
``````

### How to validate an email address using a regular expression?

There are plenty examples of this out on the net (and I think even one that fully validates the RFC - but it's tens/hundreds of lines long if memory serves). People tend to get carried away validating this sort of thing. Why not just check it has an @ and at least one . and meets some simple minimum length. It's trivial to enter a fake email and still match any valid regex anyway. I would guess that false positives are better than false negatives.

### SQL Server r2 installation error .. update Visual Studio 2008 to SP1

Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:

1. Install Visual Studio 2008
2. Install the service Package 1 (SP1)
3. Install SQL Server 2008 r2

### Set IDENTITY_INSERT ON is not working

In VB code, when trying to submit an `INSERT` query, you must submit a double query in the same 'executenonquery' like this:

``````sqlQuery = "SET IDENTITY_INSERT dbo.TheTable ON; INSERT INTO dbo.TheTable (Col1, COl2) VALUES (Val1, Val2); SET IDENTITY_INSERT dbo.TheTable OFF;"
``````

I used a `;` separator instead of a GO.

Works for me. Late but efficient!

### The service cannot accept control messages at this time

In my case, the VS debugger was attached to the w3wp process. After detaching the debugger, I was able to restart the Application Pool

### The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

I got this error after I changed my model (code first) as follows:

``````public DateTime? DateCreated
``````

to

``````public DateTime DateCreated
``````

Present rows with null-value in DateCreated caused this error. So I had to use SQL UPDATE Statement manually for initializing the field with a standard value.

Another solution could be a specifying of the default value for the filed.

### Print a list of all installed node.js modules

``````for package in `sudo npm -g ls --depth=0 --parseable`; do
printf "\${package##*/}\n";
done
``````

### SQL subquery with COUNT help

This is probably the easiest way, not the prettiest though:

``````SELECT *,
(SELECT Count(*) FROM eventsTable WHERE columnName = 'Business') as RowCount
FROM eventsTable
``````

This will also work without having to use a `group by`

``````SELECT *, COUNT(*) OVER () as RowCount
FROM eventsTables
``````

### Attach the Source in Eclipse of a jar

I have faced same problem and resolved it by using following scenario.

1 ) First we have to determine which jar file's source code we want along with version number. For Example "Spring Core » 4.0.6.RELEASE" 2 ) open https://mvnrepository.com/ and search file with name "Spring Core » 4.0.6.RELEASE". 3 ) Now Maven repository will show the the details of that jar file. 4 ) In that details there is one option "View All" just click on that. 5 ) Then we will navigate to URL "https://repo1.maven.org/maven2/org/springframework/spring-core/4.0.6.RELEASE/".

6) there so many options so select and download "spring-core-4.0.6.RELEASE-sources.jar " in our our system and attach same jar file as a source attachment in eclipse.

### Apache - MySQL Service detected with wrong path. / Ports already in use

Ok so i found out the problem :)

ctrl+alt+delete to start task manager, once you get to task manager go to services. find MySQL and right click on it. Then click stop process. That worked for me and i hope it works for you :D

### What does the keyword Set actually do in VBA?

`set` is used to assign a reference to an object. The C equivalent would be

`````` int i;
int* ref_i;

i = 4; // Assigning a value (in VBA: i = 4)
ref_i = &i; //assigning a reference (in VBA: set ref_i = i)
``````

### How do I jump to a closing bracket in Visual Studio Code?

The out-of-the-box way to do it is

``````Ctrl + Shift + |
``````

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

U wrote an unnecessary div, just leave it like this

_x000D_
_x000D_
``````<div id="texts" style="white-space:nowrap;">
<img src="tree.png"  align="left"/>
A very long text(about 300 words)
</div>``````
_x000D_
_x000D_
_x000D_

What u are looking for is white-space:nowrap; this code will do the trick.

### VB.net: Date without time

FormatDateTime(Now, DateFormat.ShortDate)

### How to load data to hive from HDFS without removing the source file?

I found that, when you use EXTERNAL TABLE and LOCATION together, Hive creates table and initially no data will present (assuming your data location is different from the Hive 'LOCATION').

When you use 'LOAD DATA INPATH' command, the data get MOVED (instead of copy) from data location to location that you specified while creating Hive table.

If location is not given when you create Hive table, it uses internal Hive warehouse location and data will get moved from your source data location to internal Hive data warehouse location (i.e. /user/hive/warehouse/).

### Strip / trim all strings of a dataframe

You can use `DataFrame.select_dtypes` to select `string` columns and then `apply` function `str.strip`.

Notice: Values cannot be `types` like `dicts` or `lists`, because their `dtypes` is `object`.

``````df_obj = df.select_dtypes(['object'])
print (df_obj)
0    a
1    c

df[df_obj.columns] = df_obj.apply(lambda x: x.str.strip())
print (df)

0   1
0  a  10
1  c   5
``````

But if there are only a few columns use `str.strip`:

``````df[0] = df[0].str.strip()
``````

### How to Right-align flex item?

A more flex approach would be to use an `auto` left margin (flex items treat auto margins a bit differently than when used in a block formatting context).

``````.c {
margin-left: auto;
}
``````

Updated fiddle:

_x000D_
_x000D_
``````.main { display: flex; }_x000D_
.a, .b, .c { background: #efefef; border: 1px solid #999; }_x000D_
.b { flex: 1; text-align: center; }_x000D_
.c {margin-left: auto;}``````
_x000D_
``````<h2>With title</h2>_x000D_
<div class="main">_x000D_
<div class="a"><a href="#">Home</a></div>_x000D_
<div class="b"><a href="#">Some title centered</a></div>_x000D_
<div class="c"><a href="#">Contact</a></div>_x000D_
</div>_x000D_
<h2>Without title</h2>_x000D_
<div class="main">_x000D_
<div class="a"><a href="#">Home</a></div>_x000D_
<!--<div class="b"><a href="#">Some title centered</a></div>-->_x000D_
<div class="c"><a href="#">Contact</a></div>_x000D_
</div>_x000D_
<h1>Problem</h1>_x000D_
<p>Is there a more flexbox-ish way to right align "Contact" than to use position absolute?</p>``````
_x000D_
_x000D_
_x000D_

### ps command doesn't work in docker container

If you're running a CentOS container, you can install ps using this command:

``````yum install -y procps
``````

Running this command on Dockerfile:

``````RUN yum install -y procps
``````

### pandas dataframe columns scaling with sklearn

I am not sure if previous versions of `pandas` prevented this but now the following snippet works perfectly for me and produces exactly what you want without having to use `apply`

``````>>> import pandas as pd
>>> from sklearn.preprocessing import MinMaxScaler

>>> scaler = MinMaxScaler()

>>> dfTest = pd.DataFrame({'A':[14.00,90.20,90.95,96.27,91.21],
'B':[103.02,107.26,110.35,114.23,114.68],
'C':['big','small','big','small','small']})

>>> dfTest[['A', 'B']] = scaler.fit_transform(dfTest[['A', 'B']])

>>> dfTest
A         B      C
0  0.000000  0.000000    big
1  0.926219  0.363636  small
2  0.935335  0.628645    big
3  1.000000  0.961407  small
4  0.938495  1.000000  small
``````

### Apply function to pandas groupby

Regarding the issue with 'size', size is not a function on a dataframe, it is rather a property. So instead of using size(), plain size should work

Apart from that, a method like this should work

`````` def doCalculation(df):
groupCount = df.size
groupSum = df['my_labels'].notnull().sum()

return groupCount / groupSum

dataFrame.groupby('my_labels').apply(doCalculation)
``````

### How to properly upgrade node using nvm

Node.JS to install a new version.

Step 1 : NVM Install

`npm i -g nvm`

Step 2 : NODE Newest version install

`nvm install *.*.*(NodeVersion)`

Step 3 : Selected Node Version

`nvm use *.*.*(NodeVersion)`

Finish

### Add a summary row with totals

You could use the ROLLUP operator

``````SELECT  CASE
WHEN (GROUPING([Type]) = 1) THEN 'Total'
ELSE [Type] END AS [TYPE]
,SUM([Total Sales]) as Total_Sales
From    Before
GROUP BY
[Type] WITH ROLLUP
``````

### Moving Git repository content to another repository preserving history

If you're looking to preserve the existing branches and commit history, here's one way that worked for me.

``````git clone --mirror https://github.com/account/repo.git cloned-repo
cd cloned-repo
git push --mirror {URL of new (empty) repo}

# at this point only remote cloned-repo is correct, local has auto-generated repo structure with folders such as "branches" or "refs"
cd ..
rm -rf cloned-repo
git clone {URL of new (empty) repo}
# only now will you see the expected user-generated contents in local cloned-repo folder

# note: all non-master branches are avaialable, but git branch will not show them until you git checkout each of them
# to automatically checkout all remote branches use this loop:
for b in `git branch -r | grep -v -- '->'`; do git branch --track \${b##origin/} \$b; done
``````

Now, suppose you want to keep the source and destination repos in sync for a period of time. For example, there's still activity within the current remote repo that you want to bring over to the new/replacement repo.

``````git clone -o old https://github.com/account/repo.git my-repo
cd my-repo
git remote add new {URL of new repo}
``````

To pull down the latest updates (assuming you have no local changes):

``````git checkout {branch(es) of interest}
git pull old
git push --all new
``````

NB: I have yet to use submodules, so I don't know what additional steps might be required if you have them.

### Difference between save and saveAndFlush in Spring data jpa

Depending on the hibernate flush mode that you are using (`AUTO` is the default) `save` may or may not write your changes to the DB straight away. When you call `saveAndFlush` you are enforcing the synchronization of your model state with the DB.

If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between `save()` and `saveAndFlush()` because the select triggers a flush first. See the documention.

### Image vs Bitmap class

Image provides an abstract access to an arbitrary image , it defines a set of methods that can loggically be applied upon any implementation of Image. Its not bounded to any particular image format or implementation . Bitmap is a specific implementation to the image abstract class which encapsulate windows GDI bitmap object. Bitmap is just a specific implementation to the Image abstract class which relay on the GDI bitmap Object.

You could for example , Create your own implementation to the Image abstract , by inheriting from the Image class and implementing the abstract methods.

Anyway , this is just a simple basic use of OOP , it shouldn't be hard to catch.

### Incrementing a variable inside a Bash loop

Using the following 1 line command for changing many files name in linux using phrase specificity:

``````find -type f -name '*.jpg' | rename 's/holiday/honeymoon/'
``````

For all files with the extension ".jpg", if they contain the string "holiday", replace it with "honeymoon". For instance, this command would rename the file "ourholiday001.jpg" to "ourhoneymoon001.jpg".

This example also illustrates how to use the find command to send a list of files (-type f) with the extension .jpg (-name '*.jpg') to rename via a pipe (|). rename then reads its file list from standard input.

### How do I limit the number of rows returned by an Oracle query after ordering?

I'v started preparing for Oracle 1z0-047 exam, validated against 12c While prepping for it i came across a 12c enhancement known as 'FETCH FIRST' It enables you to fetch rows /limit rows as per your convenience. Several options are available with it

``````- FETCH FIRST n ROWS ONLY
- OFFSET n ROWS FETCH NEXT N1 ROWS ONLY // leave the n rows and display next N1 rows
- n % rows via FETCH FIRST N PERCENT ROWS ONLY
``````

Example:

``````Select * from XYZ a
order by a.pqr
FETCH FIRST 10 ROWS ONLY
``````

Dispite what the accepted answer says in the comments, the correct way to install 'Memcache' is:

``````sudo apt-get install php5-memcache
``````

NOTE Memcache & Memcached are two distinct although related pieces of software, that are often confused.

EDIT As this is now an old post I thought it worth mentioning that you should replace php5 with your php version number.

### Assign output to variable in Bash

In shell, you don't put a \$ in front of a variable you're assigning. You only use \$IP when you're referring to the variable.

``````#!/bin/bash

IP=\$(curl automation.whatismyip.com/n09230945.asp)

echo "\$IP"

sed "s/IP/\$IP/" nsupdate.txt | nsupdate
``````

### Can I load a UIImage from a URL?

The way using a Swift Extension to `UIImageView` (source code here):

#### Creating Computed Property for Associated `UIActivityIndicatorView`

``````import Foundation
import UIKit
import ObjectiveC

private var activityIndicatorAssociationKey: UInt8 = 0

extension UIImageView {
//Associated Object as Computed Property
var activityIndicator: UIActivityIndicatorView! {
get {
return objc_getAssociatedObject(self, &activityIndicatorAssociationKey) as? UIActivityIndicatorView
}
set(newValue) {
objc_setAssociatedObject(self, &activityIndicatorAssociationKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
}
}

private func ensureActivityIndicatorIsAnimating() {
if (self.activityIndicator == nil) {
self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
self.activityIndicator.hidesWhenStopped = true
let size = self.frame.size;
self.activityIndicator.center = CGPoint(x: size.width/2, y: size.height/2);
self.activityIndicator.startAnimating()
})
}
}
``````

#### Custom Initializer and Setter

``````    convenience init(URL: NSURL, errorImage: UIImage? = nil) {
self.init()
self.setImageFromURL(URL)
}

func setImageFromURL(URL: NSURL, errorImage: UIImage? = nil) {
self.ensureActivityIndicatorIsAnimating()
if (error == nil) {
self.activityIndicator.stopAnimating()
self.image = UIImage(data: data)
})
}
else {
self.image = errorImage
}
}
}
}
``````

### How can I verify if an AD account is locked?

The `LockedOut` property is what you are looking for among all the properties you returned. You are only seeing incomplete output in TechNet. The information is still there. You can isolate that one property using `Select-Object`

``````Get-ADUser matt -Properties * | Select-Object LockedOut

LockedOut
---------
False
``````

Note: Try to avoid `-Properties *`. While it is great for simple testing it can make queries, especially ones with multiple accounts, unnecessarily slow. So, in this case, since you only need `lockedout`:

``````Get-ADUser matt -Properties LockedOut | Select-Object LockedOut
``````

### How to add calendar events in Android?

Just in case if someone needs this for Xamarin in c#:

``````        Intent intent = new Intent(Intent.ActionInsert);
intent.SetData(Android.Provider.CalendarContract.Events.ContentUri);
intent.PutExtra(Android.Provider.CalendarContract.ExtraEventBeginTime, Utils.Tools.CurrentTimeMillis(game.Date));
intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.AllDay, false);
intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.EventLocation, "Location");
intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.Description, "Description");
intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.Title, "Title");
StartActivity(intent);
``````

Helper Functions:

``````    private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

public static long CurrentTimeMillis(DateTime date)
{
return (long)(date.ToUniversalTime() - Jan1st1970).TotalMilliseconds;
}
``````

### how to generate a unique token which expires after 24 hours?

you need to store the token while creating for 1st registration. When you retrieve data from login table you need to differentiate entered date with current date if it is more than 1 day (24 hours) you need to display message like your token is expired.

To generate key refer here

### Format date and Subtract days using Moment.js

``````startdate = moment().subtract(1, 'days').format('DD-MM-YYYY');
``````

### How to check file input size with jQuery?

Use below to check file's size and clear if it's greater,

``````    \$("input[type='file']").on("change", function () {
if(this.files[0].size > 2000000) {
\$(this).val('');
}
});
``````

### How to know user has clicked "X" or the "Close" button?

The `CloseReason` enumeration you found on MSDN is just for the purpose of checking whether the user closed the app, or it was due to a shutdown, or closed by the task manager, etc...

You can do different actions, according to the reason, like:

``````void Form_FormClosing(object sender, FormClosingEventArgs e)
{
if(e.CloseReason == CloseReason.UserClosing)
// Prompt user to save his data

if(e.CloseReason == CloseReason.WindowsShutDown)
// Autosave and clear up ressources
}
``````

But like you guessed, there is no difference between clicking the x button, or rightclicking the taskbar and clicking 'close', or pressing Alt F4, etc. It all ends up in a `CloseReason.UserClosing` reason.

### Creating a border like this using :before And :after Pseudo-Elements In CSS?

``````#footer:after
{
content: "";
width: 40px;
height: 3px;
background-color: #529600;
left: 0;
position: relative;
display: block;
top: 10px;
}
``````

To the best of my memory, a physical address is an explicit, set in stone address in memory, while a logical address consists of a base pointer and offset.

The reason is as you have basically specified. It allows for not only the segmentation of programs and processes into threads and data, but also for the dynamic loading of such programs, and the allowance for at least pseudo-parallelism, without any actual interlacing of instructions in memory needing to take place.

### How to save data in an android app

You have two options, and I'll leave selection up to you.

1. Shared Preferences

This is a framework unique to Android that allows you to store primitive values (such as `int`, `boolean,` and `String`, although strictly speaking `String` isn't a primitive) in a key-value framework. This means that you give a value a name, say, "homeScore" and store the value to this key.

``````SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("homeScore", YOUR_HOME_SCORE);

// Apply the edits!
editor.apply();

// Get from the SharedPreferences
SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
int homeScore = settings.getInt("homeScore", 0);
``````
2. Internal Storage

This, in my opinion, is what you might be looking for. You can store anything you want to a file, so this gives you more flexibility. However, the process can be trickier because everything will be stored as bytes, and that means you have to be careful to keep your read and write processes working together.

``````int homeScore;
byte[] homeScoreBytes;

homeScoreBytes[0] = (byte) homeScore;
homeScoreBytes[1] = (byte) (homeScore >> 8);  //you can probably skip these two
homeScoreBytes[2] = (byte) (homeScore >> 16); //lines, because I've never seen a
//such a rare occurance.

FileOutputStream outputStream = getApplicationContext().openFileOutput(FILENAME, Context.MODE_PRIVATE);
outputStream.write(homeScoreBytes);
outputStream.close();
``````

Now, you can also look into External Storage, but I don't recommend that in this particular case, because the external storage might not be there later. (Note that if you pick this, it requires a permission)

### How to retrieve the dimensions of a view?

As F.X. mentioned, you can use an `OnLayoutChangeListener` to the view that you want to track itself

``````view.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
// Make changes
}
});
``````

You can remove the listener in the callback if you only want the initial layout.

### \$location / switching between html5 and hashbang mode / link rewriting

Fur future readers, if you are using Angular 1.6, you also need to change the `hashPrefix`:

``````appModule.config(['\$locationProvider', function(\$locationProvider) {
\$locationProvider.html5Mode(true);
\$locationProvider.hashPrefix('');
}]);
``````

Don't forget to set the base in your HTML `<head>`:

``````<head>
<base href="/">
...
``````

### Excel telling me my blank cells aren't blank

Goto->Special->blanks does not like merged cells. Try unmerging cells above the range in which you want to select blanks then try again.

### Getting distance between two points based on latitude/longitude

Edit: Just as a note, if you just need a quick and easy way of finding the distance between two points, I strongly recommend using the approach described in Kurt's answer below instead of re-implementing Haversine -- see his post for rationale.

This answer focuses just on answering the specific bug OP ran into.

It's because in Python, all the trig functions use radians, not degrees.

You can either convert the numbers manually to radians, or use the `radians` function from the math module:

``````from math import sin, cos, sqrt, atan2, radians

# approximate radius of earth in km
R = 6373.0

dlon = lon2 - lon1
dlat = lat2 - lat1

a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))

distance = R * c

print("Result:", distance)
print("Should be:", 278.546, "km")
``````

The distance is now returning the correct value of `278.545589351` km.

### Convert string to int array using LINQ

Here's code that filters out invalid fields:

``````    var ints = from field in s1.Split(';').Where((x) => { int dummy; return Int32.TryParse(x, out dummy); })
select Int32.Parse(field);
``````

### Restart container within pod

There are cases when you want to restart a specific container instead of deleting the pod and letting Kubernetes recreate it.

Doing a `kubectl exec POD_NAME -c CONTAINER_NAME /sbin/killall5` worked for me.

(I changed the command from `reboot` to `/sbin/killall5` based on the below recommendations.)

### Declaring a variable and setting its value from a SELECT query in Oracle

When you are converting from `tsql` to `plsql` you have to worry about `no_data_found` exception

``````DECLARE
v_var NUMBER;
BEGIN
SELECT clmn INTO v_var FROM tbl;
Exception when no_data_found then v_var := null; --what ever handle the exception.
END;
``````

In `tsql` if `no data found` then the variable will be `null` but no `exception`

### caching JavaScript files

``````#Create filter to match files you want to cache
<Files *.js>
</Files>
``````

I wrote about it here also:

http://betterexplained.com/articles/how-to-optimize-your-site-with-http-caching/

### Storing and retrieving datatable from session

You can do it like that but storing a DataSet object in Session is not very efficient. If you have a web app with lots of users it will clog your server memory really fast.

If you really must do it like that I suggest removing it from the session as soon as you don't need the DataSet.

### How do you convert a byte array to a hexadecimal string in C?

I know this question already has an answer but I think my solution could help someone.

So, in my case I had a byte array representing the key and I needed to convert this byte array to char array of hexadecimal values in order to print it out in one line. I extracted my code to a function like this:

``````char const * keyToStr(uint8_t const *key)
{
uint8_t offset = 0;
static char keyStr[2 * KEY_SIZE + 1];

for (size_t i = 0; i < KEY_SIZE; i++)
{
offset += sprintf(keyStr + offset, "%02X", key[i]);
}
sprintf(keyStr + offset, "%c", '\0');

return keyStr;
}
``````

Now, I can use my function like this:

``````Serial.print("Public key: ");
Serial.println(keyToStr(m_publicKey));
``````

`Serial` object is part of Arduino library and `m_publicKey` is member of my class with the following declaration `uint8_t m_publicKey[32]`.

### Parsing a JSON string in Ruby

Just to extend the answers a bit with what to do with the parsed object:

``````# JSON Parsing example
require "rubygems" # don't need this if you're Ruby v1.9.3 or higher
require "json"

string = '{"desc":{"someKey":"someValue","anotherKey":"value"},"main_item":{"stats":{"a":8,"b":12,"c":10}}}'
parsed = JSON.parse(string) # returns a hash

p parsed["desc"]["someKey"]
p parsed["main_item"]["stats"]["a"]

# Read JSON from a file, iterate over objects
file = open("shops.json")

parsed = JSON.parse(json)

parsed["shop"].each do |shop|
p shop["id"]
end
``````

### @Cacheable key on multiple method arguments

Update: Current Spring cache implementation uses all method parameters as the cache key if not specified otherwise. If you want to use selected keys, refer to Arjan's answer which uses SpEL list `{#isbn, #includeUsed} ` which is the simplest way to create unique keys.

The default key generation strategy changed with the release of Spring 4.0. Earlier versions of Spring used a key generation strategy that, for multiple key parameters, only considered the hashCode() of parameters and not equals(); this could cause unexpected key collisions (see SPR-10237 for background). The new 'SimpleKeyGenerator' uses a compound key for such scenarios.

Before Spring 4.0

I suggest you to concat the values of the parameters in Spel expression with something like `key="#checkWarehouse.toString() + #isbn.toString()")`, I believe this should work as org.springframework.cache.interceptor.ExpressionEvaluator returns Object, which is later used as the key so you don't have to provide an `int` in your SPEL expression.

As for the hash code with a high collision probability - you can't use it as the key.

Someone in this thread has suggested to use `T(java.util.Objects).hash(#p0,#p1, #p2)` but it WILL NOT WORK and this approach is easy to break, for example I've used the data from SPR-9377 :

``````    System.out.println( Objects.hash("someisbn", new Integer(109), new Integer(434)));
System.out.println( Objects.hash("someisbn", new Integer(110), new Integer(403)));
``````

Both lines print -636517714 on my environment.

P.S. Actually in the reference documentation we have

``````@Cacheable(value="books", key="T(someType).hash(#isbn)")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
``````

I think that this example is WRONG and misleading and should be removed from the documentation, as the keys should be unique.

P.P.S. also see https://jira.springsource.org/browse/SPR-9036 for some interesting ideas regarding the default key generation.

I'd like to add for the sake of correctness and as an entertaining mathematical/computer science fact that unlike built-in hash, using a secure cryptographic hash function like MD5 or SHA256, due to the properties of such function IS absolutely possible for this task, but to compute it every time may be too expensive, checkout for example Dan Boneh cryptography course to learn more.

### SQL update fields of one table from fields of another one

I have been working with IBM DB2 database for more then decade and now trying to learn PostgreSQL.

It works on PostgreSQL 9.3.4, but does not work on DB2 10.5:

``````UPDATE B SET
COLUMN1 = A.COLUMN1,
COLUMN2 = A.COLUMN2,
COLUMN3 = A.COLUMN3
FROM A
WHERE A.ID = B.ID
``````

Note: Main problem is FROM cause that is not supported in DB2 and also not in ANSI SQL.

It works on DB2 10.5, but does NOT work on PostgreSQL 9.3.4:

``````UPDATE B SET
(COLUMN1, COLUMN2, COLUMN3) =
(SELECT COLUMN1, COLUMN2, COLUMN3 FROM A WHERE ID = B.ID)
``````

FINALLY! It works on both PostgreSQL 9.3.4 and DB2 10.5:

``````UPDATE B SET
COLUMN1 = (SELECT COLUMN1 FROM A WHERE ID = B.ID),
COLUMN2 = (SELECT COLUMN2 FROM A WHERE ID = B.ID),
COLUMN3 = (SELECT COLUMN3 FROM A WHERE ID = B.ID)
``````

### Foreach value from POST from form

i wouldn't do it this way

I'd use name arrays in the form elements

so i'd get the layout

``````\$_POST['field'][0]['name'] = 'value';
\$_POST['field'][0]['price'] = 'value';
\$_POST['field'][1]['name'] = 'value';
\$_POST['field'][1]['price'] = 'value';
``````

then you could do an array slice to get the amount you need

### How to analyse the heap dump using jmap in java

If you use Eclipse as your IDE I would recommend the excellent eclipse plugin memory analyzer

Another option is to use JVisualVM, it can read (and create) heap dumps as well, and is shipped with every JDK. You can find it in the bin directory of your JDK.

### How can I set Image source with base64

Your problem are the cr (carriage return)

http://jsfiddle.net/NT9KB/210/

you can use:

``````document.getElementById("img").src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
``````

### Strip HTML from strings in Python

I haven't thought much about the cases it will miss, but you can do a simple regex:

``````re.sub('<[^<]+?>', '', text)
``````

For those that don't understand regex, this searches for a string `<...>`, where the inner content is made of one or more (`+`) characters that isn't a `<`. The `?` means that it will match the smallest string it can find. For example given `<p>Hello</p>`, it will match `<'p>` and `</p>` separately with the `?`. Without it, it will match the entire string `<..Hello..>`.

If non-tag `<` appears in html (eg. `2 < 3`), it should be written as an escape sequence `&...` anyway so the `^<` may be unnecessary.

### why is plotting with Matplotlib so slow?

Matplotlib makes great publication-quality graphics, but is not very well optimized for speed. There are a variety of python plotting packages that are designed with speed in mind:

### How to run python script on terminal (ubuntu)?

Set the PATH as below:

In the csh shell - type `setenv PATH "\$PATH:/usr/local/bin/python"` and press Enter.

In the bash shell (Linux) - type `export PATH="\$PATH:/usr/local/bin/python"` and press Enter.

In the sh or ksh shell - type `PATH="\$PATH:/usr/local/bin/python"` and press Enter.

Note - `/usr/local/bin/python` is the path of the Python directory

now run as below:

``````-bash-4.2\$ python test.py

Hello, Python!
``````

### CSS3 gradient background set on body doesn't stretch but instead repeats?

Setting `html { height: 100%}` can wreak havoc with IE. Here's an example (png). But you know what works great? Just set your background on the `<html>` tag.

``````html {
/* etc. */
}
``````

Background extends to the bottom and no weird scrolling behavior occurs. You can skip all of the other fixes. And this is broadly supported. I haven't found a browser that doesn't let you apply a background to the html tag. It's perfectly valid CSS and has been for a while. :)

### What's the better (cleaner) way to ignore output in PowerShell?

I just did some tests of the four options that I know about.

``````Measure-Command {\$(1..1000) | Out-Null}

TotalMilliseconds : 76.211

Measure-Command {[Void]\$(1..1000)}

TotalMilliseconds : 0.217

Measure-Command {\$(1..1000) > \$null}

TotalMilliseconds : 0.2478

Measure-Command {\$null = \$(1..1000)}

TotalMilliseconds : 0.2122

## Control, times vary from 0.21 to 0.24
Measure-Command {\$(1..1000)}

TotalMilliseconds : 0.2141
``````

So I would suggest that you use anything but `Out-Null` due to overhead. The next important thing, to me, would be readability. I kind of like redirecting to `\$null` and setting equal to `\$null` myself. I use to prefer casting to `[Void]`, but that may not be as understandable when glancing at code or for new users.

I guess I slightly prefer redirecting output to `\$null`.

``````Do-Something > \$null
``````

Edit

After stej's comment again, I decided to do some more tests with pipelines to better isolate the overhead of trashing the output.

Here are some tests with a simple 1000 object pipeline.

``````## Control Pipeline
Measure-Command {\$(1..1000) | ?{\$_ -is [int]}}

TotalMilliseconds : 119.3823

## Out-Null
Measure-Command {\$(1..1000) | ?{\$_ -is [int]} | Out-Null}

TotalMilliseconds : 190.2193

## Redirect to \$null
Measure-Command {\$(1..1000) | ?{\$_ -is [int]} > \$null}

TotalMilliseconds : 119.7923
``````

In this case, `Out-Null` has about a 60% overhead and `> \$null` has about a 0.3% overhead.

Addendum 2017-10-16: I originally overlooked another option with `Out-Null`, the use of the `-inputObject` parameter. Using this the overhead seems to disappear, however the syntax is different:

``````Out-Null -inputObject (\$(1..1000) | ?{\$_ -is [int]})
``````

And now for some tests with a simple 100 object pipeline.

``````## Control Pipeline
Measure-Command {\$(1..100) | ?{\$_ -is [int]}}

TotalMilliseconds : 12.3566

## Out-Null
Measure-Command {\$(1..100) | ?{\$_ -is [int]} | Out-Null}

TotalMilliseconds : 19.7357

## Redirect to \$null
Measure-Command {\$(1..1000) | ?{\$_ -is [int]} > \$null}

TotalMilliseconds : 12.8527
``````

Here again `Out-Null` has about a 60% overhead. While `> \$null` has an overhead of about 4%. The numbers here varied a bit from test to test (I ran each about 5 times and picked the middle ground). But I think it shows a clear reason to not use `Out-Null`.

### Dynamically adding properties to an ExpandoObject

As explained here by Filip - http://www.filipekberg.se/2011/10/02/adding-properties-and-methods-to-an-expandoobject-dynamicly/

You can add a method too at runtime.

``````x.Add("Shout", new Action(() => { Console.WriteLine("Hellooo!!!"); }));
x.Shout();
``````

### How to put two divs on the same line with CSS in simple_form in rails?

Your css is fine, but I think it's not applying on divs. Just write simple class name and then try. You can check it at Jsfiddle.

``````.left {
float: left;
width: 125px;
text-align: right;
margin: 2px 10px;
display: inline;
}

.right {
float: left;
text-align: left;
margin: 2px 10px;
display: inline;
}
``````

### Sending JSON to PHP using ajax

To send javascript obj to php using json and ajax:

js:

``````var dataPost = {
"var": "foo"
};
var dataString = JSON.stringify(dataPost);

\$.ajax({
url: 'server.php',
data: {myData: dataString},
type: 'POST',
success: function(response) {
}
});
``````

to use that object in php:

``````\$obj = json_decode(\$_POST["myData"]);

echo \$obj->var;
``````

### generate a random number between 1 and 10 in c

Generating a single random number in a program is problematic. Random number generators are only "random" in the sense that repeated invocations produce numbers from a given probability distribution.

Seeding the RNG won't help, especially if you just seed it from a low-resolution timer. You'll just get numbers that are a hash function of the time, and if you call the program often, they may not change often. You might improve a little bit by using `srand(time(NULL) + getpid())` (`_getpid()` on Windows), but that still won't be random.

The ONLY way to get numbers that are random across multiple invocations of a program is to get them from outside the program. That means using a system service such as `/dev/random` (Linux) or `CryptGenRandom()` (Windows), or from a service like `random.org`.

### How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

This issue should be fixed in the newest version of Homebrew. Try reinstalling it, which is described on the Homebrew home page.

### How do I reflect over the members of dynamic object?

In the case of ExpandoObject, the ExpandoObject class actually implements `IDictionary<string, object>` for its properties, so the solution is as trivial as casting:

``````IDictionary<string, object> propertyValues = (IDictionary<string, object>)s;
``````

Note that this will not work for general dynamic objects. In these cases you will need to drop down to the DLR via IDynamicMetaObjectProvider.

### SELECT DISTINCT on one column

Try this:

`SELECT * FROM [TestData] WHERE Id IN(SELECT DISTINCT MIN(Id) FROM [TestData] GROUP BY Product)`

### How to use java.net.URLConnection to fire and handle HTTP requests?

Initially I was misled by this article which favours `HttpClient`.

Later I have been realized that `HttpURLConnection` is going to stay from this article

Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases. For Gingerbread , HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android.

Transparent compression and response caching reduce network use, improve speed and save battery. New applications should use HttpURLConnection; it is where we will be spending our energy going forward.

After reading this article and some other stack over flow questions, I am convinced that `HttpURLConnection` is going to stay for longer durations.

Some of the SE questions favouring `HttpURLConnections`:

On Android, make a POST request with URL Encoded Form data without using UrlEncodedFormEntity

HttpPost works in Java project, not in Android

### Android Eclipse - Could not find *.apk

i'm no expert, but eclipse on Windows, doing android apps, refuses to create the default.properties file (in the app root directory). I've just copied one from another app and it works fine. Simple contents, for Android 2.2 project it just says (ignoring comments):

target=android-8

fwiw

### How to convert the ^M linebreak to 'normal' linebreak in a file opened in vim?

Simple thing that worked for me

``````dos2unix   filename
``````

### How to load all the images from one of my folder into my web page, using Jquery/Javascript

You can use the fs.readdir or fs.readdirSync methods to get the file names in the directory.

The difference between the two methods, is that the first one is asynchronous, so you have to provide a callback function that will be executed when the read process ends.

The second is synchronous, it will returns the file name array, but it will stop any further execution of your code until the read process ends.

After that you simply have to iterate through the names and using append function, add them to their appropriate locations. To check out how it works see HTML DOM and JS reference

### Is it possible to set async:false to \$.getJSON call

I don't think you can set that option there. You will have to use jQuery.ajax() with the appropriate parameters (basically getJSON just wraps that call into an easier API, as well).

### Pass an array of integers to ASP.NET Web API?

Or you could just pass a string of delimited items and put it into an array or list on the receiving end.

### Android : difference between invisible and gone?

INVISIBLE:

This view is invisible, but it still takes up space for layout purposes.

GONE:

This view is invisible, and it doesn't take any space for layout purposes.

### How to sort a data frame by date

The only way I found to work with hours, through an US format in source (mm-dd-yyyy HH-MM-SS PM/AM)...

``````df_dataSet\$time <- as.POSIXct( df_dataSet\$time , format = "%m/%d/%Y %I:%M:%S %p" , tz = "GMT")
class(df_dataSet\$time)
df_dataSet <- df_dataSet[do.call(order, df_dataSet), ]
``````

### java.lang.ClassNotFoundException: HttpServletRequest

I had the same problem, and the cause was the missing of commons-logging-1.2.jar

I add it to the `lib` folder, then my Apache Tomcat 7 server executed without problems.

### SQL Row_Number() function in Where Clause

``````SELECT  employee_id
FROM    (
SELECT  employee_id, ROW_NUMBER() OVER (ORDER BY employee_id) AS rn
FROM    V_EMPLOYEE
) q
WHERE   rn > 0
ORDER BY
Employee_ID
``````

Note that this filter is redundant: `ROW_NUMBER()` starts from `1` and is always greater than `0`.

### How to solve "The directory is not empty" error when running rmdir command in a batch script?

I had "C:\Users\User Name\OneDrive\Fonts", which was mklink'ed ( /D ) to "C:\Windows\Fonts", and I got the same problem. In my case

cd "C:\Users\User Name\OneDrive"

rd /s Fonts

Y (to confirm the action)

helped me. I hope, that it helps you too ;D

my 2c:

I tried both with n and with nvm on Linux Ubuntu 12.04 LTS, in order to update node from v0.8.25 to v0.10.22.

The first one was successfully completed, but the command 'which node' resulted in the old v0.8.25.
The second one was successfully completed and the same command resulted in v.0.10.22.

### Mod in Java produces negative numbers

Since Java 8 you can use the Math.floorMod() method:

``````Math.floorMod(-1, 2); //== 1
``````

Note: If the modulo-value (here `2`) is negative, all output values will be negative too. :)

### jquery get all form elements: input, textarea & select

For the record: The following snippet can help you to get details about input, textarea, select, button, a tags through a temp title when hover them.

``````\$( 'body' ).on( 'mouseover', 'input, textarea, select, button, a', function() {
var \$tag = \$( this );
var \$form = \$tag.closest( 'form' );
var title = this.title;
var id = this.id;
var name = this.name;
var value = this.value;
var type = this.type;
var cls = this.className;
var tagName = this.tagName;
var options = [];
var hidden = [];
var formDetails = '';

if ( \$form.length ) {
\$form.find( ':input[type="hidden"]' ).each( function( index, el ) {
hidden.push( "\t" + el.name + ' = ' + el.value );
} );

var formName = \$form.prop( 'name' );
var formTitle = \$form.prop( 'title' );
var formId = \$form.prop( 'id' );
var formClass = \$form.prop( 'class' );

formDetails +=
"\n\nFORM NAME: " + formName +
"\nFORM TITLE: " + formTitle +
"\nFORM ID: " + formId +
"\nFORM CLASS: " + formClass +
"\nFORM HIDDEN INPUT:\n" + hidden.join( "\n" );
}

var tempTitle =
"TAG: " + tagName +
"\nTITLE: " + title +
"\nID: " + id +
"\nCLASS: " + cls;

if ( 'SELECT' === tagName ) {
\$tag.find( 'option' ).each( function( index, el ) {
options.push( el.value );
} );

tempTitle +=
"\nNAME: " + name +
"\nVALUE: " + value +
"\nTYPE: " + type +
"\nSELECT OPTIONS:\n\t" + options;

} else if ( 'A' === tagName ) {
tempTitle +=
"\nHTML: " + \$tag.html();

} else {
tempTitle +=
"\nNAME: " + name +
"\nVALUE: " + value +
"\nTYPE: " + type;
}

tempTitle += formDetails;

\$tag.prop( 'title', tempTitle );
\$tag.on( 'mouseout', function() {
\$tag.prop( 'title', title );
} )
} );
``````

### Checking if a key exists in a JavaScript object?

Optional Chaining operator can also be used for this

`````` ?.
``````
``````const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};

console.log(dogName);
// expected output: undefined
``````

You need to add a reference to System.Windows.Forms.dll, then use the `System.Windows.Forms.FolderBrowserDialog` class.

Adding `using WinForms = System.Windows.Forms;` will be helpful.

### HTML embedded PDF iframe

Iframe

``````<iframe id="fred" style="border:1px solid #666CCC" title="PDF in an i-Frame" src="PDFData.pdf" frameborder="1" scrolling="auto" height="1100" width="850" ></iframe>
``````

Object

``````<object data="your_url_to_pdf" type="application/pdf">
<embed src="your_url_to_pdf" type="application/pdf" />
</object>
``````

### How can I make an EXE file from a Python program?

I found this presentation to be very helpfull.

How I Distribute Python applications on Windows - py2exe & InnoSetup

From the site:

There are many deployment options for Python code. I'll share what has worked well for me on Windows, packaging command line tools and services using py2exe and InnoSetup. I'll demonstrate a simple build script which creates windows binaries and an InnoSetup installer in one step. In addition, I'll go over common errors which come up when using py2exe and hints on troubleshooting them. This is a short talk, so there will be a follow-up Open Space session to share experience and help each other solve distribution problems.

### jQuery append() - return appended elements

``````// wrap it in jQuery, now it's a collection
var \$elements = \$(someHTML);

// append to the DOM
\$("#myDiv").append(\$elements);

// do stuff, using the initial reference
\$elements.effects("highlight", {}, 2000);
``````

### Responsive bootstrap 3 timepicker?

Was someone able to have a timepicker working with Bootstrap 3.4?

### A CSS selector to get last visible div

This worked for me.

``````.alert:not(:first-child){
margin: 30px;
}
``````

### Finding Key associated with max Value in a Java Map

Basically you'd need to iterate over the map's entry set, remembering both the "currently known maximum" and the key associated with it. (Or just the entry containing both, of course.)

For example:

``````Map.Entry<Foo, Bar> maxEntry = null;

for (Map.Entry<Foo, Bar> entry : map.entrySet())
{
if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)
{
maxEntry = entry;
}
}
``````

### Difference between Mutable objects and Immutable objects

Mutable objects have fields that can be changed, immutable objects have no fields that can be changed after the object is created.

A very simple immutable object is a object without any field. (For example a simple Comparator Implementation).

``````class Mutable{
private int value;

public Mutable(int value) {
this.value = value;
}

//getter and setter for value
}

class Immutable {
private final int value;

public Immutable(int value) {
this.value = value;
}

//only getter
}
``````

### linux find regex

Regular expressions with character classes (e.g. `[[:digit:]]`) are not supported in the default regular expression syntax used by `find`. You need to specify a different regex type such as `posix-extended` in order to use them.

Take a look at GNU Find's Regular Expression documentation which shows you all the regex types and what they support.

### Ping a site in Python?

Depending on what you want to achive, you are probably easiest calling the system ping command..

Using the subprocess module is the best way of doing this, although you have to remember the ping command is different on different operating systems!

``````import subprocess

ping = subprocess.Popen(
["ping", "-c", "4", host],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)

out, error = ping.communicate()
print out
``````

You don't need to worry about shell-escape characters. For example..

``````host = "google.com; `echo test`
``````

..will not execute the echo command.

Now, to actually get the ping results, you could parse the `out` variable. Example output:

``````round-trip min/avg/max/stddev = 248.139/249.474/250.530/0.896 ms
``````

Example regex:

``````import re
matcher = re.compile("round-trip min/avg/max/stddev = (\d+.\d+)/(\d+.\d+)/(\d+.\d+)/(\d+.\d+)")
print matcher.search(out).groups()

# ('248.139', '249.474', '250.530', '0.896')
``````

Again, remember the output will vary depending on operating system (and even the version of `ping`). This isn't ideal, but it will work fine in many situations (where you know the machines the script will be running on)

### Where can I find "make" program for Mac OS X Lion?

It appears you can install the command line tools without getting Xcode from Downloads for Apple Developers. It required me to login with my apple account.

Alternatively, once you install Xcode from the app store, you might notice the command line tools are not installed by default. Open Xcode, go to preferences, click to the "downloads" tab, and from there you can download and install command line tools.

### Sum columns with null values in oracle

The top-rated answer with NVL is totally valid. If you have any interest in making your SQL code more portable, you might want to use CASE, which is supported with the same syntax in both Oracle and SQL Server:

``````select
type,craft,
SUM(
case when regular is null
then 0
else regular
end
+
case when overtime is null
then 0
else overtime
end
) as total_hours
from
hours_t
group by
type
,craft
order by
type
,craft
``````

### Print newline in PHP in single quotes

I wonder why no one added the alternative of using the function `chr()`:

``````echo 'Hello World!' . chr(10);
``````

or, more efficient if you're going to repeat it a million times:

``````define('C_NewLine', chr(10));
...
echo 'Hello World!' . C_NewLine;
``````

This avoids the silly-looking notation of concatenating a single- and double-quoted string.

### Increment a value in Postgres

``````UPDATE totals
SET total = total + 1
WHERE name = 'bill';
``````

If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:

``````UPDATE totals
SET total = total + 1
WHERE name = 'bill'
AND total = 203;
``````

### Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

https://cdn.rawgit.com is shutting down. Thus, one of the alternate options can be used. JSDeliver is a free cdn that can be used.

// load any GitHub release, commit, or branch

// note: we recommend using npm for projects that support it

https://cdn.jsdelivr.net/gh/user/repo@version/file

https://cdn.jsdelivr.net/gh/jquery/[email protected]/dist/jquery.min.js

// use a version range instead of a specific version

https://cdn.jsdelivr.net/gh/jquery/[email protected]/dist/jquery.min.js

https://cdn.jsdelivr.net/gh/jquery/jquery@3/dist/jquery.min.js

// omit the version completely to get the latest one

// you should NOT use this in production

https://cdn.jsdelivr.net/gh/jquery/jquery/dist/jquery.min.js

// add ".min" to any JS/CSS file to get a minified version

// if one doesn't exist, we'll generate it for you

https://cdn.jsdelivr.net/gh/jquery/[email protected]/src/core.min.js

// add / at the end to get a directory listing

https://cdn.jsdelivr.net/gh/jquery/jquery/

### Error occurred during initialization of boot layer FindException: Module not found

check your project build in jdk 9 or not above that eclipse is having some issues with the modules. Change it to jdk 9 then it will run fine

### How to use Spring Boot with MySQL database and JPA?

Your code is in the default package, i.e. you have source all files in src/main/java with no custom package. I strongly suggest u to create package n then place your source file in it.

``````Ex-
src->
main->
java->
com.myfirst.example
Example.java
com.myfirst.example.controller
PersonController.java
com.myfirst.example.repository
PersonRepository.java
com.myfirst.example.model
Person.java
``````

I hope it will resolve your problem.

### ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

I tried the following steps:

1. Log in as `super user` or use `sudo`
2. Open `/etc/mysql/my.cnf` using gedit
3. Find `bind-address`, and change its value to the database server host machine's IP address. For me, it was `localhost` or `127.0.0.1`
4. Save and close the file.
5. Come back to terminal and execute `sudo service mysql start`

And it worked for me.

### PHP Get name of current directory

For EXAMPLE

`Your Path = /home/serverID_name/www/your_route_Dir/`

THIS_is_the_DIR_I_Want

A Soultion that WORKS:

``````\$url = dirname(\__FILE__);
\$array = explode('\\\',\$url);
\$count = count(\$array);
echo \$array[\$count-1];
``````

### Select multiple columns in data.table by their numeric indices

For versions of data.table `>= 1.9.8`, the following all just work:

``````library(data.table)
dt <- data.table(a = 1, b = 2, c = 3)

# select single column by index
dt[, 2]
#    b
# 1: 2

# select multiple columns by index
dt[, 2:3]
#    b c
# 1: 2 3

# select single column by name
dt[, "a"]
#    a
# 1: 1

# select multiple columns by name
dt[, c("a", "b")]
#    a b
# 1: 1 2
``````

For versions of data.table `< 1.9.8` (for which numerical column selection required the use of `with = FALSE`), see this previous version of this answer. See also NEWS on v1.9.8, POTENTIALLY BREAKING CHANGES, point 3.

If everything is contained in one file, there's the command `gd` (as in 'goto definition'), which will take you to the first occurrence in the file of the word under the cursor, which is often the definition.

### Angular: Cannot Get /

I had the same error caused by build errors. I ran ng build in the directory of my application which helped me correct my errors

### Best practices for SQL varchar column length

I haven't checked this lately, but I know in the past with Oracle that the JDBC driver would reserve a chunk of memory during query execution to hold the result set coming back. The size of the memory chunk is dependent on the column definitions and the fetch size. So the length of the varchar2 columns affects how much memory is reserved. This caused serious performance issues for me years ago as we always used varchar2(4000) (the max at the time) and garbage collection was much less efficient than it is today.

### Key hash for Android-Facebook app

For Linux

Open Terminal :

For Debug Build

``````keytool -exportcert -alias androiddebugkey -keystore debug.keystore | openssl sha1 -binary | openssl base64
``````

you wil find debug.keystore from ".android" folder copy it from and paste on desktop and run above command

For release Build

``````keytool -exportcert -alias <aliasName> -keystore <keystoreFilePath> | openssl sha1 -binary | openssl base64
``````

NOTE : Make sure In Both case it must ask for password. If it does not asks for password that means something is wrong in command.

### How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

### Android Fragment onAttach() deprecated

``````@Override
public void onAttach(Context context) {
super.onAttach(context);

Activity activity = context instanceof Activity ? (Activity) context : null;
}
``````