Programs & Examples On #Visualforce

Visualforce is Salesforce.com's HTML template technology, allowing dynamic creation of web pages (as well as other files) utilising Apex logic and SOQL queries to replace merge fields with content.

Handling multiple IDs in jQuery

Solution:

To your secondary question

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector.

elem1.css({'display':'none'}); //will work

In the below case selector is already stored in a variable.

$(elem1,elem2,elem3).css({'display':'none'}); // will not work

Java: Reading a file into an array

import java.io.File;

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;

import java.util.List;

// ...

Path filePath = new File("fileName").toPath();
Charset charset = Charset.defaultCharset();        
List<String> stringList = Files.readAllLines(filePath, charset);
String[] stringArray = stringList.toArray(new String[]{});

Retrieving Dictionary Value Best Practices

Well in fact TryGetValue is faster. How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.

Edit:

Ok, I understand your confusion so let me elaborate:

Case 1:

if (myDict.Contains(someKey))
     someVal = myDict[someKey];

In this case there are 2 calls to FindEntry, one to check if the key exists and one to retrieve it

Case 2:

myDict.TryGetValue(somekey, out someVal)

In this case there is only one call to FindKey because the resulting index is kept for the actual retrieval in the same method.

What is the best way to give a C# auto-property an initial value?

I know this is an old question, but it came up when I was looking for how to have a default value that gets inherited with the option to override, I came up with

//base class
public class Car
{
    public virtual string FuelUnits
    {
        get { return "gasoline in gallons"; }
        protected set { }
    }
}
//derived
public class Tesla : Car
{
    public override string FuelUnits => "ampere hour";
}

React onClick function fires on render

JSX is used with ReactJS as it is very similar to HTML and it gives programmers feel of using HTML whereas it ultimately transpiles to a javascript file.

Writing a for-loop and specifying function as {this.props.removeTaskFunction(todo)} will execute the functions whenever the loop is triggered .

To stop this behaviour we need to return the function to onClick.

The fat arrow function has a hidden return statement along with the bind property. Thus it returns the function to OnClick as Javascript can return functions too !!!!!

Use -

onClick={() => { this.props.removeTaskFunction(todo) }}

which means-

var onClick = function() {
  return this.props.removeTaskFunction(todo);
}.bind(this);

Windows 10 SSH keys

WINDOWS: If you have git for windows installed go to its folder.

enter image description here

Look in the bin directory. There is a sh.exe file. Run that.

enter image description here

Then type:

ssh-keygen -t rsa -C "your email here"

Follow through instructions and then type:

cat ~/.ssh/id_rsa.pub | clip

It copies the key to your clipboard. Now you can paste that public key to the server side.

How to copy commits from one branch to another?

git cherry-pick : Apply the changes introduced by some existing commits

Assume we have branch A with (X, Y, Z) commits. We need to add these commits to branch B. We are going to use the cherry-pick operations.

When we use cherry-pick, we should add commits on branch B in the same chronological order that the commits appear in Branch A.

cherry-pick does support a range of commits, but if you have merge commits in that range, it gets really complicated

git checkout B
git cherry-pick SHA-COMMIT-X
git cherry-pick SHA-COMMIT-Y
git cherry-pick SHA-COMMIT-Z

Example of workflow :

enter image description here

We can use cherry-pick with options

-e or --edit : With this option, git cherry-pick will let you edit the commit message prior to committing.

-n or --no-commit : Usually the command automatically creates a sequence of commits. This flag applies the changes necessary to cherry-pick each named commit to your working tree and the index, without making any commit. In addition, when this option is used, your index does not have to match the HEAD commit. The cherry-pick is done against the beginning state of your index.

Here an interesting article concerning cherry-pick.

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

Codeigniter displays a blank page instead of error messages

I had this same problem and as Shayan Husaini pointed out, I had an undetected syntax error.

I solved it using the php linter in the terminal:

php -l file.php

You can also use something like this to use the linter in every file in some folder:

find -type f -name "*.php" -exec php -l '{}' \;

And to filter just the ones with errors:

find -type f -name "*.php" -exec php -l '{}' \; | grep '^[^N]'

That should show files with parsing errors and the line where the error is.

sql query to find the duplicate records

You can't do it as a simple single query, but this would do:

select title
from kmovies
where title in (
    select title
    from kmovies
    group by title
    order by cnt desc
    having count(title) > 1
)

Not able to start Genymotion device

(Windows 8) In my case i have changed default RAM from 1GB to 2GB on Genymotion and it gave this error. When i changed it back to 1GB it worked.

Django request get parameters

You may also use:

request.POST.get('section','') # => [39]
request.POST.get('MAINS','') # => [137] 
request.GET.get('section','') # => [39]
request.GET.get('MAINS','') # => [137]

Using this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an exception the fallback value (second argument of .get() will be used).

How do you use global variables or constant values in Ruby?

I think it's local to the file you declared offset. Consider every file to be a method itself.

Maybe put the whole thing into a class and then make offset a class variable with @@offset = Point.new(100, 200);?

How to change column datatype from character to numeric in PostgreSQL 8.4

You can try using USING:

The optional USING clause specifies how to compute the new column value from the old; if omitted, the default conversion is the same as an assignment cast from old data type to new. A USING clause must be provided if there is no implicit or assignment cast from old to new type.

So this might work (depending on your data):

alter table presales alter column code type numeric(10,0) using code::numeric;
-- Or if you prefer standard casting...
alter table presales alter column code type numeric(10,0) using cast(code as numeric);

This will fail if you have anything in code that cannot be cast to numeric; if the USING fails, you'll have to clean up the non-numeric data by hand before changing the column type.

Extract string between two strings in java

Your pattern is fine. But you shouldn't be split()ting it away, you should find() it. Following code gives the output you are looking for:

String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

Shell equality operators (=, ==, -eq)

Several answers show dangerous examples. OP's example [ $a == $b ] specifically used unquoted variable substitution (as of Oct '17 edit). For [...] that is safe for string equality.

But if you're going to enumerate alternatives like [[...]], you must inform also that the right-hand-side must be quoted. If not quoted, it is a pattern match! (From bash man page: "Any part of the pattern may be quoted to force it to be matched as a string.").

Here in bash, the two statements yielding "yes" are pattern matching, other three are string equality:

$ rht="A*"
$ lft="AB"
$ [ $lft = $rht ] && echo yes
$ [ $lft == $rht ] && echo yes
$ [[ $lft = $rht ]] && echo yes
yes
$ [[ $lft == $rht ]] && echo yes
yes
$ [[ $lft == "$rht" ]] && echo yes
$

Shuffle an array with python, randomize array item order with python

I don't know I used random.shuffle() but it return 'None' to me, so I wrote this, might helpful to someone

def shuffle(arr):
    for n in range(len(arr) - 1):
        rnd = random.randint(0, (len(arr) - 1))
        val1 = arr[rnd]
        val2 = arr[rnd - 1]

        arr[rnd - 1] = val1
        arr[rnd] = val2

    return arr

How to set DateTime to null

This should work:

if (!string.IsNullOrWhiteSpace(dateTimeEnd))
    eventCustom.DateTimeEnd = DateTime.Parse(dateTimeEnd);
else
    eventCustom.DateTimeEnd = null;

Note that this will throw an exception if the string is not in the correct format.

How to exit when back button is pressed?

Why wouldn't the user just hit the home button? Then they can exit your app from any of your activities, not just a specific one.

If you are worried about your application continuing to do something in the background. Make sure to stop it in the relevant onPause and onStop commands (which will get triggered when the user presses Home).

If your issue is that you want the next time the user clicks on your app for it to start back at the beginning, I recommend putting some kind of menu item or UI button on the screen that takes the user back to the starting activity of your app. Like the twitter bird in the official twitter app, etc.

Hibernate Delete query

To understand this peculiar behavior of hibernate, it is important to understand a few hibernate concepts -

Hibernate Object States

Transient - An object is in transient status if it has been instantiated and is still not associated with a Hibernate session.

Persistent - A persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session.

Detached - A detached instance is an object that has been persistent, but its Session has been closed.

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html#objectstate-overview

Transaction Write-Behind

The next thing to understand is 'Transaction Write behind'. When objects attached to a hibernate session are modified they are not immediately propagated to the database. Hibernate does this for at least two different reasons.

  • To perform batch inserts and updates.
  • To propagate only the last change. If an object is updated more than once, it still fires only one update statement.

http://learningviacode.blogspot.com/2012/02/write-behind-technique-in-hibernate.html

First Level Cache

Hibernate has something called 'First Level Cache'. Whenever you pass an object to save(), update() or saveOrUpdate(), and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session. This is where it tracks changes to various objects.

Hibernate Intercepters and Object Lifecycle Listeners -

The Interceptor interface and listener callbacks from the session to the application, allow the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. http://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html#d0e3069


This section Updated

Cascading

Hibernate allows applications to define cascade relationships between associations. For example, 'cascade-delete' from parent to child association will result in deletion of all children when a parent is deleted.

So, why are these important.

To be able to do transaction write-behind, to be able to track multiple changes to objects (object graphs) and to be able to execute lifecycle callbacks hibernate needs to know whether the object is transient/detached and it needs to have the object in it's first level cache before it makes any changes to the underlying object and associated relationships.

That's why hibernate (sometimes) issues a 'SELECT' statement to load the object (if it's not already loaded) in to it's first level cache before it makes changes to it.

Why does hibernate issue the 'SELECT' statement only sometimes?

Hibernate issues a 'SELECT' statement to determine what state the object is in. If the select statement returns an object, the object is in detached state and if it does not return an object, the object is in transient state.

Coming to your scenario -

Delete - The 'Delete' issued a SELECT statement because hibernate needs to know if the object exists in the database or not. If the object exists in the database, hibernate considers it as detached and then re-attches it to the session and processes delete lifecycle.

Update - Since you are explicitly calling 'Update' instead of 'SaveOrUpdate', hibernate blindly assumes that the object is in detached state, re-attaches the given object to the session first level cache and processes the update lifecycle. If it turns out that the object does not exist in the database contrary to hibernate's assumption, an exception is thrown when session flushes.

SaveOrUpdate - If you call 'SaveOrUpdate', hibernate has to determine the state of the object, so it uses a SELECT statement to determine if the object is in Transient/Detached state. If the object is in transient state, it processes the 'insert' lifecycle and if the object is in detached state, it processes the 'Update' lifecycle.

how to convert java string to Date object

"mm" means the "minutes" fragment of a date. For the "months" part, use "MM".

So, try to change the code to:

DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
Date startDate = df.parse(startDateString);

Edit: A DateFormat object contains a date formatting definition, not a Date object, which contains only the date without concerning about formatting. When talking about formatting, we are talking about create a String representation of a Date in a specific format. See this example:

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class DateTest {

        public static void main(String[] args) throws Exception {
            String startDateString = "06/27/2007";

            // This object can interpret strings representing dates in the format MM/dd/yyyy
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 

            // Convert from String to Date
            Date startDate = df.parse(startDateString);

            // Print the date, with the default formatting. 
            // Here, the important thing to note is that the parts of the date 
            // were correctly interpreted, such as day, month, year etc.
            System.out.println("Date, with the default formatting: " + startDate);

            // Once converted to a Date object, you can convert 
            // back to a String using any desired format.
            String startDateString1 = df.format(startDate);
            System.out.println("Date in format MM/dd/yyyy: " + startDateString1);

            // Converting to String again, using an alternative format
            DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy"); 
            String startDateString2 = df2.format(startDate);
            System.out.println("Date in format dd/MM/yyyy: " + startDateString2);
        }
    }

Output:

Date, with the default formatting: Wed Jun 27 00:00:00 BRT 2007
Date in format MM/dd/yyyy: 06/27/2007
Date in format dd/MM/yyyy: 27/06/2007

Place API key in Headers or URL

I would not put the key in the url, as it does violate this loose 'standard' that is REST. However, if you did, I would place it in the 'user' portion of the url.

eg: http://[email protected]/myresource/myid

This way it can also be passed as headers with basic-auth.

How do I adb pull ALL files of a folder present in SD Card

Directory pull is available on new android tools. ( I don't know from which version it was added, but its working on latest ADT 21.1 )

adb pull /sdcard/Robotium-Screenshots
pull: building file list...
pull: /sdcard/Robotium-Screenshots/090313-110415.jpg -> ./090313-110415.jpg
pull: /sdcard/Robotium-Screenshots/090313-110412.jpg -> ./090313-110412.jpg
pull: /sdcard/Robotium-Screenshots/090313-110408.jpg -> ./090313-110408.jpg
pull: /sdcard/Robotium-Screenshots/090313-110406.jpg -> ./090313-110406.jpg
pull: /sdcard/Robotium-Screenshots/090313-110404.jpg -> ./090313-110404.jpg
5 files pulled. 0 files skipped.
61 KB/s (338736 bytes in 5.409s)

Convert String to Float in Swift

Use this:

 // get the values from text boxes
    let a:Double = firstText.text.bridgeToObjectiveC().doubleValue
    let b:Double = secondText.text.bridgeToObjectiveC().doubleValue

//  we checking against 0.0, because above function return 0.0 if it gets failed to convert
    if (a != 0.0) && (b != 0.0) {
        var ans = a + b
        answerLabel.text = "Answer is \(ans)"
    } else {
        answerLabel.text = "Input values are not numberic"
    }

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

Load local JSON file into variable

For ES6/ES2015 you can import directly like:

// example.json
{
    "name": "testing"
}


// ES6/ES2015
// app.js
import * as data from './example.json';
const {name} = data;
console.log(name); // output 'testing'

If you use Typescript, you may declare json module like:

// tying.d.ts
declare module "*.json" {
    const value: any;
    export default value;
}

Since Typescript 2.9+ you can add --resolveJsonModule compilerOptions in tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
     ...
    "resolveJsonModule": true,
     ...
  },
  ...
}

Convert a Unicode string to an escaped ASCII string

To store actual Unicode codepoints, you have to first decode the String's UTF-16 codeunits to UTF-32 codeunits (which are currently the same as the Unicode codepoints). Use System.Text.Encoding.UTF32.GetBytes() for that, and then write the resulting bytes to the StringBuilder as needed,i.e.

static void Main(string[] args) 
{ 
    String originalString = "This string contains the unicode character Pi(p)"; 
    Byte[] bytes = Encoding.UTF32.GetBytes(originalString);
    StringBuilder asAscii = new StringBuilder();
    for (int idx = 0; idx < bytes.Length; idx += 4)
    { 
        uint codepoint = BitConverter.ToUInt32(bytes, idx);
        if (codepoint <= 127) 
            asAscii.Append(Convert.ToChar(codepoint)); 
        else 
            asAscii.AppendFormat("\\u{0:x4}", codepoint); 
    } 
    Console.WriteLine("Final string: {0}", asAscii); 
    Console.ReadKey(); 
}

Arrays in unix shell?

The following code creates and prints an array of strings in shell:

#!/bin/bash
array=("A" "B" "ElementC" "ElementE")
for element in "${array[@]}"
do
    echo "$element"
done

echo
echo "Number of elements: ${#array[@]}"
echo
echo "${array[@]}"

Result:

A
B
ElementC
ElementE

Number of elements: 4

A B ElementC ElementE

css label width not taking effect

Make it a block first, then float left to stop pushing the next block in to a new line.

#report-upload-form label {
                           padding-left:26px;
                           width:125px;
                           text-transform: uppercase;
                           display:block;
                           float:left
}

text-align: right on <select> or <option>

You could try using the "dir" attribute, but I'm not sure that would produce the desired effect?

<select dir="rtl">
    <option>Foo</option>    
    <option>bar</option>
    <option>to the right</option>
</select>

Demo here: http://jsfiddle.net/fparent/YSJU7/

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

This is the W3C solution. Works in Firefox and Chrome.

ul { list-style-type: ""; }
/* Sets the marker to a  emoji character */

http://dev.w3.org/csswg/css-lists/#marker-content

_x000D_
_x000D_
ul { list-style-type: " "; }
_x000D_
  <ul><li>item</li></ul>
_x000D_
_x000D_
_x000D_

How can I make sticky headers in RecyclerView? (Without external lib)

you can get sticky header functionality by copying these 2 files into your project. i had no issues with this implementation:

  • can interact with the sticy header (tap/long press/swipe)
  • the sticky header hides and reveals itself properly...even if each view holder has a different height (some other answers here don't handle that properly, causing the wrong headers to show, or the headers to jump up and down)

see an example of the 2 files being used in this small github project i whipped up

How to list all tags along with the full message in git?

Use --format option

git tag -l --format='%(tag) %(subject)'

JavaScript + Unicode regexes

You can also use:

function myFunction() {
  var str = "xq234"; 
  var allowChars = "^[a-zA-ZÀ-ÿ]+$";
  var res = str.match(allowChars);
  if(!str.match(allowChars)){
    res="true";
  }
  else {
    res="false";
  }
  document.getElementById("demo").innerHTML = res;

Convert PEM to PPK file format

I'm rather shocked that this has not been answered since the solution is very simple.

As mentioned in previous posts, you would not want to convert it using C#, but just once. This is easy to do with PuTTYGen.

  1. Download your .pem from AWS
  2. Open PuTTYgen
  3. Click "Load" on the right side about 3/4 down
  4. Set the file type to *.*
  5. Browse to, and Open your .pem file
  6. PuTTY will auto-detect everything it needs, and you just need to click "Save private key" and you can save your ppk key for use with PuTTY

Enjoy!

Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

see NSURLError.h Define

NSURLErrorUnknown =             -1,
NSURLErrorCancelled =           -999,
NSURLErrorBadURL =              -1000,
NSURLErrorTimedOut =            -1001,
NSURLErrorUnsupportedURL =          -1002,
NSURLErrorCannotFindHost =          -1003,
NSURLErrorCannotConnectToHost =         -1004,
NSURLErrorNetworkConnectionLost =       -1005,
NSURLErrorDNSLookupFailed =         -1006,
NSURLErrorHTTPTooManyRedirects =        -1007,
NSURLErrorResourceUnavailable =         -1008,
NSURLErrorNotConnectedToInternet =      -1009,
NSURLErrorRedirectToNonExistentLocation =   -1010,
NSURLErrorBadServerResponse =       -1011,
NSURLErrorUserCancelledAuthentication =     -1012,
NSURLErrorUserAuthenticationRequired =  -1013,
NSURLErrorZeroByteResource =        -1014,
NSURLErrorCannotDecodeRawData =             -1015,
NSURLErrorCannotDecodeContentData =         -1016,
NSURLErrorCannotParseResponse =             -1017,
NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022,
NSURLErrorFileDoesNotExist =        -1100,
NSURLErrorFileIsDirectory =         -1101,
NSURLErrorNoPermissionsToReadFile =     -1102,
NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) =   -1103,

// SSL errors
NSURLErrorSecureConnectionFailed =      -1200,
NSURLErrorServerCertificateHasBadDate =     -1201,
NSURLErrorServerCertificateUntrusted =  -1202,
NSURLErrorServerCertificateHasUnknownRoot = -1203,
NSURLErrorServerCertificateNotYetValid =    -1204,
NSURLErrorClientCertificateRejected =   -1205,
NSURLErrorClientCertificateRequired =   -1206,
NSURLErrorCannotLoadFromNetwork =       -2000,

// Download and file I/O errors
NSURLErrorCannotCreateFile =        -3000,
NSURLErrorCannotOpenFile =          -3001,
NSURLErrorCannotCloseFile =         -3002,
NSURLErrorCannotWriteToFile =       -3003,
NSURLErrorCannotRemoveFile =        -3004,
NSURLErrorCannotMoveFile =          -3005,
NSURLErrorDownloadDecodingFailedMidStream = -3006,
NSURLErrorDownloadDecodingFailedToComplete =-3007,

NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) =         -1018,
NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) =                    -1019,
NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) =                  -1020,
NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) =      -1021,

NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995,
NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996,
NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997,

How to return dictionary keys as a list in Python?

If you need to store the keys separately, here's a solution that requires less typing than every other solution presented thus far, using Extended Iterable Unpacking (python3.x+).

newdict = {1: 0, 2: 0, 3: 0}
*k, = newdict

k
# [1, 2, 3]

            +---------------------------------------------------------+
            ¦ k = list(d)   ¦   9 characters (excluding whitespace)   ¦
            +---------------+-----------------------------------------¦
            ¦ k = [*d]      ¦   6 characters                          ¦
            +---------------+-----------------------------------------¦
            ¦ *k, = d       ¦   5 characters                          ¦
            +---------------------------------------------------------+

How do I use the CONCAT function in SQL Server 2008 R2?

(city + ', ' + state + ' ' + zip) as ctstzip for select
(city + ', ' + state + ' ' + zip) for insert

Only cast or convert if any field type is different from others.

On insert the value needs to be in the correct spot you need it be inserted. Using "as" will give you an error.

i.e.

Insert into testtable (ctstzip) Values ((city + ', ' + state + ' ' + zip))

openCV video saving in python

import cv2

cap = cv2.VideoCapture(0)

fourcc = cv2.VideoWriter_fourcc('X','V','I','D')
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))

out = cv2.VideoWriter('output.mp4', fourcc, 20,(frame_width,frame_height),True )
print(int(cap.get(3)))
print(int(cap.get(4)))
while(cap.isOpened()):
    ret,frame = cap.read()
    if ret == True:
        print(frame.shape)
        out.write(frame)
        cv2.imshow('Frame', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
out.release()`enter code here`

cv2.destroyAllWindows()

This works fine but the problem of having video size relatively very small means nothing is captured. So make sure the height and width of a video and the image that you are going to recorded is same. If you are using some manipulation after capturing a video than you must confirm the size (before and after). Hope it will save some1's hour

Add an object to a python list

Is your problem similar to this:

l = [[0]] * 4
l[0][0] += 1
print l # prints "[[1], [1], [1], [1]]"

If so, you simply need to copy the objects when you store them:

import copy
l = [copy.copy(x) for x in [[0]] * 4]
l[0][0] += 1
print l # prints "[[1], [0], [0], [0]]"

The objects in question should implement a __copy__ method to copy objects. See the documentation for copy. You may also be interested in copy.deepcopy, which is there as well.

EDIT: Here's the problem:

arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(wM) # appends the wM object to the list
    wM.reset()           # clears  the wM object

You need to append a copy:

import copy
arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(copy.copy(wM)) # appends a copy to the list
    wM.reset()                      # clears the wM object

But I'm still confused as to where wM is coming from. Won't you just be copying the same wM object over and over, except clearing it after the first time so all the rest will be empty? Or does model() modify the wM (which sounds like a terrible design flaw to me)? And why are you throwing away result?

How to execute mongo commands through shell scripts?

There is an official documentation page about this as well.

Examples from that page include:

mongo server:27017/dbname --quiet my_commands.js
mongo test --eval "printjson(db.getCollectionNames())"

C# Iterate through Class properties

I tried what Samuel Slade has suggested. Didn't work for me. The PropertyInfo list was coming as empty. So, I tried the following and it worked for me.

    Type type = typeof(Record);
    FieldInfo[] properties = type.GetFields();
    foreach (FieldInfo property in properties) {
       Debug.LogError(property.Name);
    }

Generate a random number in the range 1 - 10

To summarize and a bit simplify, you can use:

-- 0 - 9
select floor(random() * 10);
-- 0 - 10
SELECT floor(random() * (10 + 1));
-- 1 - 10
SELECT ceil(random() * 10);

And you can test this like mentioned by @user80168

-- 0 - 9
SELECT min(i), max(i) FROM (SELECT floor(random() * 10) AS i FROM generate_series(0, 100000)) q;
-- 0 - 10
SELECT min(i), max(i) FROM (SELECT floor(random() * (10 + 1)) AS i FROM generate_series(0, 100000)) q;
-- 1 - 10
SELECT min(i), max(i) FROM (SELECT ceil(random() * 10) AS i FROM generate_series(0, 100000)) q;

Delete a closed pull request from GitHub

There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.

However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.

Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]

UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

If you want to use forward slashes in the format, the you need to escape with back slashes in the regex:

_x000D_
_x000D_
   _x000D_
var dateformat = /^(0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])[\/\-]\d{4}$/;
_x000D_
_x000D_
_x000D_

How can I beautify JSON programmatically?

Programmatic formatting solution:

The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4);    // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/

This method is also included with json2.js, for supporting older browsers.

Manual formatting solution

If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.

Click through div to underlying elements

An easier way would be to inline the transparent background image using Data URIs as follows:

.click-through {
    pointer-events: none;
    background: url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7);
}

HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?

Here's a one-liner slim way for layering text on top of an input in jQuery using ES6 syntax.

_x000D_
_x000D_
$('.input-group > input').focus(e => $(e.currentTarget).parent().find('.placeholder').hide()).blur(e => { if (!$(e.currentTarget).val()) $(e.currentTarget).parent().find('.placeholder').show(); });
_x000D_
* {
  font-family: sans-serif;
}

.input-group {
  position: relative;
}

.input-group > input {
  width: 150px;
  padding: 10px 0px 10px 25px;
}

.input-group > .placeholder {
  position: absolute;
  top: 50%;
  left: 25px;
  transform: translateY(-50%);
  color: #929292;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group">
  <span class="placeholder">Username</span>
  <input>
</div>
_x000D_
_x000D_
_x000D_

Recommended way to save uploaded files in a servlet application

Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:

  1. Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.

  2. In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.

  3. Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.

It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath() method. Using that method is in any case alarming.

The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location) does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.

So, the path to the final storage location can be definied in either of the following ways:

  • Hardcoded:

      File uploads = new File("/path/to/uploads");
    
  • Environment variable via SET UPLOAD_LOCATION=/path/to/uploads:

      File uploads = new File(System.getenv("UPLOAD_LOCATION"));
    
  • VM argument during server startup via -Dupload.location="/path/to/uploads":

      File uploads = new File(System.getProperty("upload.location"));
    
  • *.properties file entry as upload.location=/path/to/uploads:

      File uploads = new File(properties.getProperty("upload.location"));
    
  • web.xml <context-param> with name upload.location and value /path/to/uploads:

      File uploads = new File(getServletContext().getInitParameter("upload.location"));
    
  • If any, use the server-provided location, e.g. in JBoss AS/WildFly:

      File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
    

Either way, you can easily reference and save the file as follows:

File file = new File(uploads, "somefilename.ext");

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath());
}

Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:

File file = File.createTempFile("somefilename-", ".ext", uploads);

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

How to obtain part in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?

Note: do not use Part#write() as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location).

See also:

Google Maps API Multiple Markers with Infowindows

Here is the code snippet which will work for sure. You can visit below link for working jsFiddle and explainantion in detail. How to locate multiple addresses on google maps with perfect zoom

var infowindow = new google.maps.InfoWindow();  
google.maps.event.addListener(marker, 'mouseover', (function(marker) {  
           return function() {  
               var content = address;  
               infowindow.setContent(content);  
               infowindow.open(map, marker);  
           }  
         })(marker));  

Replacing instances of a character in a string

If you want to replace a single semicolon:

for i in range(0,len(line)):
 if (line[i]==";"):
     line = line[:i] + ":" + line[i+1:]

Havent tested it though.

What is the difference between syntax and semantics in programming languages?

Syntax is about the structure or the grammar of the language. It answers the question: how do I construct a valid sentence? All languages, even English and other human (aka "natural") languages have grammars, that is, rules that define whether or not the sentence is properly constructed.

Here are some C language syntax rules:

  • separate statements with a semi-colon
  • enclose the conditional expression of an IF statement inside parentheses
  • group multiple statements into a single statement by enclosing in curly braces
  • data types and variables must be declared before the first executable statement (this feature has been dropped in C99. C99 and latter allow mixed type declarations.)

Semantics is about the meaning of the sentence. It answers the questions: is this sentence valid? If so, what does the sentence mean? For example:

x++;                  // increment
foo(xyz, --b, &qrs);  // call foo

are syntactically valid C statements. But what do they mean? Is it even valid to attempt to transform these statements into an executable sequence of instructions? These questions are at the heart of semantics.

Consider the ++ operator in the first statement. First of all, is it even valid to attempt this?

  • If x is a float data type, this statement has no meaning (according to the C language rules) and thus it is an error even though the statement is syntactically correct.
  • If x is a pointer to some data type, the meaning of the statement is to "add sizeof(some data type) to the value at address x and store the result into the location at address x".
  • If x is a scalar, the meaning of the statement is "add one to the value at address x and store the result into the location at address x".

Finally, note that some semantics cannot be determined at compile-time and must therefore must be evaluated at run-time. In the ++ operator example, if x is already at the maximum value for its data type, what happens when you try to add 1 to it? Another example: what happens if your program attempts to dereference a pointer whose value is NULL?

In summary, syntax is the concept that concerns itself only whether or not the sentence is valid for the grammar of the language . Semantics is about whether or not the sentence has a valid meaning.

How to add border around linear layout except at the bottom?

Here is a Github link to a lightweight and very easy to integrate library that enables you to play with borders as you want for any widget you want, simply based on a FrameLayout widget.

Here is a quick sample code for you to see how easy it is, but you will find more information on the link.

<com.khandelwal.library.view.BorderFrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:leftBorderColor="#00F0F0"
            app:leftBorderWidth="10dp"
            app:topBorderColor="#F0F000"
            app:topBorderWidth="15dp"
            app:rightBorderColor="#F000F0"
            app:rightBorderWidth="20dp"
            app:bottomBorderColor="#000000"
            app:bottomBorderWidth="25dp" >
    </com.khandelwal.library.view.BorderFrameLayout>

So, if you don't want borders on bottom, delete the two lines about bottom in this custom widget, and that's done.

And no, I'm neither the author of this library nor one of his friend ;-)

How to connect Android app to MySQL database?

Can i use pHp to develop an android app?
Yes . for web development you can use Phonegap. "PHP , HTML"etc.
What are the ways this can be done:?
you can check couple of examples on the internet here is one of them "an easy way" Connect Android To MySQL

Best Practice to Organize Javascript Library & CSS Folder Structure

 root/
   assets/
      lib/-------------------------libraries--------------------
          bootstrap/--------------Libraries can have js/css/images------------
              css/
              js/
              images/  
          jquery/
              js/
          font-awesome/
              css/
              images/
     common/--------------------common section will have application level resources             
          css/
          js/
          img/

 index.html

This is how I organized my application's static resources.

In Unix, how do you remove everything in the current directory and below it?

This simplest safe & general solution is probably:

find -mindepth 1 -maxdepth 1 -print0 | xargs -0 rm -rf

Determining the size of an Android view at runtime

Use below code, it is give the size of view.

@Override
public void onWindowFocusChanged(boolean hasFocus) {
       super.onWindowFocusChanged(hasFocus);
       Log.e("WIDTH",""+view.getWidth());
       Log.e("HEIGHT",""+view.getHeight());
}

Base64: java.lang.IllegalArgumentException: Illegal character

I encountered this error since my encoded image started with data:image/png;base64,iVBORw0....

This answer led me to the solution:

String partSeparator = ",";
if (data.contains(partSeparator)) {
  String encodedImg = data.split(partSeparator)[1];
  byte[] decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8));
  Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
  Files.write(destinationFile, decodedImg);
}

WindowsError: [Error 126] The specified module could not be found

In Windows, it's possible. You will need to install: Visual C++ Redistributable for Visual Studio 2015. I had the same problem and I installed both version (Windows x86 and Windows x64). Apparently both are necessary to make it work.

Creating SolidColorBrush from hex color value

If you don't want to deal with the pain of the conversion every time simply create an extension method.

public static class Extensions
{
    public static SolidColorBrush ToBrush(this string HexColorString)
    {
        return (SolidColorBrush)(new BrushConverter().ConvertFrom(HexColorString));
    }    
}

Then use like this: BackColor = "#FFADD8E6".ToBrush()

Alternately if you could provide a method to do the same thing.

public SolidColorBrush BrushFromHex(string hexColorString)
{
    return (SolidColorBrush)(new BrushConverter().ConvertFrom(hexColorString));
}

BackColor = BrushFromHex("#FFADD8E6");

Python Pandas iterate over rows and access column names

How to iterate efficiently

If you really have to iterate a Pandas dataframe, you will probably want to avoid using iterrows(). There are different methods and the usual iterrows() is far from being the best. itertuples() can be 100 times faster.

In short:

  • As a general rule, use df.itertuples(name=None). In particular, when you have a fixed number columns and less than 255 columns. See point (3)
  • Otherwise, use df.itertuples() except if your columns have special characters such as spaces or '-'. See point (2)
  • It is possible to use itertuples() even if your dataframe has strange columns by using the last example. See point (4)
  • Only use iterrows() if you cannot the previous solutions. See point (1)

Different methods to iterate over rows in a Pandas dataframe:

Generate a random dataframe with a million rows and 4 columns:

    df = pd.DataFrame(np.random.randint(0, 100, size=(1000000, 4)), columns=list('ABCD'))
    print(df)

1) The usual iterrows() is convenient, but damn slow:

start_time = time.clock()
result = 0
for _, row in df.iterrows():
    result += max(row['B'], row['C'])

total_elapsed_time = round(time.clock() - start_time, 2)
print("1. Iterrows done in {} seconds, result = {}".format(total_elapsed_time, result))

2) The default itertuples() is already much faster, but it doesn't work with column names such as My Col-Name is very Strange (you should avoid this method if your columns are repeated or if a column name cannot be simply converted to a Python variable name).:

start_time = time.clock()
result = 0
for row in df.itertuples(index=False):
    result += max(row.B, row.C)

total_elapsed_time = round(time.clock() - start_time, 2)
print("2. Named Itertuples done in {} seconds, result = {}".format(total_elapsed_time, result))

3) The default itertuples() using name=None is even faster but not really convenient as you have to define a variable per column.

start_time = time.clock()
result = 0
for(_, col1, col2, col3, col4) in df.itertuples(name=None):
    result += max(col2, col3)

total_elapsed_time = round(time.clock() - start_time, 2)
print("3. Itertuples done in {} seconds, result = {}".format(total_elapsed_time, result))

4) Finally, the named itertuples() is slower than the previous point, but you do not have to define a variable per column and it works with column names such as My Col-Name is very Strange.

start_time = time.clock()
result = 0
for row in df.itertuples(index=False):
    result += max(row[df.columns.get_loc('B')], row[df.columns.get_loc('C')])

total_elapsed_time = round(time.clock() - start_time, 2)
print("4. Polyvalent Itertuples working even with special characters in the column name done in {} seconds, result = {}".format(total_elapsed_time, result))

Output:

         A   B   C   D
0       41  63  42  23
1       54   9  24  65
2       15  34  10   9
3       39  94  82  97
4        4  88  79  54
...     ..  ..  ..  ..
999995  48  27   4  25
999996  16  51  34  28
999997   1  39  61  14
999998  66  51  27  70
999999  51  53  47  99

[1000000 rows x 4 columns]

1. Iterrows done in 104.96 seconds, result = 66151519
2. Named Itertuples done in 1.26 seconds, result = 66151519
3. Itertuples done in 0.94 seconds, result = 66151519
4. Polyvalent Itertuples working even with special characters in the column name done in 2.94 seconds, result = 66151519

This article is a very interesting comparison between iterrows and itertuples

php - get numeric index of associative array


  $a = array(
      'blue' => 'nice',
      'car' => 'fast',
      'number' => 'none'
  );  
var_dump(array_search('car', array_keys($a)));
var_dump(array_search('blue', array_keys($a)));
var_dump(array_search('number', array_keys($a)));

Change default timeout for mocha

By default Mocha will read a file named test/mocha.opts that can contain command line arguments. So you could create such a file that contains:

--timeout 5000

Whenever you run Mocha at the command line, it will read this file and set a timeout of 5 seconds by default.

Another way which may be better depending on your situation is to set it like this in a top level describe call in your test file:

describe("something", function () {
    this.timeout(5000); 

    // tests...
});

This would allow you to set a timeout only on a per-file basis.

You could use both methods if you want a global default of 5000 but set something different for some files.


Note that you cannot generally use an arrow function if you are going to call this.timeout (or access any other member of this that Mocha sets for you). For instance, this will usually not work:

describe("something", () => {
    this.timeout(5000); //will not work

    // tests...
});

This is because an arrow function takes this from the scope the function appears in. Mocha will call the function with a good value for this but that value is not passed inside the arrow function. The documentation for Mocha says on this topic:

Passing arrow functions (“lambdas”) to Mocha is discouraged. Due to the lexical binding of this, such functions are unable to access the Mocha context.

How to recursively find the latest modified file in a directory?

This recursively changes the modification time of all directories in the current directory to the newest file in each directory:

for dir in */; do find $dir -type f -printf '%T@ "%p"\n' | sort -n | tail -1 | cut -f2- -d" " | xargs -I {} touch -r {} $dir; done

How to create a number picker dialog?

To show NumberPicker in AlertDialog use this code :

final AlertDialog.Builder d = new AlertDialog.Builder(context);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.number_picker_dialog, null);
d.setTitle("Title");
d.setMessage("Message");
d.setView(dialogView);
final NumberPicker numberPicker = (NumberPicker) dialogView.findViewById(R.id.dialog_number_picker);
numberPicker.setMaxValue(50);
numberPicker.setMinValue(1);
numberPicker.setWrapSelectorWheel(false);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
    @Override
    public void onValueChange(NumberPicker numberPicker, int i, int i1) {
        Log.d(TAG, "onValueChange: ");
    }
});
d.setPositiveButton("Done", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        Log.d(TAG, "onClick: " + numberPicker.getValue());
    }
});
d.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
    }
});
AlertDialog alertDialog = d.create();
alertDialog.show();

number_picker_dialog.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center_horizontal">

<NumberPicker
    android:id="@+id/dialog_number_picker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</LinearLayout>

Get name of current script in Python

 def basename():
   x=__file__
   y=x.split('\\')
   y1=y[-1]
   y2=y1.split('.')
   y3=y2[0]
 return(y2[0])
  

how can I login anonymously with ftp (/usr/bin/ftp)?

Anonymous ftp logins are usually the username 'anonymous' with the user's email address as the password. Some servers parse the password to ensure it looks like an email address.

User:  anonymous
Password:  [email protected]

Update all objects in a collection using LINQ

There is no built-in extension method to do this. Although defining one is fairly straight forward. At the bottom of the post is a method I defined called Iterate. It can be used like so

collection.Iterate(c => { c.PropertyToSet = value;} );

Iterate Source

public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T> callback)
{
    if (enumerable == null)
    {
        throw new ArgumentNullException("enumerable");
    }

    IterateHelper(enumerable, (x, i) => callback(x));
}

public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
{
    if (enumerable == null)
    {
        throw new ArgumentNullException("enumerable");
    }

    IterateHelper(enumerable, callback);
}

private static void IterateHelper<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
{
    int count = 0;
    foreach (var cur in enumerable)
    {
        callback(cur, count);
        count++;
    }
}

Limit on the WHERE col IN (...) condition

You did not specify the database engine in question; in Oracle, an option is to use tuples like this:

SELECT * FROM table WHERE (Col, 1) IN ((123,1),(123,1),(222,1),....)

This ugly hack only works in Oracle SQL, see https://asktom.oracle.com/pls/asktom/asktom.search?tag=limit-and-conversion-very-long-in-list-where-x-in#9538075800346844400

However, a much better option is to use stored procedures and pass the values as an array.

Batch program to to check if process exists

TASKLIST does not set errorlevel.

echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit

should do the job, since ":" should appear in TASKLIST output only if the task is NOT found, hence FIND will set the errorlevel to 0 for not found and 1 for found

Nevertheless,

taskkill /f /im "notepad.exe"

will kill a notepad task if it exists - it can do nothing if no notepad task exists, so you don't really need to test - unless there's something else you want to do...like perhaps

echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"&exit

which would appear to do as you ask - kill the notepad process if it exists, then exit - otherwise continue with the batch

What is the meaning of CTOR?

Type "ctor" and press the TAB key twice this will add the default constructor automatically

How to output git log with the first line only?

Without commit messages, only the hash:

git log --pretty=oneline | awk '{print $1}'

How to change workspace and build record Root Directory on Jenkins?

By default, Jenkins stores all of its data in this directory on the file system.

There are a few ways to change the Jenkins home directory:

  • Edit the JENKINS_HOME variable in your Jenkins configuration file (e.g. /etc/sysconfig/jenkins on Red Hat Linux).
  • Use your web container's admin tool to set the JENKINS_HOME environment variable.
  • Set the environment variable JENKINS_HOME before launching your web container, or before launching Jenkins directly from the WAR file.
  • Set the JENKINS_HOME Java system property when launching your web container, or when launching Jenkins directly from the WAR file.
  • Modify web.xml in jenkins.war (or its expanded image in your web container). This is not recommended. This value cannot be changed while Jenkins is running. It is shown here to help you ensure that your configuration is taking effect.

How to create and use resources in .NET

The above didn't actually work for me as I had expected with Visual Studio 2010. It wouldn't let me access Properties.Resources, said it was inaccessible due to permission issues. I ultimately had to change the Persistence settings in the properties of the resource and then I found how to access it via the Resources.Designer.cs file, where it had an automatic getter that let me access the icon, via MyNamespace.Properties.Resources.NameFromAddingTheResource. That returns an object of type Icon, ready to just use.

How to merge many PDF files into a single one?

You can use http://www.mergepdf.net/ for example

Or:

PDFTK http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/

If you are NOT on Ubuntu and you have the same problem (and you wanted to start a new topic on SO and SO suggested to have a look at this question) you can also do it like this:

Things You'll Need:

* Full Version of Adobe Acrobat
  1. Open all the .pdf files you wish to merge. These can be minimized on your desktop as individual tabs.

  2. Pull up what you wish to be the first page of your merged document.

  3. Click the 'Combine Files' icon on the top left portion of the screen.

  4. The 'Combine Files' window that pops up is divided into three sections. The first section is titled, 'Choose the files you wish to combine'. Select the 'Add Open Files' option.

  5. Select the other open .pdf documents on your desktop when prompted.

  6. Rearrange the documents as you wish in the second window, titled, 'Arrange the files in the order you want them to appear in the new PDF'

  7. The final window, titled, 'Choose a file size and conversion setting' allows you to control the size of your merged PDF document. Consider the purpose of your new document. If its to be sent as an e-mail attachment, use a low size setting. If the PDF contains images or is to be used for presentation, choose a high setting. When finished, select 'Next'.

  8. A final choice: choose between either a single PDF document, or a PDF package, which comes with the option of creating a specialized cover sheet. When finished, hit 'Create', and save to your preferred location.

    • Tips & Warnings

Double check the PDF documents prior to merging to make sure all pertinent information is included. Its much easier to re-create a single PDF page than a multi-page document.

Access PHP variable in JavaScript

You can't, you'll have to do something like

<script type="text/javascript">
   var php_var = "<?php echo $php_var; ?>";
</script>

You can also load it with AJAX

rhino is right, the snippet lacks of a type for the sake of brevity.

Also, note that if $php_var has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.

Declaration of Methods should be Compatible with Parent Methods in PHP

childClass::customMethod() has different arguments, or a different access level (public/private/protected) than parentClass::customMethod().

How to use if, else condition in jsf to display image

Instead of using the "c" tags, you could also do the following:

<h:outputLink value="Images/thumb_02.jpg" target="_blank" rendered="#{not empty user or user.userId eq 0}" />
<h:graphicImage value="Images/thumb_02.jpg" rendered="#{not empty user or user.userId eq 0}" />

<h:outputLink value="/DisplayBlobExample?userId=#{user.userId}" target="_blank" rendered="#{not empty user and user.userId neq 0}" />
<h:graphicImage value="/DisplayBlobExample?userId=#{user.userId}" rendered="#{not empty user and user.userId neq 0}"/>

I think that's a little more readable alternative to skuntsel's alternative answer and is utilizing the JSF rendered attribute instead of nesting a ternary operator. And off the answer, did you possibly mean to put your image in between the anchor tags so the image is clickable?

Where in memory are my variables stored in C?

  • Variables/automatic variables ---> stack section
  • Dynamically allocated variables ---> heap section
  • Initialised global variables -> data section
  • Uninitialised global variables -> data section (bss)
  • Static variables -> data section
  • String constants -> text section/code section
  • Functions -> text section/code section
  • Text code -> text section/code section
  • Registers -> CPU registers
  • Command line inputs -> environmental/command line section
  • Environmental variables -> environmental/command line section

jquery (or pure js) simulate enter key pressed for testing

Demo Here

var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);

How to get index of object by its property in JavaScript?

var fields = {
teste:
{
    Acess:
    {
        Edit: true,
      View: false

      }
 },
teste1:
{
    Acess:
    {
        Edit: false,
      View: false

      }
  }
};

console.log(find(fields,'teste'));
function find(fields,field){
    for(key in fields){
        if(key == field){
        return true;
    }
}
return false;
}

If you have one Object with multiply objects inside, if you want know if some object are include on Master object, just put find(MasterObject,'Object to Search'), this function will return the response if exist or not (TRUE or FALSE), I hope help with this, can see the exemple on JSFiddle.

Convert a SQL Server datetime to a shorter date format

The shortest date format of mm/dd/yy can be obtained with:

Select Convert(varchar(8),getdate(),1)

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

All values of column A that are not present in column B will have a red background. Hope that it helps as starting point.

Sub highlight_missings()
Dim i As Long, lastA As Long, lastB As Long
Dim compare As Variant
Range("A:A").ClearFormats
lastA = Range("A65536").End(xlUp).Row
lastB = Range("B65536").End(xlUp).Row

For i = 2 To lastA
    compare = Application.Match(Range("a" & i), Range("B2:B" & lastB), 0)
        If IsError(compare) Then
            Range("A" & i).Interior.ColorIndex = 3
        End If
Next i
End Sub

SQL Server NOLOCK and joins

I was pretty sure that you need to specify the NOLOCK for each JOIN in the query. But my experience was limited to SQL Server 2005.

When I looked up MSDN just to confirm, I couldn't find anything definite. The below statements do seem to make me think, that for 2008, your two statements above are equivalent though for 2005 it is not the case:

[SQL Server 2008 R2]

All lock hints are propagated to all the tables and views that are accessed by the query plan, including tables and views referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.

[SQL Server 2005]

In SQL Server 2005, all lock hints are propagated to all the tables and views that are referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.

Additionally, point to note - and this applies to both 2005 and 2008:

The table hints are ignored if the table is not accessed by the query plan. This may be caused by the optimizer choosing not to access the table at all, or because an indexed view is accessed instead. In the latter case, accessing an indexed view can be prevented by using the OPTION (EXPAND VIEWS) query hint.

Convert datetime to valid JavaScript date

You can use moment.js for that, it will convert DateTime object into valid Javascript formated date:

   moment(DateOfBirth).format('DD-MMM-YYYY'); // put format as you want 

   Output: 28-Apr-1993

Hope it will help you :)

Taking the record with the max date

Justin Cave answer is the best, but if you want antoher option, try this:

select A,col_date
from (select A,col_date
    from tablename 
      order by col_date desc)
      where rownum<2

Callback when DOM is loaded in react.js

A combination of componentDidMount and componentDidUpdate will get the job done in a code with class components. But if you're writing code in total functional components the Effect Hook would do a great job it's the same as componentDidMount and componentDidUpdate.

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

https://reactjs.org/docs/hooks-effect.html

How do I clear my Jenkins/Hudson build history?

Another easy way to clean builds is by adding the Discard Old Plugin at the end of your jobs. Set a maximum number of builds to save and then run the job again:

https://wiki.jenkins-ci.org/display/JENKINS/Discard+Old+Build+plugin

How do you overcome the HTML form nesting limitation?

If you really don't want to use multiple forms (as Jason sugests), then use buttons and onclick handlers.

<form id='form' name='form' action='path/to/add/edit/blog' method='post'>
    <textarea name='message' id='message'>Blog message here</textarea>
    <input type='submit' id='save' value='Save'>
</form>
<button id='delete'>Delete</button>
<button id='cancel'>Cancel</button>

And then in javascript (I use jQuery here for easyness) (even though it is pretty overkill for adding some onclick handlers)

$('#delete').click( function() {
   document.location = 'path/to/delete/post/id'; 
});
$('#cancel').click( function() {
   document.location = '/home/index';
});

Also I know, this will make half the page not work without javascript.

PowerShell: Comparing dates

Late but more complete answer in point of getting the most advanced date from $Output

## Q:\test\2011\02\SO_5097125.ps1
## simulate object input with a here string 
$Output = @"
"Date"
"Monday, April 08, 2013 12:00:00 AM"
"Friday, April 08, 2011 12:00:00 AM"
"@ -split '\r?\n' | ConvertFrom-Csv

## use Get-Date and calculated property in a pipeline
$Output | Select-Object @{n='Date';e={Get-Date $_.Date}} |
    Sort-Object Date | Select-Object -Last 1 -Expand Date

## use Get-Date in a ForEach-Object
$Output.Date | ForEach-Object{Get-Date $_} |
    Sort-Object | Select-Object -Last 1

## use [datetime]::ParseExact
## the following will only work if your locale is English for day, month day abbrev.
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',$Null)
} | Sort-Object | Select-Object -Last 1

## for non English locales
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',[cultureinfo]::InvariantCulture)
} | Sort-Object | Select-Object -Last 1

## in case the day month abbreviations are in other languages, here German
## simulate object input with a here string 
$Output = @"
"Date"
"Montag, April 08, 2013 00:00:00"
"Freidag, April 08, 2011 00:00:00"
"@ -split '\r?\n' | ConvertFrom-Csv
$CIDE = New-Object System.Globalization.CultureInfo("de-DE")
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy HH:mm:ss',$CIDE)
} | Sort-Object | Select-Object -Last 1

Send data from a textbox into Flask?

Unless you want to do something more complicated, feeding data from a HTML form into Flask is pretty easy.

  • Create a view that accepts a POST request (my_form_post).
  • Access the form elements in the dictionary request.form.

templates/my-form.html:

<form method="POST">
    <input name="text">
    <input type="submit">
</form>
from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template('my-form.html')

@app.route('/', methods=['POST'])
def my_form_post():
    text = request.form['text']
    processed_text = text.upper()
    return processed_text

This is the Flask documentation about accessing request data.

If you need more complicated forms that need validation then you can take a look at WTForms and how to integrate them with Flask.

Note: unless you have any other restrictions, you don't really need JavaScript at all to send your data (although you can use it).

What is the return value of os.system() in Python?

"On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent."

http://docs.python.org/library/os.html#os.system

There is no error, so the exit code is zero

Passing variable number of arguments around

Ross' solution cleaned-up a bit. Only works if all args are pointers. Also language implementation must support eliding of previous comma if __VA_ARGS__ is empty (both Visual Studio C++ and GCC do).

// pass number of arguments version
 #define callVardicMethodSafely(...) {value_t *args[] = {NULL, __VA_ARGS__}; _actualFunction(args+1,sizeof(args) / sizeof(*args) - 1);}


// NULL terminated array version
 #define callVardicMethodSafely(...) {value_t *args[] = {NULL, __VA_ARGS__, NULL}; _actualFunction(args+1);}

Exporting PDF with jspdf not rendering CSS

To remove black background only add background-color: white; to the style of

basic authorization command for curl

How do I set up the basic authorization?

All you need to do is use -u, --user USER[:PASSWORD]. Behind the scenes curl builds the Authorization header with base64 encoded credentials for you.

Example:

curl -u username:password -i -H 'Accept:application/json' http://example.com

How do I make JavaScript beep?

function beep(wavFile){
    wavFile = wavFile || "beep.wav"
    if (navigator.appName == 'Microsoft Internet Explorer'){
        var e = document.createElement('BGSOUND');
        e.src = wavFile;
        e.loop =1;
        document.body.appendChild(e);
        document.body.removeChild(e);
    }else{
        var e = document.createElement('AUDIO');
        var src1 = document.createElement('SOURCE');
        src1.type= 'audio/wav';
        src1.src= wavFile;
        e.appendChild(src1);
        e.play();
    }
}

Works on Chrome,IE,Mozilla using Win7 OS. Requires a beep.wav file on the server.

How to convert Milliseconds to "X mins, x seconds" in Java?

    long startTime = System.currentTimeMillis();
    // do your work...
    long endTime=System.currentTimeMillis();
    long diff=endTime-startTime;       
    long hours=TimeUnit.MILLISECONDS.toHours(diff);
    diff=diff-(hours*60*60*1000);
    long min=TimeUnit.MILLISECONDS.toMinutes(diff);
    diff=diff-(min*60*1000);
    long seconds=TimeUnit.MILLISECONDS.toSeconds(diff);
    //hour, min and seconds variables contains the time elapsed on your work

How do I verify that a string only contains letters, numbers, underscores and dashes?

[Edit] There's another solution not mentioned yet, and it seems to outperform the others given so far in most cases.

Use string.translate to replace all valid characters in the string, and see if we have any invalid ones left over. This is pretty fast as it uses the underlying C function to do the work, with very little python bytecode involved.

Obviously performance isn't everything - going for the most readable solutions is probably the best approach when not in a performance critical codepath, but just to see how the solutions stack up, here's a performance comparison of all the methods proposed so far. check_trans is the one using the string.translate method.

Test code:

import string, re, timeit

pat = re.compile('[\w-]*$')
pat_inv = re.compile ('[^\w-]')
allowed_chars=string.ascii_letters + string.digits + '_-'
allowed_set = set(allowed_chars)
trans_table = string.maketrans('','')

def check_set_diff(s):
    return not set(s) - allowed_set

def check_set_all(s):
    return all(x in allowed_set for x in s)

def check_set_subset(s):
    return set(s).issubset(allowed_set)

def check_re_match(s):
    return pat.match(s)

def check_re_inverse(s): # Search for non-matching character.
    return not pat_inv.search(s)

def check_trans(s):
    return not s.translate(trans_table,allowed_chars)

test_long_almost_valid='a_very_long_string_that_is_mostly_valid_except_for_last_char'*99 + '!'
test_long_valid='a_very_long_string_that_is_completely_valid_' * 99
test_short_valid='short_valid_string'
test_short_invalid='/$%$%&'
test_long_invalid='/$%$%&' * 99
test_empty=''

def main():
    funcs = sorted(f for f in globals() if f.startswith('check_'))
    tests = sorted(f for f in globals() if f.startswith('test_'))
    for test in tests:
        print "Test %-15s (length = %d):" % (test, len(globals()[test]))
        for func in funcs:
            print "  %-20s : %.3f" % (func, 
                   timeit.Timer('%s(%s)' % (func, test), 'from __main__ import pat,allowed_set,%s' % ','.join(funcs+tests)).timeit(10000))
        print

if __name__=='__main__': main()

The results on my system are:

Test test_empty      (length = 0):
  check_re_inverse     : 0.042
  check_re_match       : 0.030
  check_set_all        : 0.027
  check_set_diff       : 0.029
  check_set_subset     : 0.029
  check_trans          : 0.014

Test test_long_almost_valid (length = 5941):
  check_re_inverse     : 2.690
  check_re_match       : 3.037
  check_set_all        : 18.860
  check_set_diff       : 2.905
  check_set_subset     : 2.903
  check_trans          : 0.182

Test test_long_invalid (length = 594):
  check_re_inverse     : 0.017
  check_re_match       : 0.015
  check_set_all        : 0.044
  check_set_diff       : 0.311
  check_set_subset     : 0.308
  check_trans          : 0.034

Test test_long_valid (length = 4356):
  check_re_inverse     : 1.890
  check_re_match       : 1.010
  check_set_all        : 14.411
  check_set_diff       : 2.101
  check_set_subset     : 2.333
  check_trans          : 0.140

Test test_short_invalid (length = 6):
  check_re_inverse     : 0.017
  check_re_match       : 0.019
  check_set_all        : 0.044
  check_set_diff       : 0.032
  check_set_subset     : 0.037
  check_trans          : 0.015

Test test_short_valid (length = 18):
  check_re_inverse     : 0.125
  check_re_match       : 0.066
  check_set_all        : 0.104
  check_set_diff       : 0.051
  check_set_subset     : 0.046
  check_trans          : 0.017

The translate approach seems best in most cases, dramatically so with long valid strings, but is beaten out by regexes in test_long_invalid (Presumably because the regex can bail out immediately, but translate always has to scan the whole string). The set approaches are usually worst, beating regexes only for the empty string case.

Using all(x in allowed_set for x in s) performs well if it bails out early, but can be bad if it has to iterate through every character. isSubSet and set difference are comparable, and are consistently proportional to the length of the string regardless of the data.

There's a similar difference between the regex methods matching all valid characters and searching for invalid characters. Matching performs a little better when checking for a long, but fully valid string, but worse for invalid characters near the end of the string.

Using (Ana)conda within PyCharm

Change the project interpreter to ~/anaconda2/python/bin by going to File -> Settings -> Project -> Project Interpreter. Also update the run configuration to use the project default Python interpreter via Run -> Edit Configurations. This makes PyCharm use Anaconda instead of the default Python interpreter under usr/bin/python27.

What are examples of TCP and UDP in real life?

TCP is appropriate when you have to move a decent amount of data (> ~1 kB), and you require all of it to be delivered. Almost all data that moves across the internet does so via TCP - HTTP, SMTP, BitTorrent, SSH, etc, all use TCP.

UDP is appropriate when you have small messages which you can afford to lose, and would like to send them as efficiently as possible. One reason you might be able to afford to lose them is because you can re-send them if they get lost. The main example on the internet is DNS - DNS consists of small queries saying things like "what is the IP number for stackoverflow.com?", and the responses are correspondingly small. Computers make a lot of these queries, so they should be made efficiently, but if they get lost en route, it's easy to time out and re-send them.

Exception is never thrown in body of corresponding try statement

As pointed out in the comments, you cannot catch an exception that's not thrown by the code within your try block. Try changing your code to:

try{
    Integer.parseInt(args[i-1]); // this only throws a NumberFormatException
}
catch(NumberFormatException e){
    throw new MojException("Bledne dane");
}

Always check the documentation to see what exceptions are thrown by each method. You may also wish to read up on the subject of checked vs unchecked exceptions before that causes you any confusion in the future.

Convert factor to integer

You can combine the two functions; coerce to characters thence to numerics:

> fac <- factor(c("1","2","1","2"))
> as.numeric(as.character(fac))
[1] 1 2 1 2

How to find an available port?

See ServerSocket:

Creates a server socket, bound to the specified port. A port of 0 creates a socket on any free port.

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

I've found many problems here, so I made my own.

Here it is in all it's glory, with tests:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*([^a-zA-Z\d\s])).{9,}$

https://regex101.com/r/DCRR65/4/tests

Things to look out for:

  1. doesn't use \w because that includes _, which I'm testing for.
  2. I've had lots of troubles matching symbols, without matching the end of the line.
  3. Doesn't specify symbols specifically, this is also because different locales may have different symbols on their keyboards that they may want to use.

form_for with nested resources

Travis R is correct. (I wish I could upvote ya.) I just got this working myself. With these routes:

resources :articles do
  resources :comments
end

You get paths like:

/articles/42
/articles/42/comments/99

routed to controllers at

app/controllers/articles_controller.rb
app/controllers/comments_controller.rb

just as it says at http://guides.rubyonrails.org/routing.html#nested-resources, with no special namespaces.

But partials and forms become tricky. Note the square brackets:

<%= form_for [@article, @comment] do |f| %>

Most important, if you want a URI, you may need something like this:

article_comment_path(@article, @comment)

Alternatively:

[@article, @comment]

as described at http://edgeguides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects

For example, inside a collections partial with comment_item supplied for iteration,

<%= link_to "delete", article_comment_path(@article, comment_item),
      :method => :delete, :confirm => "Really?" %>

What jamuraa says may work in the context of Article, but it did not work for me in various other ways.

There is a lot of discussion related to nested resources, e.g. http://weblog.jamisbuck.org/2007/2/5/nesting-resources

Interestingly, I just learned that most people's unit-tests are not actually testing all paths. When people follow jamisbuck's suggestion, they end up with two ways to get at nested resources. Their unit-tests will generally get/post to the simplest:

# POST /comments
post :create, :comment => {:article_id=>42, ...}

In order to test the route that they may prefer, they need to do it this way:

# POST /articles/42/comments
post :create, :article_id => 42, :comment => {...}

I learned this because my unit-tests started failing when I switched from this:

resources :comments
resources :articles do
  resources :comments
end

to this:

resources :comments, :only => [:destroy, :show, :edit, :update]
resources :articles do
  resources :comments, :only => [:create, :index, :new]
end

I guess it's ok to have duplicate routes, and to miss a few unit-tests. (Why test? Because even if the user never sees the duplicates, your forms may refer to them, either implicitly or via named routes.) Still, to minimize needless duplication, I recommend this:

resources :comments
resources :articles do
  resources :comments, :only => [:create, :index, :new]
end

Sorry for the long answer. Not many people are aware of the subtleties, I think.

JSON.parse unexpected character error

Not true for the OP, but this error can be caused by using single quotation marks (') instead of double (") for strings.

The JSON spec requires double quotation marks for strings.

E.g:

JSON.parse(`{"myparam": 'myString'}`)

gives the error, whereas

JSON.parse(`{"myparam": "myString"}`)

does not. Note the quotation marks around myString.

Related: https://stackoverflow.com/a/14355724/1461850

How to allow user to pick the image with Swift?

I know this is question is a year old, but here's some pretty simple code (mostly from this tutorial) that's working well for me:

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var imageView: UIImageView!

var imagePicker = UIImagePickerController()

override func viewDidLoad() {
    super.viewDidLoad()

    self.imagePicker.delegate = self
}

@IBAction func loadImageButtonTapped(sender: AnyObject) {
    print("hey!")
    self.imagePicker.allowsEditing = false
    self.imagePicker.sourceType = .SavedPhotosAlbum

    self.presentViewController(imagePicker, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        self.imageView.contentMode = .ScaleAspectFit
        self.imageView.image = pickedImage
    }

    dismissViewControllerAnimated(true, completion: nil)

}

func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    self.imagePicker = UIImagePickerController()
    dismissViewControllerAnimated(true, completion: nil)
}

#pragma mark in Swift?

There are Three options to add #pragma_mark in Swift:

1) // MARK: - your text here -

2) // TODO: - your text here -

3) // FIXME: - your text here -

Note: Uses - for add separators

Age from birthdate in python

Expanding on Danny's Solution, but with all sorts of ways to report ages for younger folk (note, today is datetime.date(2015,7,17)):

def calculate_age(born):
    '''
        Converts a date of birth (dob) datetime object to years, always rounding down.
        When the age is 80 years or more, just report that the age is 80 years or more.
        When the age is less than 12 years, rounds down to the nearest half year.
        When the age is less than 2 years, reports age in months, rounded down.
        When the age is less than 6 months, reports the age in weeks, rounded down.
        When the age is less than 2 weeks, reports the age in days.
    '''
    today = datetime.date.today()
    age_in_years = today.year - born.year - ((today.month, today.day) < (born.month, born.day))
    months = (today.month - born.month - (today.day < born.day)) %12
    age = today - born
    age_in_days = age.days
    if age_in_years >= 80:
        return 80, 'years or older'
    if age_in_years >= 12:
        return age_in_years, 'years'
    elif age_in_years >= 2:
        half = 'and a half ' if months > 6 else ''
        return age_in_years, '%syears'%half
    elif months >= 6:
        return months, 'months'
    elif age_in_days >= 14:
        return age_in_days/7, 'weeks'
    else:
        return age_in_days, 'days'

Sample code:

print '%d %s' %calculate_age(datetime.date(1933,6,12)) # >=80 years
print '%d %s' %calculate_age(datetime.date(1963,6,12)) # >=12 years
print '%d %s' %calculate_age(datetime.date(2010,6,19)) # >=2 years
print '%d %s' %calculate_age(datetime.date(2010,11,19)) # >=2 years with half
print '%d %s' %calculate_age(datetime.date(2014,11,19)) # >=6 months
print '%d %s' %calculate_age(datetime.date(2015,6,4)) # >=2 weeks
print '%d %s' %calculate_age(datetime.date(2015,7,11)) # days old

80 years or older
52 years
5 years
4 and a half years
7 months
6 weeks
7 days

jquery how to use multiple ajax calls one after the end of the other

This is the most elegant solution I've been using for a while. It doesn't require external counter variable and it provides nice degree of encapsulation.

var urls = ['http://..', 'http://..', ..];

function ajaxRequest (urls) {
    if (urls.length > 0) {
        $.ajax({
            method: 'GET',
            url: urls.pop()
        })
        .done(function (result)) {
            ajaxRequest(urls);
        });
    }
}

ajaxRequest(urls); 

When should we use intern method of String on String literals

Learn Java String Intern - once for all

Strings in java are immutable objects by design. Therefore, two string objects even with same value will be different objects by default. However, if we wish to save memory, we could indicate to use same memory by a concept called string intern.

The below rules would help you understand the concept in clear terms:

  1. String class maintains an intern-pool which is initially empty. This pool must guarantee to contain string objects with only unique values.
  2. All string literals having same value must be considered same memory-location object because they have otherwise no notion of distinction. Therefore, all such literals with same value will make a single entry in the intern-pool and will refer to same memory location.
  3. Concatenation of two or more literals is also a literal. (Therefore rule #2 will be applicable for them)
  4. Each string created as object (i.e. by any other method except as literal) will have different memory locations and will not make any entry in the intern-pool
  5. Concatenation of literals with non-literals will make a non-literal. Thus, the resultant object will have a new memory location and will NOT make an entry in the intern-pool.
  6. Invoking intern method on a string object, either creates a new object that enters the intern-pool or return an existing object from the pool that has same value. The invocation on any object which is not in the intern-pool, does NOT move the object to the pool. It rather creates another object that enters the pool.

Example:

String s1=new String (“abc”);
String s2=new String (“abc”);
If (s1==s2)  //would return false  by rule #4
If (“abc” == “a”+”bc” )  //would return true by rules #2 and #3
If (“abc” == s1 )  //would return false  by rules #1,2 and #4
If (“abc” == s1.intern() )  //would return true  by rules #1,2,4 and #6
If ( s1 == s2.intern() )      //wound return false by rules #1,4, and #6

Note: The motivational cases for string intern are not discussed here. However, saving of memory will definitely be one of the primary objectives.

How to get the current date and time

Java has always got inadequate support for the date and time use cases. For example, the existing classes (such as java.util.Date and SimpleDateFormatter) aren’t thread-safe which can lead to concurrency issues. Also there are certain flaws in API. For example, years in java.util.Date start at 1900, months start at 1, and days start at 0—not very intuitive. These issues led to popularity of third-party date and time libraries, such as Joda-Time. To address a new date and time API is designed for Java SE 8.

LocalDateTime timePoint = LocalDateTime.now();
System.out.println(timePoint);

As per doc:

The method now() returns the current date-time using the system clock and default time-zone, not null. It obtains the current date-time from the system clock in the default time-zone. This will query the system clock in the default time-zone to obtain the current date-time. Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.

How do I center floated elements?

<!DOCTYPE html>
<html>
<head>
    <title>float object center</title>
    <style type="text/css">
#warp{
    width:500px;
    margin:auto;
}
.ser{
width: 200px;
background-color: #ffffff;
display: block;
float: left;
margin-right: 50px;
}
.inim{
    width: 120px;
    margin-left: 40px;
}

    </style>
</head>
<body>



<div id="warp">
            <div class="ser">
              <img class="inim" src="http://123greetingsquotes.com/wp-content/uploads/2015/01/republic-day-parade-india-images-120x120.jpg">

              </div>
           <div class="ser">
             <img class="inim" sr`enter code here`c="http://123greetingsquotes.com/wp-content/uploads/2015/01/republic-day-parade-india-images-120x120.jpg">

             </div>
        </div>

</body>
</html>

step 1

create two or more div's you want and give them a definite width like 100px for each then float it left or right

step 2

then warp these two div's in another div and give it the width of 200px. to this div apply margin auto. boom it works pretty well. check the above example.

How to use null in switch

This is not possible with a switch statement in Java. Check for null before the switch:

if (i == null) {
    doSomething0();
} else {
    switch (i) {
    case 1:
        // ...
        break;
    }
}

You can't use arbitrary objects in switch statements*. The reason that the compiler doesn't complain about switch (i) where i is an Integer is because Java auto-unboxes the Integer to an int. As assylias already said, the unboxing will throw a NullPointerException when i is null.

* Since Java 7 you can use String in switch statements.

More about switch (including example with null variable) in Oracle Docs - Switch

CR LF notepad++ removal

View -> Show Symbol -> uncheck Show End of Line.

Parsing time string in Python

Your best bet is to have a look at strptime()

Something along the lines of

>>> from datetime import datetime
>>> date_str = 'Tue May 08 15:14:45 +0800 2012'
>>> date = datetime.strptime(date_str, '%a %B %d %H:%M:%S +0800 %Y')
>>> date
datetime.datetime(2012, 5, 8, 15, 14, 45)

Im not sure how to do the +0800 timezone unfortunately, maybe someone else can help out with that.

The formatting strings can be found at http://docs.python.org/library/time.html#time.strftime and are the same for formatting the string for printing.

Hope that helps

Mark

PS, Your best bet for timezones in installing pytz from pypi. ( http://pytz.sourceforge.net/ ) in fact I think pytz has a great datetime parsing method if i remember correctly. The standard lib is a little thin on the ground with timezone functionality.

How can I create a carriage return in my C# string

Along with Environment.NewLine and the literal \r\n or just \n you may also use a verbatim string in C#. These begin with @ and can have embedded newlines. The only thing to keep in mind is that " needs to be escaped as "". An example:

string s = @"This is a string
that contains embedded new lines,
that will appear when this string is used."

PHPMailer AddAddress()

All answers are great. Here is an example use case for multiple add address: The ability to add as many email you want on demand with a web form:

See it in action with jsfiddle here (except the php processor)

### Send unlimited email with a web form
# Form for continuously adding e-mails:
<button type="button" onclick="emailNext();">Click to Add Another Email.</button>
<div id="addEmail"></div>
<button type="submit">Send All Emails</button>
# Script function:
<script>
function emailNext() {
    var nextEmail, inside_where;
    nextEmail = document.createElement('input');
    nextEmail.type = 'text';
    nextEmail.name = 'emails[]';
    nextEmail.className = 'class_for_styling';
    nextEmail.style.display = 'block';
    nextEmail.placeholder  = 'Enter E-mail Here';
    inside_where = document.getElementById('addEmail');
    inside_where.appendChild(nextEmail);
    return false;
}
</script>
# PHP Data Processor:
<?php
// ...
// Add the rest of your $mailer here...
if ($_POST[emails]){
    foreach ($_POST[emails] AS $postEmail){
        if ($postEmail){$mailer->AddAddress($postEmail);}
    }
} 
?>

So what it does basically is to generate a new input text box on every click with the name "emails[]".

The [] added at the end makes it an array when posted.

Then we go through each element of the array with "foreach" on PHP side adding the:

    $mailer->AddAddress($postEmail);

add image to uitableview cell

All good answers from others. Here are two ways you can solve this:

  1. Directly from the code where you will have to programmatically control the dimensions of the imageview

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "xyz", for: indexPath)
        ...
        cell.imageView!.image = UIImage(named: "xyz") // if retrieving the image from the assets folder 
        return cell
    }
    
  2. From the story board, where you can use the attribute inspector & size inspector in the utility pane to adjust positioning, add constraints and specify dimensions

    • In the storyboard, add an imageView object in to the cell's content view with your desired dimensions and add a tag to the view(imageView) in the attribute inspector. Then do the following in your viewController

      override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          let cell = tableView.dequeueReusableCell(withIdentifier: "xyz", for: indexPath)
          ...
          let pictureView = cell.viewWithTag(119) as! UIImageView //let's assume the tag is set to 119
          pictureView.image = UIImage(named: "xyz") // if retrieving the image from the assets folder 
          return cell
      }
      

Read a file line by line with VB.NET

Replaced the reader declaration with this one and now it works!

Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)

Encoding.Default represents the ANSI code page that is set under Windows Control Panel.

How to create cron job using PHP?

why you not use curl? logically, if you execute php file, you will execute that by url on your browser. its very simple if you run curl

while(true)
{
    sleep(60); // sleep for 60 sec = 1 minute

    $s = curl_init();
    curl_setopt($s,CURLOPT_URL, $your_php_url_to_cron); 
    curl_exec($s); 
    curl_getinfo($s,CURLINFO_HTTP_CODE); 
    curl_close($s);
}

Convert a Map<String, String> to a POJO

A solution with Gson:

Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(map);
MyPojo pojo = gson.fromJson(jsonElement, MyPojo.class);

How to use DISTINCT and ORDER BY in same SELECT statement?

if object_id ('tempdb..#tempreport') is not null
begin  
drop table #tempreport
end 
create table #tempreport (
Category  nvarchar(510),
CreationDate smallint )
insert into #tempreport 
select distinct Category from MonitoringJob (nolock) 
select * from #tempreport  ORDER BY CreationDate DESC

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

If you use two databases you can add another DataClasses.dbml and map the second database into it.
It works.

python: how to check if a line is an empty line

line.strip() == ''

Or, if you don't want to "eat up" lines consisting of spaces:

line in ('\n', '\r\n')

How do I convert a org.w3c.dom.Document object to a String?

A Scala version based on Zaz's answer.

  case class DocumentEx(document: Document) {
    def toXmlString(pretty: Boolean = false):Try[String] = {
      getStringFromDocument(document, pretty)
    }
  }

  implicit def documentToDocumentEx(document: Document):DocumentEx = {
    DocumentEx(document)
  }

  def getStringFromDocument(doc: Document, pretty:Boolean): Try[String] = {
    try
    {
      val domSource= new DOMSource(doc)
      val writer = new StringWriter()
      val result = new StreamResult(writer)
      val tf = TransformerFactory.newInstance()
      val transformer = tf.newTransformer()
      if (pretty)
        transformer.setOutputProperty(OutputKeys.INDENT, "yes")
      transformer.transform(domSource, result)
      Success(writer.toString);
    }
    catch {
      case ex: TransformerException =>
        Failure(ex)
    }
  }

With that, you can do either doc.toXmlString() or call the getStringFromDocument(doc) function.

How to convert integer to char in C?

You can try atoi() library function. Also sscanf() and sprintf() would help.

Here is a small example to show converting integer to character string:

main()
{
  int i = 247593;
  char str[10];

  sprintf(str, "%d", i);
  // Now str contains the integer as characters
} 

Here for another Example

#include <stdio.h>

int main(void)
{
   char text[] = "StringX";
   int digit;
   for (digit = 0; digit < 10; ++digit)
   {
      text[6] = digit + '0';
      puts(text);
   }
   return 0;
}

/* my output
String0
String1
String2
String3
String4
String5
String6
String7
String8
String9
*/

adding and removing classes in angularJs using ng-click

If you prefer separation of concerns such that logic for adding and removing classes happens on the controller, you can do this

controller

 (function() {
    angular.module('MyApp', []).controller('MyController', MyController);

    function MyController() {
      var vm = this;
      vm.tab = 0;

      vm.setTab = function(val) {
          vm.tab = val;
       };
      vm.toggleClass = function(val) {
          return val === vm.tab;
           };
        }
    })();

HTML

<div ng-app="MyApp">
  <ul class="" ng-controller="MyController as myCtrl">
    <li ng-click="myCtrl.setTab(0)" ng-class="{'highlighted':myCtrl.toggleClass(0)}">One</li>
    <li ng-click="myCtrl.setTab(1)" ng-class="{'highlighted':myCtrl.toggleClass(1)}">Two</li>
    <li ng-click="myCtrl.setTab(2)" ng-class="{'highlighted':myCtrl.toggleClass(2)}">Three</li>
   <li ng-click="myCtrl.setTab(3)" ng-class="{'highlighted':myCtrl.toggleClass(3)}">Four</li>
 </ul>

CSS

.highlighted {
   background-color: green;
   color: white;
}

Generate MD5 hash string with T-SQL

You didn't explicitly say you wanted the string to be hex; if you are open to the more space efficient base 64 string encoding, and you are using SQL Server 2016 or later, here's an alternative:

select SubString(h, 1, 32) from OpenJson(
    (select HashBytes('MD5', '[email protected]') h for json path)
) with (h nvarchar(max));

This produces:

9TvQiSDl0lgJ3yVj75xStg==

Match exact string

Use the start and end delimiters: ^abc$

How to include multiple js files using jQuery $.getScript() method

Load the following up needed script in the callback of the previous one like:

$.getScript('scripta.js', function()
{
   $.getScript('scriptb.js', function()
   {
       // run script that depends on scripta.js and scriptb.js
   });
});

Recommended Fonts for Programming?

I use MonteCarlo, which is based on ProFont but has a bold face too. That way IDEs/editors that use bold as part of their syntax highlighting leave your text still properly fixed width.

java example http://bok.net.nyud.net/MonteCarlo/images/java-example.png quick brown fox example http://bok.net.nyud.net/MonteCarlo/images/screenshot-small.gif

Like ProFont, Proggy & others, its quite small (& being bitmap based, obviously doesn't scale), but I like a small font for coding and its still extremely clear and easy on the eyes.

How to write a test which expects an Error to be thrown in Jasmine?

In my case the function throwing error was async so I followed here:

await expectAsync(asyncFunction()).toBeRejected();
await expectAsync(asyncFunction()).toBeRejectedWithError(...);

Prolog "or" operator, query

Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:

registered(X, Y) :-
    X = ct101; X = ct102; X = ct103.

For a fuller explanation:

Predicate control in Prolog

How can I disable the bootstrap hover color for links?

If you like an ugly hacks which you should never do in real worlds systems; you could strip all :hover style rules from document.styleSheets.

Just go through all CSS styles with JavaScript and remove all rules, which contain ":hover" in their selector. I use this method when I need to remove :hover styles from bootstrap 2.

_.each(document.styleSheets, function (sheet) { 
    var rulesToLoose = []; 
    _.each(sheet.cssRules, function (rule, index) { 
        if (rule.selectorText && rule.selectorText.indexOf(':hover') > 0) { 
            rulesToLoose.push(index);
        }
    });

    _.each(rulesToLoose.reverse(), function (index) {
        if (sheet.deleteRule) {
            sheet.deleteRule(index);
        } else if (sheet.removeRule) {
            sheet.removeRule(index);
        }
    });
});

I did use underscore for iterating arrays, but one could write those with pure js loop as well:

for (var i = 0; i < document.styleSheets.length; i++) {}

Using other keys for the waitKey() function of opencv

This prints the key combination directly to the image:

z pressed an ctrl + z pressed

The first window shows 'z' pressed, the second shows 'ctrl' + 'z' pressed. When a key combination is used, a question mark appear.

Don't mess up with the question mark code, which is 63.

import numpy as np
import cv2

im = np.zeros((100, 300), np.uint8)
cv2.imshow('Keypressed', im)
while True:
  key = cv2.waitKey(0)
  im_c = im.copy()
  cv2.putText(
    im_c,
    f'{chr(key)} -> {key}',
    (10, 60), 
    cv2.FONT_HERSHEY_SIMPLEX, 
    1,
    (255,255,255),
    2)
  cv2.imshow('Keypressed', im_c)
  if key == 27: break # 'ESC'

Javascript replace with reference to matched group?

For the replacement string and the replacement pattern as specified by $. here a resume:

enter image description here

link to doc : here

"hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")



Note:

If you want to have a $ in the replacement string use $$. Same as with vscode snippet system.

Using $_POST to get select option value from HTML

You can access values in the $_POST array by their key. $_POST is an associative array, so to access taskOption you would use $_POST['taskOption'];.

Make sure to check if it exists in the $_POST array before proceeding though.

<form method="post" action="process.php">
  <select name="taskOption">
    <option value="first">First</option>
    <option value="second">Second</option>
    <option value="third">Third</option>
  </select>
  <input type="submit" value="Submit the form"/>
</form>

process.php

<?php
   $option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
   if ($option) {
      echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
   } else {
     echo "task option is required";
     exit; 
   }

Split files using tar, gz, zip, or bzip2

If you are splitting from Linux, you can still reassemble in Windows.

copy /b file1 + file2 + file3 + file4 filetogether

Format telephone and credit card numbers in AngularJS

I created an AngularJS module to handle this issue regarding phonenumbers for myself with a custom directive and accompanying filter.

jsfiddle example: http://jsfiddle.net/aberke/s0xpkgmq/

Filter use example: <p>{{ phonenumberValue | phonenumber }}</p>

Filter code:

.filter('phonenumber', function() {
    /* 
    Format phonenumber as: c (xxx) xxx-xxxx
        or as close as possible if phonenumber length is not 10
        if c is not '1' (country code not USA), does not use country code
    */

    return function (number) {
        /* 
        @param {Number | String} number - Number that will be formatted as telephone number
        Returns formatted number: (###) ###-####
            if number.length < 4: ###
            else if number.length < 7: (###) ###

        Does not handle country codes that are not '1' (USA)
        */
        if (!number) { return ''; }

        number = String(number);

        // Will return formattedNumber. 
        // If phonenumber isn't longer than an area code, just show number
        var formattedNumber = number;

        // if the first character is '1', strip it out and add it back
        var c = (number[0] == '1') ? '1 ' : '';
        number = number[0] == '1' ? number.slice(1) : number;

        // # (###) ###-#### as c (area) front-end
        var area = number.substring(0,3);
        var front = number.substring(3, 6);
        var end = number.substring(6, 10);

        if (front) {
            formattedNumber = (c + "(" + area + ") " + front);  
        }
        if (end) {
            formattedNumber += ("-" + end);
        }
        return formattedNumber;
    };
});

Directive use example:

<phonenumber-directive placeholder="'Input phonenumber here'" model='myModel.phonenumber'></phonenumber-directive>

Directive code:

.directive('phonenumberDirective', ['$filter', function($filter) {
    /*
    Intended use:
        <phonenumber-directive placeholder='prompt' model='someModel.phonenumber'></phonenumber-directive>
    Where:
        someModel.phonenumber: {String} value which to bind only the numeric characters [0-9] entered
            ie, if user enters 617-2223333, value of 6172223333 will be bound to model
        prompt: {String} text to keep in placeholder when no numeric input entered
    */

    function link(scope, element, attributes) {

        // scope.inputValue is the value of input element used in template
        scope.inputValue = scope.phonenumberModel;

        scope.$watch('inputValue', function(value, oldValue) {

            value = String(value);
            var number = value.replace(/[^0-9]+/g, '');
            scope.phonenumberModel = number;
            scope.inputValue = $filter('phonenumber')(number);
        });
    }

    return {
        link: link,
        restrict: 'E',
        scope: {
            phonenumberPlaceholder: '=placeholder',
            phonenumberModel: '=model',
        },
        // templateUrl: '/static/phonenumberModule/template.html',
        template: '<input ng-model="inputValue" type="tel" class="phonenumber" placeholder="{{phonenumberPlaceholder}}" title="Phonenumber (Format: (999) 9999-9999)">',
    };
}])

Full code with module and how to use it: https://gist.github.com/aberke/042eef0f37dba1138f9e

Download pdf file using jquery ajax

I am newbie and most of the code is from google search. I got my pdf download working with the code below (trial and error play). Thank you for code tips (xhrFields) above.

$.ajax({
            cache: false,
            type: 'POST',
            url: 'yourURL',
            contentType: false,
            processData: false,
            data: yourdata,
             //xhrFields is what did the trick to read the blob to pdf
            xhrFields: {
                responseType: 'blob'
            },
            success: function (response, status, xhr) {

                var filename = "";                   
                var disposition = xhr.getResponseHeader('Content-Disposition');

                 if (disposition) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches !== null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                } 
                var linkelem = document.createElement('a');
                try {
                                           var blob = new Blob([response], { type: 'application/octet-stream' });                        

                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        //   IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                        window.navigator.msSaveBlob(blob, filename);
                    } else {
                        var URL = window.URL || window.webkitURL;
                        var downloadUrl = URL.createObjectURL(blob);

                        if (filename) { 
                            // use HTML5 a[download] attribute to specify filename
                            var a = document.createElement("a");

                            // safari doesn't support this yet
                            if (typeof a.download === 'undefined') {
                                window.location = downloadUrl;
                            } else {
                                a.href = downloadUrl;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.target = "_blank";
                                a.click();
                            }
                        } else {
                            window.location = downloadUrl;
                        }
                    }   

                } catch (ex) {
                    console.log(ex);
                } 
            }
        });

Zoom in on a point (using scale and translate)

Here's an approach I use for tighter control over how things are drawn

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

var scale = 1;
var xO = 0;
var yO = 0;

draw();

function draw(){
    // Clear screen
    ctx.clearRect(0, 0, canvas.offsetWidth, canvas.offsetHeight);

    // Original coordinates
    const xData = 50, yData = 50, wData = 100, hData = 100;
    
    // Transformed coordinates
    const x = xData * scale + xO,
     y = yData * scale + yO,
     w = wData * scale,
     h = hData * scale;

    // Draw transformed positions
    ctx.fillStyle = "black";
    ctx.fillRect(x,y,w,h);
}

canvas.onwheel = function (e){
    e.preventDefault();

    const r = canvas.getBoundingClientRect(),
      xNode =  e.pageX - r.left,
      yNode =  e.pageY - r.top;

    const newScale = scale * Math.exp(-Math.sign(e.deltaY) * 0.2),
      scaleFactor = newScale/scale;

    xO = xNode - scaleFactor * (xNode - xO);
    yO = yNode - scaleFactor * (yNode - yO);
    scale = newScale;

    draw();
}
_x000D_
<canvas id="canvas" width="600" height="200"></canvas>
_x000D_
_x000D_
_x000D_

How to dynamically set bootstrap-datepicker's date value?

Simple way like this (one line)

$('#startDateText').val(startDate).datepicker("update");

Add Foreign Key to existing table

To add a foreign key (grade_id) to an existing table (users), follow the following steps:

ALTER TABLE users ADD grade_id SMALLINT UNSIGNED NOT NULL DEFAULT 0;
ALTER TABLE users ADD CONSTRAINT fk_grade_id FOREIGN KEY (grade_id) REFERENCES grades(id);

Maven: repository element was not specified in the POM inside distributionManagement?

The ID of the two repos are both localSnap; that's probably not what you want and it might confuse Maven.

If that's not it: There might be more repository elements in your POM. Search the output of mvn help:effective-pom for repository to make sure the number and place of them is what you expect.

Angular2 @Input to a property with get/set

@Paul Cavacas, I had the same issue and I solved by setting the Input() decorator above the getter.

  @Input('allowDays')
  get in(): any {
    return this._allowDays;
  }

  //@Input('allowDays')
  // not working
  set in(val) {
    console.log('allowDays = '+val);
    this._allowDays = val;
  }

See this plunker: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview

Why can't I push to this bare repository?

Try this in your alice repository (before pushing):

git config push.default tracking

Or, configure it as the default for your user with git config --global ….


git push does default to the origin repository (which is normally the repository from which you cloned the current repository), but it does not default to pushing the current branch—it defaults to pushing only branches that exist in both the source repository and the destination repository.

The push.default configuration variable (see git-config(1)) controls what git push will push when it is not given any “refspec” arguments (i.e. something after a repository name). The default value gives the behavior described above.

Here are possible values for push.default:

  • nothing
    This forces you to supply a “refspec”.

  • matching (the default)
    This pushes all branches that exist in both the source repository and the destination repository.
    This is completely independent of the branch that is currently checked out.

  • upstream or tracking
    (Both values mean the same thing. The later was deprecated to avoid confusion with “remote-tracking” branches. The former was introduced in 1.7.4.2, so you will have to use the latter if you are using Git 1.7.3.1.)
    These push the current branch to the branch specified by its “upstream” configuration.

  • current
    This pushes the current branch to the branch of the same name at the destination repository.

    These last two end up being the same for common cases (e.g. working on local master which uses origin/master as its upstream), but they are different when the local branch has a different name from its “upstream” branch:

    git checkout master
    # hack, commit, hack, commit
    
    # bug report comes in, we want a fix on master without the above commits
    
    git checkout -b quickfix origin/master  # "upstream" is master on origin
    # fix, commit
    git push
    

    With push.default equal to upstream (or tracking), the push would go to origin’s master branch. When it is equal to current, the push would go to origin’s quickfix branch.

The matching setting will update bare’s master in your scenario once it has been established. To establish it, you could use git push origin master once.

However, the upstream setting (or maybe current) seems like it might be a better match for what you expect to happen, so you might want to try it:

# try it once (in Git 1.7.2 and later)
git -c push.default=upstream push

# configure it for only this repository
git config push.default upstream

# configure it for all repositories that do not override it themselves
git config --global push.default upstream

(Again, if you are still using a Git before 1.7.4.2, you will need to use tracking instead of upstream).

How can I login to a website with Python?

Websites in general can check authorization in many different ways, but the one you're targeting seems to make it reasonably easy for you.

All you need is to POST to the auth/login URL a form-encoded blob with the various fields you see there (forget the labels for, they're decoration for human visitors). handle=whatever&password-clear=pwd and so on, as long as you know the values for the handle (AKA email) and password you should be fine.

Presumably that POST will redirect you to some "you've successfully logged in" page with a Set-Cookie header validating your session (be sure to save that cookie and send it back on further interaction along the session!).

How to get Javascript Select box's selected text

In order to get the value of the selected item you can do the following:

this.options[this.selectedIndex].text

Here the different options of the select are accessed, and the SelectedIndex is used to choose the selected one, then its text is being accessed.

Read more about the select DOM here.

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

gradlew: Permission Denied

on android folder cmd run

chmod +x gradlew

and run

./gradlew clean

and root project run

react-native run-android

Twitter Bootstrap: Print content of modal window

_x000D_
_x000D_
@media print{_x000D_
 body{_x000D_
  visibility: hidden; /* no print*/_x000D_
 }_x000D_
 .print{_x000D_
  _x000D_
  visibility:visible; /*print*/_x000D_
 }_x000D_
}
_x000D_
<body>_x000D_
  <div class="noprint"> <!---no print--->_x000D_
  <div class="noprint"> <!---no print--->_x000D_
  <div class="print">   <!---print--->_x000D_
  <div class="print">   <!---print--->_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to convert an entire MySQL database characterset and collation to UTF-8?

You can also DB tool Navicat, which does it more easier.

  • Siva.

Right Click Your Database & select DB Properties & Change as you desired in Drop Down

enter image description here

Linq to Entities join vs groupjoin

Let's suppose you have two different classes:

public class Person
{
    public string Name, Email;
    
    public Person(string name, string email)
    {
        Name = name;
        Email = email;
    }
}
class Data
{
    public string Mail, SlackId;
    
    public Data(string mail, string slackId)
    {
        Mail = mail;
        SlackId = slackId;
    }
}

Now, let's Prepare data to work with:

var people = new Person[]
    {
        new Person("Sudi", "[email protected]"),
        new Person("Simba", "[email protected]"),
        new Person("Sarah", string.Empty)
    };
    
    var records = new Data[]
    {
        new Data("[email protected]", "Sudi_Try"),
        new Data("[email protected]", "Sudi@Test"),
        new Data("[email protected]", "SimbaLion")
    };

You will note that [email protected] has got two slackIds. I have made that for demonstrating how Join works.

Let's now construct the query to join Person with Data:

var query = people.Join(records,
        x => x.Email,
        y => y.Mail,
        (person, record) => new { Name = person.Name, SlackId = record.SlackId});
    Console.WriteLine(query);

After constructing the query, you could also iterate over it with a foreach like so:

foreach (var item in query)
    {
        Console.WriteLine($"{item.Name} has Slack ID {item.SlackId}");
    }

Let's also output the result for GroupJoin:

Console.WriteLine(
    
        people.GroupJoin(
            records,
            x => x.Email,
            y => y.Mail,
            (person, recs) => new {
                Name = person.Name,
                SlackIds = recs.Select(r => r.SlackId).ToArray() // You could materialize //whatever way you want.
            }
        ));

You will notice that the GroupJoin will put all SlackIds in a single group.

I want to truncate a text or line with ellipsis using JavaScript

HTML with JavaScript:

<p id="myid">My long long looooong text cut cut cut cut cut</p>

<script type="text/javascript">
var myid=document.getElementById('myid');
myid.innerHTML=myid.innerHTML.substring(0,10)+'...';
</script>

The result will be:

My long lo...

Cheers

G.

How to pass credentials to httpwebrequest for accessing SharePoint Library

If you need to set the credentials on the fly, have a look at this source:

http://spc3.codeplex.com/SourceControl/changeset/view/57957#1015709

private ICredentials BuildCredentials(string siteurl, string username, string password, string authtype) {
    NetworkCredential cred;
    if (username.Contains(@"\")) {
        string domain = username.Substring(0, username.IndexOf(@"\"));
        username = username.Substring(username.IndexOf(@"\") + 1);
        cred = new System.Net.NetworkCredential(username, password, domain);
    } else {
        cred = new System.Net.NetworkCredential(username, password);
    }
    CredentialCache cache = new CredentialCache();
    if (authtype.Contains(":")) {
        authtype = authtype.Substring(authtype.IndexOf(":") + 1); //remove the TMG: prefix
    }
    cache.Add(new Uri(siteurl), authtype, cred);
    return cache;
}

How to get length of a list of lists in python

"The above text file used has 3 lines of 4 elements separated by commas. The variable numLines prints out as '4' not '3'. So, len(myLines) is returning the number of elements in each list not the length of the list of lists."

It sounds like you're reading in a .csv with 3 rows and 4 columns. If this is the case, you can find the number of rows and lines by using the .split() method:

text = open("filetest.txt", "r").read()
myRows = text.split("\n")      #this method tells Python to split your filetest object each time it encounters a line break 
print len(myRows)              #will tell you how many rows you have
for row in myRows:
  myColumns = row.split(",")   #this method will consider each of your rows one at a time. For each of those rows, it will split that row each time it encounters a comma.  
  print len(myColumns)         #will tell you, for each of your rows, how many columns that row contains

Referencing Row Number in R

Simply:

data$rownumber = 1:nrow(Data)

calling parent class method from child class object in java

Use the keyword super within the overridden method in the child class to use the parent class method. You can only use the keyword within the overridden method though. The example below will help.

public class Parent {
    public int add(int m, int n){
        return m+n;
    }
}


public class Child extends Parent{
    public int add(int m,int n,int o){
        return super.add(super.add(m, n),0);
    }

}


public class SimpleInheritanceTest {
    public static void main(String[] a){
        Child child = new Child();
        child.add(10, 11);
    }
}

The add method in the Child class calls super.add to reuse the addition logic.

iPad/iPhone hover problem causes the user to double click a link

cduruk's solution was quite effective, but caused problems on a few parts of my site. Because I was already using jQuery to add the CSS hover class, the easiest solution was to simply not add the CSS hover class on mobile devices (or more precisely, to ONLY add it when NOT on a mobile device).

Here was the general idea:

var device = navigator.userAgent.toLowerCase();
var ios = device.match(/(iphone|ipod|ipad)/);

if (!(ios)) {
    $(".portfolio-style").hover(
        function(){
            $(this).stop().animate({opacity: 1}, 100);
            $(this).addClass("portfolio-red-text");
        },
        function(){
            $(this).stop().animate({opacity: 0.85}, 100);
            $(this).removeClass("portfolio-red-text");
        }
    );
}

*code reduced for illustrative purposes

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

I just posted a snippet that makes admin.ModelAdmin support '__' syntax:

http://djangosnippets.org/snippets/2887/

So you can do:

class PersonAdmin(RelatedFieldAdmin):
    list_display = ['book__author',]

This is basically just doing the same thing described in the other answers, but it automatically takes care of (1) setting admin_order_field (2) setting short_description and (3) modifying the queryset to avoid a database hit for each row.

How to get all of the immediate subdirectories in Python

Why has no one mentioned glob? glob lets you use Unix-style pathname expansion, and is my go to function for almost everything that needs to find more than one path name. It makes it very easy:

from glob import glob
paths = glob('*/')

Note that glob will return the directory with the final slash (as unix would) while most path based solutions will omit the final slash.

Where is web.xml in Eclipse Dynamic Web Project

If your deployment descriptor tab is disabled, then click on update libraries it will also do your work. It will create. Xml file in Web content

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

Best way to use sql brackets use callback function in laravel eloquent.

YourModal::where(function ($q) {
    $q->where('a', 1)->orWhere('b', 1);
})->where(function ($q) {
    $q->where('c', 1)->orWhere('d', 1);
});

You don't have to use = symbol, it's come as the default

Lest say if you have a query that contain brackets inside a brackets

WHERE (a = 1 OR (b = 1 and c = 5))


YourModal::where(function ($q) {
    $q->where('a', 1)->orWhere(function($q2){
      $q2->where('b', 1)->where('c', 5);
    });
});

lest say you want to make values dynamics

YourModal::where(function ($q) use($val1, $val2) {
    $q->where('a', $val1)->orWhere(function($q2) use($val2){
      $q2->where('b', $val2)->where('c', $val2);
    });
});

How do I get rid of the "cannot empty the clipboard" error?

I copied a picture (instead of text) that I had in my excel 2007 file and that solved the problem for me. The picture copied to the (then empty) clipboard. I could then copy cells normally even after clearing the clipboard of the picture. I think a graph object should also do the trick.

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

while doing performance testing, the measure i go by is RPS, that is how many requests per second can the server serve within acceptable latency.

theoretically one server can only run as many requests concurrently as number of cores on it..

It doesn't look like the problem is ASP.net's threading model, since it can potentially serve thousands of rps. It seems like the problem might be your application. Are you using any synchronization primitives ?

also whats the latency on your web services, are they very quick to respond (within microseconds), if not then you might want to consider asynchronous calls, so you dont end up blocking

If this doesnt yeild something, then you might want to profile your code using visual studio or redgate profiler

How to format a URL to get a file from Amazon S3?

Its actually formulated more like:

https://<bucket-name>.s3.amazonaws.com/<key>

See here

how to set imageview src?

Each image has a resource-number, which is an integer. Pass this number to "setImageResource" and you should be ok.

Check this link for further information:
http://developer.android.com/guide/topics/resources/accessing-resources.html

e.g.:

imageView.setImageResource(R.drawable.myimage);

Setting focus to iframe contents

Try listening for events in the parent document and passing the event to a handler in the iframe document.

How to make asynchronous HTTP requests in PHP

let me show you my way :)

needs nodejs installed on the server

(my server sends 1000 https get request takes only 2 seconds)

url.php :

<?
$urls = array_fill(0, 100, 'http://google.com/blank.html');

function execinbackground($cmd) { 
    if (substr(php_uname(), 0, 7) == "Windows"){ 
        pclose(popen("start /B ". $cmd, "r"));  
    } 
    else { 
        exec($cmd . " > /dev/null &");   
    } 
} 
fwite(fopen("urls.txt","w"),implode("\n",$urls);
execinbackground("nodejs urlscript.js urls.txt");
// { do your work while get requests being executed.. }
?>

urlscript.js >

var https = require('https');
var url = require('url');
var http = require('http');
var fs = require('fs');
var dosya = process.argv[2];
var logdosya = 'log.txt';
var count=0;
http.globalAgent.maxSockets = 300;
https.globalAgent.maxSockets = 300;

setTimeout(timeout,100000); // maximum execution time (in ms)

function trim(string) {
    return string.replace(/^\s*|\s*$/g, '')
}

fs.readFile(process.argv[2], 'utf8', function (err, data) {
    if (err) {
        throw err;
    }
    parcala(data);
});

function parcala(data) {
    var data = data.split("\n");
    count=''+data.length+'-'+data[1];
    data.forEach(function (d) {
        req(trim(d));
    });
    /*
    fs.unlink(dosya, function d() {
        console.log('<%s> file deleted', dosya);
    });
    */
}


function req(link) {
    var linkinfo = url.parse(link);
    if (linkinfo.protocol == 'https:') {
        var options = {
        host: linkinfo.host,
        port: 443,
        path: linkinfo.path,
        method: 'GET'
    };
https.get(options, function(res) {res.on('data', function(d) {});}).on('error', function(e) {console.error(e);});
    } else {
    var options = {
        host: linkinfo.host,
        port: 80,
        path: linkinfo.path,
        method: 'GET'
    };        
http.get(options, function(res) {res.on('data', function(d) {});}).on('error', function(e) {console.error(e);});
    }
}


process.on('exit', onExit);

function onExit() {
    log();
}

function timeout()
{
console.log("i am too far gone");process.exit();
}

function log() 
{
    var fd = fs.openSync(logdosya, 'a+');
    fs.writeSync(fd, dosya + '-'+count+'\n');
    fs.closeSync(fd);
}

update listview dynamically with adapter

Use a ArrayAdapter backed by an ArrayList. To change the data, just update the data in the list and call adapter.notifyDataSetChanged().

How can I switch views programmatically in a view controller? (Xcode, iPhone)

[self.navigationController pushViewController:someViewController animated:YES];

Find the number of employees in each department - SQL Oracle

select  d.dname
       ,count(e.empno) as count 
from dept d 
left outer join emp e 
  on e.deptno=d.deptno 
group by d.dname;

NSArray + remove item from array

NSArray is not mutable, that is, you cannot modify it. You should take a look at NSMutableArray. Check out the "Removing Objects" section, you'll find there many functions that allow you to remove items:

[anArray removeObjectAtIndex: index];
[anArray removeObject: item];
[anArray removeLastObject];

Uncaught SyntaxError: Invalid or unexpected token

The accepted answer work when you have a single line string(the email) but if you have a

multiline string, the error will remain.

Please look into this matter:

<!-- start: definition-->
@{
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
                             string";
    item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
    function Getinfo(text) {
        alert(text);
    }
</script>

Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

How can I introduce multiple conditions in LIKE operator?

Even u can try this

Function

CREATE  FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter varchar(20))
RETURNS @Strings TABLE
(   
  position int IDENTITY PRIMARY KEY,
  value varchar(8000)  
)
AS
BEGIN

DECLARE @index int
SET @index = -1

WHILE (LEN(@text) > 0)
  BEGIN 
    SET @index = CHARINDEX(@delimiter , @text) 
    IF (@index = 0) AND (LEN(@text) > 0) 
      BEGIN  
        INSERT INTO @Strings VALUES (@text)
          BREAK 
      END 
    IF (@index > 1) 
      BEGIN  
        INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))  
        SET @text = RIGHT(@text, (LEN(@text) - @index)) 
      END 
    ELSE
      SET @text = RIGHT(@text, (LEN(@text) - @index))
    END
  RETURN
END

Query

select * from my_table inner join (select value from fn_split('ABC,MOP',','))
as split_table on my_table.column_name like '%'+split_table.value+'%';

How do you import an Eclipse project into Android Studio now?

In newer versions of Android Studio, the best way to bring in an Eclipse/ADT (Android Development Tool) project is to import it directly into Android Studio; we used to recommend you export it from Eclipse to Gradle first, but we haven't been updating ADT often enough to keep pace with Android Studio.

In any event, if you choose "Import Project" from the File menu or from the Welcome screen when you launch Android Studio, it should take you through a specialized wizard that will prompt you that it intends to copy the files into a new directory structure instead of importing them in-place, and it will offer to fix up some common things like converting dependencies into Maven-style includes and such.

It doesn't seem like you're getting this specialized flow. I think it may not be recognizing your imported project as an ADT project, and it's defaulting to the old built-into-IntelliJ behavior which doesn't know about Gradle. To get the specialized import working, the following must be true:

  • The root directory of the project you import must have an AndroidManifest.xml file.
  • Either:
    • The root directory must contain the .project and .classpath files from Eclipse
  • or
    • The root directory must contain res and src directories.

If your project is complex, perhaps you're not pointing it as the root directory it wants to see for the import to succeed.

Using ffmpeg to change framerate

In general, to set a video's FPS to 24, almost always you can do:

With Audio and without re-encoding:

# Extract video stream
ffmpeg -y -i input_video.mp4 -c copy -f h264 output_raw_bitstream.h264
# Extract audio stream
ffmpeg -y -i input_video.mp4 -vn -acodec copy output_audio.aac
# Remux with new FPS 
ffmpeg -y -r 24 -i output_raw_bitstream.h264 -i output-audio.aac -c copy output.mp4

If you want to find the video format (H264 in this case), you can use FFprobe, like this

ffprobe -loglevel error -select_streams v -show_entries stream=codec_name -of default=nw=1:nk=1 input_video.mp4

which will output:

h264

Read more in How can I analyze file and detect if the file is in H.264 video format?


With re-encoding:

ffmpeg -y -i input_video.mp4 -vf -r 24 output.mp4

Passing event and argument to v-on in Vue.js

If you want to access event object as well as data passed, you have to pass event and ticket.id both as parameters, like following:

HTML

<input type="number" v-on:input="addToCart($event, ticket.id)" min="0" placeholder="0">

Javascript

methods: {
  addToCart: function (event, id) {
    // use event here as well as id
    console.log('In addToCart')
    console.log(id)
  }
}

See working fiddle: https://jsfiddle.net/nee5nszL/

Edited: case with vue-router

In case you are using vue-router, you may have to use $event in your v-on:input method like following:

<input type="number" v-on:input="addToCart($event, num)" min="0" placeholder="0">

Here is working fiddle.

Convert the values in a column into row names in an existing data frame

It looks like the one-liner got even simpler along the line (currently using R 3.5.3):

# generate original data.frame
df <- data.frame(a = letters[1:10], b = 1:10, c = LETTERS[1:10])
# use first column for row names
df <- data.frame(df, row.names = 1)

The column used for row names is removed automatically.

Generating all permutations of a given string

//Rotate and create words beginning with all letter possible and push to stack 1

//Read from stack1 and for each word create words with other letters at the next location by rotation and so on 

/*  eg : man

    1. push1 - man, anm, nma
    2. pop1 - nma ,  push2 - nam,nma
       pop1 - anm ,  push2 - amn,anm
       pop1 - man ,  push2 - mna,man
*/

public class StringPermute {

    static String str;
    static String word;
    static int top1 = -1;
    static int top2 = -1;
    static String[] stringArray1;
    static String[] stringArray2;
    static int strlength = 0;

    public static void main(String[] args) throws IOException {
        System.out.println("Enter String : ");
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader bfr = new BufferedReader(isr);
        str = bfr.readLine();
        word = str;
        strlength = str.length();
        int n = 1;
        for (int i = 1; i <= strlength; i++) {
            n = n * i;
        }
        stringArray1 = new String[n];
        stringArray2 = new String[n];
        push(word, 1);
        doPermute();
        display();
    }

    public static void push(String word, int x) {
        if (x == 1)
            stringArray1[++top1] = word;
        else
            stringArray2[++top2] = word;
    }

    public static String pop(int x) {
        if (x == 1)
            return stringArray1[top1--];
        else
            return stringArray2[top2--];
    }

    public static void doPermute() {

        for (int j = strlength; j >= 2; j--)
            popper(j);

    }

    public static void popper(int length) {
        // pop from stack1 , rotate each word n times and push to stack 2
        if (top1 > -1) {
            while (top1 > -1) {
                word = pop(1);
                for (int j = 0; j < length; j++) {
                    rotate(length);
                    push(word, 2);
                }
            }
        }
        // pop from stack2 , rotate each word n times w.r.t position and push to
        // stack 1
        else {
            while (top2 > -1) {
                word = pop(2);
                for (int j = 0; j < length; j++) {
                    rotate(length);
                    push(word, 1);
                }
            }
        }

    }

    public static void rotate(int position) {
        char[] charstring = new char[100];
        for (int j = 0; j < word.length(); j++)
            charstring[j] = word.charAt(j);

        int startpos = strlength - position;
        char temp = charstring[startpos];
        for (int i = startpos; i < strlength - 1; i++) {
            charstring[i] = charstring[i + 1];
        }
        charstring[strlength - 1] = temp;
        word = new String(charstring).trim();
    }

    public static void display() {
        int top;
        if (top1 > -1) {
            while (top1 > -1)
                System.out.println(stringArray1[top1--]);
        } else {
            while (top2 > -1)
                System.out.println(stringArray2[top2--]);
        }
    }
}

How to check if file already exists in the folder

Dim SourcePath As String = "c:\SomeFolder\SomeFileYouWantToCopy.txt" 'This is just an example string and could be anything, it maps to fileToCopy in your code.
Dim SaveDirectory As string = "c:\DestinationFolder"

Dim Filename As String = System.IO.Path.GetFileName(SourcePath) 'get the filename of the original file without the directory on it
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, Filename) 'combines the saveDirectory and the filename to get a fully qualified path.

If System.IO.File.Exists(SavePath) Then
   'The file exists
Else
    'the file doesn't exist
End If

Using prepared statements with JDBCTemplate

By default, the JDBCTemplate does its own PreparedStatement internally, if you just use the .update(String sql, Object ... args) form. Spring, and your database, will manage the compiled query for you, so you don't have to worry about opening, closing, resource protection, etc. One of the saving graces of Spring. A link to Spring 2.5's documentation on this. Hope it makes things clearer. Also, statement caching can be done at the JDBC level, as in the case of at least some of Oracle's JDBC drivers. That will go into a lot more detail than I can competently.

Convert Java object to XML string

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

private String generateXml(Object obj, Class objClass) throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(objClass);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        StringWriter sw = new StringWriter();
        jaxbMarshaller.marshal(obj, sw);
        return sw.toString();
    }

How to remove the first character of string in PHP?

The code works well for me.

$str = substr($str ,-(strlen($str)-1));

Maybe, contribute with answers too.

Inheritance and init method in Python

A simple change in Num2 class like this:

super().__init__(num) 

It works in python3.

class Num:
        def __init__(self,num):
                self.n1 = num

class Num2(Num):
        def __init__(self,num):
                super().__init__(num)
                self.n2 = num*2
        def show(self):
                print (self.n1,self.n2)

mynumber = Num2(8)
mynumber.show()

What are CN, OU, DC in an LDAP search?

I want to add somethings different from definitions of words. Most of them will be visual.

Technically, LDAP is just a protocol that defines the method by which directory data is accessed.Necessarily, it also defines and describes how data is represented in the directory service

Data is represented in an LDAP system as a hierarchy of objects, each of which is called an entry. The resulting tree structure is called a Directory Information Tree (DIT). The top of the tree is commonly called the root (a.k.a base or the suffix).the Data (Information) Model

To navigate the DIT we can define a path (a DN) to the place where our data is (cn=DEV-India,ou=Distrubition Groups,dc=gp,dc=gl,dc=google,dc=com will take us to a unique entry) or we can define a path (a DN) to where we think our data is (say, ou=Distrubition Groups,dc=gp,dc=gl,dc=google,dc=com) then search for the attribute=value or multiple attribute=value pairs to find our target entry (or entries).

enter image description here

If you want to get more depth information, you visit here

AngularJS Folder Structure

I like this entry about angularjs structure

It's written by one of the angularjs developers, so should give you a good insight

Here's an excerpt:

root-app-folder
+-- index.html
+-- scripts
¦   +-- controllers
¦   ¦   +-- main.js
¦   ¦   +-- ...
¦   +-- directives
¦   ¦   +-- myDirective.js
¦   ¦   +-- ...
¦   +-- filters
¦   ¦   +-- myFilter.js
¦   ¦   +-- ...
¦   +-- services
¦   ¦   +-- myService.js
¦   ¦   +-- ...
¦   +-- vendor
¦   ¦   +-- angular.js
¦   ¦   +-- angular.min.js
¦   ¦   +-- es5-shim.min.js
¦   ¦   +-- json3.min.js
¦   +-- app.js
+-- styles
¦   +-- ...
+-- views
    +-- main.html
    +-- ...

Increase max execution time for php

Use mod_php7.c instead of mod_php5.c for PHP 7

Example

<IfModule mod_php7.c>
   php_value max_execution_time 500
</IfModule>

Count number of times value appears in particular column in MySQL

SELECT column_name, COUNT(column_name)
FROM table_name
GROUP BY column_name

Angular 2 Date Input not binding to date value

use DatePipe

> // ts file

import { DatePipe } from '@angular/common';

@Component({
....
providers:[DatePipe]
})

export class FormComponent {

constructor(private datePipe : DatePipe){}

    demoUser = new User(0, '', '', '', '', this.datePipe.transform(new Date(), 'yyyy-MM-dd'), '', 0, [], []);  
}

How do I import a .dmp file into Oracle?

.dmp files are dumps of oracle databases created with the "exp" command. You can import them using the "imp" command.

If you have an oracle client intalled on your machine, you can executed the command

imp help=y

to find out how it works. What will definitely help is knowing from wich schema the data was exported and what the oracle version was.

Gradle: Execution failed for task ':processDebugManifest'

I came across similar problem ,when I run

cordova build android

which report errors:

 /home/app/phonegap/helloworld/platforms/android/AndroidManifest.xml:15:5 Error:
uses-sdk:minSdkVersion 7 cannot be smaller than version 10 declared in library  /home/app/phonegap/helloworld/platforms/android/build/intermediates/exploded-aar/android/CordovaLib/unspecified/debug/AndroidManifest.xml
Suggestion: use tools:overrideLibrary="org.apache.cordova" to force usage

:processDebugManifest FAILED

FAILURE: Build failed with an exception.

  • What went wrong: Execution failed for task ':processDebugManifest'.

    Manifest merger failed : uses-sdk:minSdkVersion 7 cannot be smaller than version 10 declared in library /home/app/phonegap/helloworld/platforms/android/build/intermediates/exploded-aar/android/CordovaLib/unspecified/debug/AndroidManifest.xml Suggestion: use tools:overrideLibrary="org.apache.cordova" to force usage

In my case,

uses-sdk:minSdkVersion 7 cannot be smaller than version 10 declared

,above solution do not work! but I solve them by replace

<preference name="android-minSdkVersion" value="7" />

as

<preference name="android-minSdkVersion" value="10" />

in this two file /home/app/phonegap/helloworld/config.xml , /home/app/phonegap/helloworld/platforms/android/res/xml/config.xml

Python syntax for "if a or b or c but not all of them"

This question already had many highly upvoted answers and an accepted answer, but all of them so far were distracted by various ways to express the boolean problem and missed a crucial point:

I have a python script that can receive either zero or three command line arguments. (Either it runs on default behavior or needs all three values specified)

This logic should not be the responsibility of your code in the first place, rather it should be handled by argparse module. Don't bother writing a complex if statement, instead prefer to setup your argument parser something like this:

#!/usr/bin/env python
import argparse as ap
parser = ap.ArgumentParser()
parser.add_argument('--foo', nargs=3, default=['x', 'y', 'z'])
args = parser.parse_args()
print(args.foo)

And yes, it should be an option not a positional argument, because it is after all optional.


edited: To address the concern of LarsH in the comments, below is an example of how you could write it if you were certain you wanted the interface with either 3 or 0 positional args. I am of the opinion that the previous interface is better style, because optional arguments should be options, but here's an alternative approach for the sake of completeness. Note the overriding kwarg usage when creating your parser, because argparse will auto-generate a misleading usage message otherwise!

#!/usr/bin/env python
import argparse as ap
parser = ap.ArgumentParser(usage='%(prog)s [-h] [a b c]\n')
parser.add_argument('abc', nargs='*', help='specify 3 or 0 items', default=['x', 'y', 'z'])
args = parser.parse_args()
if len(args.abc) != 3:
  parser.error('expected 3 arguments')
print(args.abc)

Here are some usage examples:

# default case
wim@wim-zenbook:/tmp$ ./three_or_none.py 
['x', 'y', 'z']

# explicit case
wim@wim-zenbook:/tmp$ ./three_or_none.py 1 2 3
['1', '2', '3']

# example failure mode
wim@wim-zenbook:/tmp$ ./three_or_none.py 1 2 
usage: three_or_none.py [-h] [a b c]
three_or_none.py: error: expected 3 arguments

How to use componentWillMount() in React Hooks?

useLayoutEffect could accomplish this with an empty set of observers ([]) if the functionality is actually similar to componentWillMount -- it will run before the first content gets to the DOM -- though there are actually two updates but they are synchronous before drawing to the screen.

for example:


function MyComponent({ ...andItsProps }) {
     useLayoutEffect(()=> {
          console.log('I am about to render!');
     },[]);

     return (<div>some content</div>);
}

The benefit over useState with an initializer/setter or useEffect is though it may compute a render pass, there are no actual re-renders to the DOM that a user will notice, and it is run before the first noticable render, which is not the case for useEffect. The downside is of course a slight delay in your first render since a check/update has to happen before painting to screen. It really does depend on your use-case, though.

I think personally, useMemo is fine in some niche cases where you need to do something heavy -- as long as you keep in mind it is the exception vs the norm.

The right way of setting <a href=""> when it's a local file

This can happen when you are running IIS and you run the html page through it, then the Local file system will not be accessible.

To make your link work locally the run the calling html page directly from file browser not visual studio F5 or IIS simply click it to open from the file system, and make sure you are using the link like this:

<a href="file:///F:/VS_2015_WorkSpace/Projects/xyz/Intro.html">Intro</a>