Programs & Examples On #Named instance

How can I select an element by name with jQuery?

Personally, what I've done in the past is give them a common class id and used that to select them. It may not be ideal as they have a class specified that may not exist, but it makes the selection a hell of a lot easier. Just make sure you're unique in your classnames.

i.e. for the example above I'd use your selection by class. Better still would be to change the class name from bold to 'tcol1', so you don't get any accidental inclusions into the jQuery results. If bold does actually refer to a CSS class, you can always specify both in the class property - i.e. 'class="tcol1 bold"'.

In summary, if you can't select by Name, either use a complicated jQuery selector and accept any related performance hit or use Class selectors.

You can always limit the jQuery scope by including the table name i.e. $('#tableID > .bold')

That should restrict jQuery from searching the "world".

Its could still be classed as a complicated selector, but it quickly constrains any searching to within the table with the ID of '#tableID', so keeps the processing to a minimum.

An alternative of this if you're looking for more than 1 element within #table1 would be to look this up separately and then pass it to jQuery as this limits the scope, but saves a bit of processing to look it up each time.

var tbl = $('#tableID');
var boldElements = $('.bold',tbl);
var rows = $('tr',tbl);
if (rows.length) {
   var row1 = rows[0]; 
   var firstRowCells = $('td',row1); 
}

How do I trim leading/trailing whitespace in a standard way?

void trim(char* const str)
{
    char* begin = str;
    char* end = str;
    while (isspace(*begin))
    {
        ++begin;
    }
    char* s = begin;
    while (*s != '\0')
    {
        if (!isspace(*s++))
        {
            end = s;
        }
    }
    *end = '\0';
    const int dist = end - begin;
    if (begin > str && dist > 0)
    {
        memmove(str, begin, dist + 1);
    }
}

Modifies string in place, so you can still delete it.

Doesn't use fancy pants library functions (unless you consider memmove fancy).

Handles string overlap.

Trims front and back (not middle, sorry).

Fast if string is large (memmove often written in assembly).

Only moves characters if required (I find this true in most use cases because strings rarely have leading spaces and often don't have tailing spaces)

I would like to test this but I'm running late. Enjoy finding bugs... :-)

SQL LEFT-JOIN on 2 fields for MySQL

Let's try this way:

select 
    a.ip, 
    a.os, 
    a.hostname, 
    a.port, 
    a.protocol, 
    b.state
from a
left join b 
    on a.ip = b.ip 
        and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/

So, in where clause you can filter result set by column from right table only on this way:

...
where b.somecolumn <> (=) null

When is assembly faster than C?

LInux assembly howto, asks this question and gives the pros and cons of using assembly.

Is it possible to simulate key press events programmatically?

For those interested, you can, in-fact recreate keyboard input events reliably. In order to change text in input area (move cursors, or the page via an input character) you have to follow the DOM event model closely: http://www.w3.org/TR/DOM-Level-3-Events/#h4_events-inputevents

The model should do:

  • focus (dispatched on the DOM with the target set)

Then for each character:

  • keydown (dispatched on the DOM)
  • beforeinput (dispatched at the target if its a textarea or input)
  • keypress (dispatched on the DOM)
  • input (dispatched at the target if its a textarea or input)
  • change (dispatched at the target if its a select)
  • keyup (dispatched on the DOM)

Then, optionally for most:

  • blur (dispatched on the DOM with the target set)

This actually changes the text in the page via javascript (without modifying value statements) and sets off any javascript listeners/handlers appropriately. If you mess up the sequence javascript will not fire in the appropriate order, the text in the input box will not change, the selections will not change or the cursor will not move to the next space in the text area.

Unfortunately the code was written for an employer under an NDA so I cannot share it, but it is definitely possible but you must recreate the entire key input "stack" for each element in the correct order.

What is the meaning of curly braces?

In languages like C curly braces ({}) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.

The best way to remove duplicate values from NSMutableArray in Objective-C?

just use this simple code :

NSArray *hasDuplicates = /* (...) */;
NSArray *noDuplicates = [[NSSet setWithArray: hasDuplicates] allObjects];

since nsset doesn't allow duplicate values and all objects returns an array

How to check that a JCheckBox is checked?

By using itemStateChanged(ItemListener) you can track selecting and deselecting checkbox (and do whatever you want based on it):

myCheckBox.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
            //do something...
        } else {//checkbox has been deselected
            //do something...
        };
    }
});

Java Swing itemStateChanged docu should help too. By using isSelected() method you can just test if actual is checkbox selected:

if(myCheckBox.isSelected()){_do_something_if_selected_}

How to get the selected value from drop down list in jsp?

    <%-- if you want to select value from drop-downlist here is jsp code. --%>
    <body>
    <form name="f1" method="get" action="#">
       <select name="clr">
           <option>Red</option>
           <option>Blue</option>   
           <option>Green</option>
           <option>Pink</option>
       </select>
     <input type="submit" name="submit" value="Select Color"/>
    </form>
    <%-- To display selected value from dropdown list. --%>
     <% 
                String s=request.getParameter("clr");
                if (s !=null)
                {
                    out.println("Selected Color is : "+s);
                }
      %>
</body>

How to use Lambda in LINQ select statement

Using Lambda expressions:

  1. If we don't have a specific class to bind the result:

     var stores = context.Stores.Select(x => new { x.id, x.name, x.city }).ToList();
    
  2. If we have a specific class then we need to bind the result with it:

    List<SelectListItem> stores = context.Stores.Select(x => new SelectListItem { Id = x.id, Name = x.name, City = x.city }).ToList();
    

Using simple LINQ expressions:

  1. If we don't have a specific class to bind the result:

    var stores = (from a in context.Stores select new { x.id, x.name, x.city }).ToList();
    
  2. If we have a specific class then we need to bind the result with it:

    List<SelectListItem> stores = (from a in context.Stores select new SelectListItem{ Id = x.id, Name = x.name, City = x.city }).ToList();
    

How can I add a .npmrc file?

There are a few different points here:

  1. Where is the .npmrc file created.
  2. How can you download private packages

Running npm config ls -l will show you all the implicit settings for npm, including what it thinks is the right place to put the .npmrc. But if you have never logged in (using npm login) it will be empty. Simply log in to create it.

Another thing is #2. You can actually do that by putting a .npmrc file in the NPM package's root. It will then be used by NPM when authenticating. It also supports variable interpolation from your shell so you could do stuff like this:

; Get the auth token to use for fetching private packages from our private scope
; see http://blog.npmjs.org/post/118393368555/deploying-with-npm-private-modules
; and also https://docs.npmjs.com/files/npmrc
//registry.npmjs.org/:_authToken=${NPM_TOKEN}

Pointers

Conditional formatting based on another cell's value

Note: when it says "B5" in the explanation below, it actually means "B{current_row}", so for C5 it's B5, for C6 it's B6 and so on. Unless you specify $B$5 - then you refer to one specific cell.


This is supported in Google Sheets as of 2015: https://support.google.com/drive/answer/78413#formulas

In your case, you will need to set conditional formatting on B5.

  • Use the "Custom formula is" option and set it to =B5>0.8*C5.
  • set the "Range" option to B5.
  • set the desired color

You can repeat this process to add more colors for the background or text or a color scale.

Even better, make a single rule apply to all rows by using ranges in "Range". Example assuming the first row is a header:

  • On B2 conditional formatting, set the "Custom formula is" to =B2>0.8*C2.
  • set the "Range" option to B2:B.
  • set the desired color

Will be like the previous example but works on all rows, not just row 5.

Ranges can also be used in the "Custom formula is" so you can color an entire row based on their column values.

MySQL CURRENT_TIMESTAMP on create and on update

Guess this is a old post but actually i guess mysql supports 2 TIMESTAMP in its recent editions mysql 5.6.25 thats what im using as of now.

File content into unix variable with newlines

This is due to IFS (Internal Field Separator) variable which contains newline.

$ cat xx1
1
2

$ A=`cat xx1`
$ echo $A
1 2

$ echo "|$IFS|"
|       
|

A workaround is to reset IFS to not contain the newline, temporarily:

$ IFSBAK=$IFS
$ IFS=" "
$ A=`cat xx1` # Can use $() as well
$ echo $A
1
2
$ IFS=$IFSBAK

To REVERT this horrible change for IFS:

IFS=$IFSBAK

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

This is what worked for me: Using Gradle 4.8.1

buildscript {
    ext.kotlin_version = '1.1.1' 
repositories {
    jcenter()
    google()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.1.0'}
}
allprojects {
    repositories {
        mavenLocal()
        jcenter()
        google()
        maven {
            url "$rootDir/../node_modules/react-native/android"
        }
    maven {
            url 'https://dl.bintray.com/kotlin/kotlin-dev/'
    }
  }
}   

LINQ select one field from list of DTO objects to array

This is very simple in LinQ... You can use the select statement to get an Enumerable of properties of the objects.

var mySkus = myLines.Select(x => x.Sku);

Or if you want it as an Array just do...

var mySkus = myLines.Select(x => x.Sku).ToArray();

Why do we have to override the equals() method in Java?

.equals() doesn't perform an intelligent comparison for most classes unless the class overrides it. If it's not defined for a (user) class, it behaves the same as ==.

Reference: http://www.leepoint.net/notes-java/data/expressions/22compareobjects.html http://www.leepoint.net/data/expressions/22compareobjects.html

Changing the default title of confirm() in JavaScript?

Don't use the confirm() dialog then... easy to use a custom dialog from prototype/scriptaculous, YUI, jQuery ... there's plenty out there.

Load RSA public key from file

Below is the relevant information from the link which Zaki provided.

Generate a 2048-bit RSA private key

$ openssl genrsa -out private_key.pem 2048

Convert private Key to PKCS#8 format (so Java can read it)

$ openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt

Output public key portion in DER format (so Java can read it)

$ openssl rsa -in private_key.pem -pubout -outform DER -out public_key.der

Private key

import java.io.*;
import java.nio.*;
import java.security.*;
import java.security.spec.*;

public class PrivateKeyReader {

  public static PrivateKey get(String filename)
  throws Exception {

    byte[] keyBytes = Files.readAllBytes(Paths.get(filename));

    PKCS8EncodedKeySpec spec =
      new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(spec);
  }
}

Public key

import java.io.*;
import java.nio.*;
import java.security.*;
import java.security.spec.*;

public class PublicKeyReader {

  public static PublicKey get(String filename)
    throws Exception {

    byte[] keyBytes = Files.readAllBytes(Paths.get(filename));

    X509EncodedKeySpec spec =
      new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePublic(spec);
  }
}

Jenkins CI: How to trigger builds on SVN commit

There are two ways to go about this:

I recommend the first option initially, due to its ease of implementation. Once you mature in your build processes, switch over to the second.

  1. Poll the repository to see if changes occurred. This might "skip" a commit if two commits come in within the same polling interval. Description of how to do so here, note the fourth screenshot where you configure on the job a "build trigger" based on polling the repository (with a crontab-like configuration).

  2. Configure your repository to have a post-commit hook which notifies Jenkins that a build needs to start. Description of how to do so here, in the section "post-commit hooks"

The SVN Tag feature is not part of the polling, it is part of promoting the current "head" of the source code to a tag, to snapshot a build. This allows you to refer to Jenkins buid #32 as SVN tag /tags/build-32 (or something similar).

How to upgrade Python version to 3.7?

On ubuntu you can add this PPA Repository and use it to install python 3.7: https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.7

Or a different PPA that provides several Python versions is Deadsnakes: https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa

See also here: https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get (I know it says 3.6 in the url, but the deadsnakes ppa also contains 3.7 so you can use it for 3.7 just the same)

If you want "official" you'd have to install it from the sources from the site, get the code (which you already downloaded) and do this:

tar -xf Python-3.7.0.tar.xz
cd Python-3.7.0
./configure
make
sudo make install        <-- sudo is required.

This might take a while

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

Javascript Date - set just the date, ignoring time?

If you don't mind creating an extra date object, you could try:

var tempDate = new Date(parseInt(item.timestamp, 10));
var visitDate = new Date (tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate());

I do something very similar to get a date of the current month without the time.

jQuery get the id/value of <li> element after click function

If you change your html code a bit - remove the ids

<ul id='myid'>  
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>

Then the jquery code you want is...

$("#myid li").click(function() {
    alert($(this).prevAll().length+1);
});?

You don't need to place any ids, just keep on adding li items.

Take a look at demo

Useful links

How to copy java.util.list Collection

You may create a new list with an input of a previous list like so:

List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);

This will allow you to modify the order or what elemtents are contained independent of the first list.

Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.

example:

MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"

Edit

To avoid this you need a deep copy of each element in the list like so:

List<Torero> one = new ArrayList<Torero>();
//add elements

List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
    Torero copy = deepCopy(t);
    two.add(copy);
}

with copy like the following:

public Torero deepCopy(Torero input){
    Torero copy = new Torero();
    copy.setValue(input.getValue());//.. copy primitives, deep copy objects again

    return copy;
}

How can I get the name of an object in Python?

Here's another way to think about it. Suppose there were a name() function that returned the name of its argument. Given the following code:

def f(a):
    return a

b = "x"
c = b
d = f(c)

e = [f(b), f(c), f(d)]

What should name(e[2]) return, and why?

Parsing XML in Python using ElementTree example

So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

import elementtree.ElementTree as ET

tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')

print thingy.attrib

and got the following back:

{'name': 'NWIS Time Series Instantaneous Values'}

It appears to have found the timeSeries element without needing to use numerical indices.

What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

Whitespace Matching Regex - Java

For Java (not php, not javascript, not anyother):

txt.replaceAll("\\p{javaSpaceChar}{2,}"," ")

An efficient way to Base64 encode a byte array?

You could use the String Convert.ToBase64String(byte[]) to encode the byte array into a base64 string, then Byte[] Convert.FromBase64String(string) to convert the resulting string back into a byte array.

Are HTTP cookies port specific?

In IE 8, cookies (verified only against localhost) are shared between ports. In FF 10, they are not.

I've posted this answer so that readers will have at least one concrete option for testing each scenario.

How to perform case-insensitive sorting in JavaScript?

It is time to revisit this old question.

You should not use solutions relying on toLowerCase. They are inefficient and simply don't work in some languages (Turkish for instance). Prefer this:

['Foo', 'bar'].sort((a, b) => a.localeCompare(b, undefined, {sensitivity: 'base'}))

Check the documentation for browser compatibility and all there is to know about the sensitivity option.

Questions every good Database/SQL developer should be able to answer

An interesting question would involve relational division, or how to express a "for all" relationship, which would require nested not exists clauses.

The question comes straigh from this link.

Given the following tables, representing pilots that can fly planes and planes in a hangar:

create table PilotSkills (
  pilot_name char(15) not null,
  plane_name char(15) not null
)

create table Hangar (
  plane_name char(15) not null
)

Select the names of the pilots who can fly every plane in the hangar.

The answer:

select distinct pilot_name
from PilotSkills as ps1 
where not exists (
  select * from hangar
  where not exists (
    select * from PilotSkills as ps2 where 
      ps1.pilot_name = ps2.pilot_name and 
      ps2.plane_name = hangar.plane_name
  )
)

Or ...

Select all stack overflow users that have accepted answers in questions tagged with the 10 most popular programming languages.

The (possible) answer (assuming an Accepted_Answers view and a Target_Language_Tags table with the desired tags):

select distinct u.user_name
from Users as u
join Accepted_Answers as a1 on u.user_id = a1.user_id
where not exists (
  select * from Target_Language_Tags t
  where not exists (
    select * 
      from Accepted_Answers as a2
      join Questions as q on a2.question_id = q.question_id
      join Question_Tags as qt on qt.question_id = q.question_id 
    where 
      qt.tag_name = t.tag_name and
      a1.user_id = a2.user_id
  )
)

Get exit code for command in bash/ksh

Try

safeRunCommand() {
   "$@"

   if [ $? != 0 ]; then
      printf "Error when executing command: '$1'"
      exit $ERROR_CODE
   fi
}

select2 changing items dynamically

I'm successfully using the following to update options dynamically:

$control.select2('destroy').empty().select2({data: [{id: 1, text: 'new text'}]});

The view didn't return an HttpResponse object. It returned None instead

I had the same error using an UpdateView

I had this:

if form.is_valid() and form2.is_valid():
    form.save()
    form2.save()
    return HttpResponseRedirect(self.get_success_url())

and I solved just doing:

if form.is_valid() and form2.is_valid():
    form.save()
    form2.save()
    return HttpResponseRedirect(reverse_lazy('adopcion:solicitud_listar'))

SQL Server function to return minimum date (January 1, 1753)

Here is a fast and highly readable way to get the min date value

Note: This is a Deterministic Function, so to improve performance further we might as well apply WITH SCHEMABINDING to the return value.

Create a function

CREATE FUNCTION MinDate()
RETURNS DATETIME WITH SCHEMABINDING
AS
BEGIN
    RETURN CONVERT(DATETIME, -53690)

END

Call the function

dbo.MinDate()

Example 1

PRINT dbo.MinDate()

Example 2

PRINT 'The minimimum date allowed in an SQL database is ' + CONVERT(VARCHAR(MAX), dbo.MinDate())

Example 3

SELECT * FROM Table WHERE DateValue > dbo.MinDate()

Example 4

SELECT dbo.MinDate() AS MinDate

Example 5

DECLARE @MinDate AS DATETIME = dbo.MinDate()

SELECT @MinDate AS MinDate

How to make lists contain only distinct element in Python?

Let me explain to you by an example:

if you have Python list

>>> randomList = ["a","f", "b", "c", "d", "a", "c", "e", "d", "f", "e"]

and you want to remove duplicates from it.

>>> uniqueList = []

>>> for letter in randomList:
    if letter not in uniqueList:
        uniqueList.append(letter)

>>> uniqueList
['a', 'f', 'b', 'c', 'd', 'e']

This is how you can remove duplicates from the list.

How can javascript upload a blob?

I could not get the above example to work with blobs and I wanted to know what exactly is in upload.php. So here you go:

(tested only in Chrome 28.0.1500.95)

// javascript function that uploads a blob to upload.php
function uploadBlob(){
    // create a blob here for testing
    var blob = new Blob(["i am a blob"]);
    //var blob = yourAudioBlobCapturedFromWebAudioAPI;// for example   
    var reader = new FileReader();
    // this function is triggered once a call to readAsDataURL returns
    reader.onload = function(event){
        var fd = new FormData();
        fd.append('fname', 'test.txt');
        fd.append('data', event.target.result);
        $.ajax({
            type: 'POST',
            url: 'upload.php',
            data: fd,
            processData: false,
            contentType: false
        }).done(function(data) {
            // print the output from the upload.php script
            console.log(data);
        });
    };      
    // trigger the read from the reader...
    reader.readAsDataURL(blob);

}

The contents of upload.php:

<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data, 
echo ($decodedData);
$filename = "test.txt";
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>

pandas convert some columns into rows

Use set_index with stack for MultiIndex Series, then for DataFrame add reset_index with rename:

df1 = (df.set_index(["location", "name"])
         .stack()
         .reset_index(name='Value')
         .rename(columns={'level_2':'Date'}))
print (df1)
  location  name        Date  Value
0        A  test    Jan-2010     12
1        A  test    Feb-2010     20
2        A  test  March-2010     30
3        B   foo    Jan-2010     18
4        B   foo    Feb-2010     20
5        B   foo  March-2010     25

Why I get 'list' object has no attribute 'items'?

If you don't care about the type of the numbers you can simply use:

qs[0].values()

Retrieving the text of the selected <option> in <select> element

document.getElementById('test').options[document.getElementById('test').selectedIndex].text;

Finding a branch point with Git?

After a lot of research and discussions, it's clear there's no magic bullet that would work in all situations, at least not in the current version of Git.

That's why I wrote a couple of patches that add the concept of a tail branch. Each time a branch is created, a pointer to the original point is created too, the tail ref. This ref gets updated every time the branch is rebased.

To find out the branch point of the devel branch, all you have to do is use devel@{tail}, that's it.

https://github.com/felipec/git/commits/fc/tail

Find out the history of SQL queries

For recent SQL:

select * from v$sql

For history:

select * from dba_hist_sqltext

What is FCM token in Firebase?

What is it exactly?

An FCM Token, or much commonly known as a registrationToken like in . As described in the GCM FCM docs:

An ID issued by the GCM connection servers to the client app that allows it to receive messages. Note that registration tokens must be kept secret.


How can I get that token?

Update: The token can still be retrieved by calling getToken(), however, as per FCM's latest version, the FirebaseInstanceIdService.onTokenRefresh() has been replaced with FirebaseMessagingService.onNewToken() -- which in my experience functions the same way as onTokenRefresh() did.


Old answer:

As per the FCM docs:

On initial startup of your app, the FCM SDK generates a registration token for the client app instance. If you want to target single devices or create device groups, you'll need to access this token.

You can access the token's value by extending FirebaseInstanceIdService. Make sure you have added the service to your manifest, then call getToken in the context of onTokenRefresh, and log the value as shown:

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    // TODO: Implement this method to send any registration to your app's servers.
    sendRegistrationToServer(refreshedToken);
}

The onTokenRefreshcallback fires whenever a new token is generated, so calling getToken in its context ensures that you are accessing a current, available registration token. FirebaseInstanceID.getToken() returns null if the token has not yet been generated.

After you've obtained the token, you can send it to your app server and store it using your preferred method. See the Instance ID API reference for full detail on the API.

How to parse a JSON string into JsonNode in Jackson?

A third variant:

ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readValue("{\"k1\":\"v1\"}", JsonNode.class);

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

How can I call the 'base implementation' of an overridden virtual method?

I konow it's history question now. But for other googlers: you could write something like this. But this requires change in base class what makes it useless with external libraries.

class A
{
  void protoX() { Console.WriteLine("x"); }
  virtual void X() { protoX(); }
}

class B : A
{
  override void X() { Console.WriteLine("y"); }
}

class Program
{
  static void Main()
  {
    A b = new B();
    // Call A.X somehow, not B.X...
    b.protoX();


  }

CSS root directory

This problem that the "../" means step up (parent folder) link "../images/img.png" will not work because when you are using ajax like data passing to the web site from the server.

What you have to do is point the image location to root with "./" then the second folder (in this case the second folder is "images")

url("./images/img.png")

if you have folders like this

root -> content -> images

then you use url("./content/images/img.png"), remember your image will not visible in the editor window but when it passed to the browser using ajax it will display.

Add two numbers and display result in textbox with Javascript

var first_number = parseInt(document.getElementById("Text1").value);
var second_number = parseInt(document.getElementById("Text2").value);

// This is because your method .getElementById has the letter 's': .getElement**s**ById

Prevent Caching in ASP.NET MVC for specific actions using an attribute

Here's the NoCache attribute proposed by mattytommo, simplified by using the information from Chris Moschini's answer:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : OutputCacheAttribute
{
    public NoCacheAttribute()
    {
        this.Duration = 0;
    }
}

Generate random array of floats between a range

Why not to combine random.uniform with a list comprehension?

>>> def random_floats(low, high, size):
...    return [random.uniform(low, high) for _ in xrange(size)]
... 
>>> random_floats(0.5, 2.8, 5)
[2.366910411506704, 1.878800401620107, 1.0145196974227986, 2.332600336488709, 1.945869474662082]

What is the exact meaning of Git Bash?

Bash is a Command Line Interface that was created over twenty-seven years ago by Brian Fox as a free software replacement for the Bourne Shell. A shell is a specific kind of Command Line Interface. Bash is "open source" which means that anyone can read the code and suggest changes. Since its beginning, it has been supported by a large community of engineers who have worked to make it an incredible tool. Bash is the default shell for Linux and Mac. For these reasons, Bash is the most used and widely distributed shell.

Windows has a different Command Line Interface, called Command Prompt. While this has many of the same features as Bash, Bash is much more popular. Because of the strength of the open source community and the tools they provide, mastering Bash is a better investment than mastering Command Prompt.

To use Bash on a Windows computer, we need to download and install a program called Git Bash. Git Bash (Is the Bash for windows) allows us to easily access Bash as well as another tool called Git, inside the Windows environment.

Fill background color left to right CSS

A single css code on hover can do the trick: box-shadow: inset 100px 0 0 0 #e0e0e0;

A complete demo can be found in my fiddle:

https://jsfiddle.net/shuvamallick/3o0h5oka/

Static methods in Python?

Yep, using the staticmethod decorator

class MyClass(object):
    @staticmethod
    def the_static_method(x):
        print(x)

MyClass.the_static_method(2)  # outputs 2

Note that some code might use the old method of defining a static method, using staticmethod as a function rather than a decorator. This should only be used if you have to support ancient versions of Python (2.2 and 2.3)

class MyClass(object):
    def the_static_method(x):
        print(x)
    the_static_method = staticmethod(the_static_method)

MyClass.the_static_method(2)  # outputs 2

This is entirely identical to the first example (using @staticmethod), just not using the nice decorator syntax

Finally, use staticmethod sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.


The following is verbatim from the documentation::

A static method does not receive an implicit first argument. To declare a static method, use this idiom:

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

The @staticmethod form is a function decorator ā€“ see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see classmethod().

For more information on static methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

New in version 2.2.

Changed in version 2.4: Function decorator syntax added.

Count number of lines in a git repository

If you want to get the number of lines from a certain author, try the following code:

git ls-files "*.java" | xargs -I{} git blame {} | grep ${your_name} | wc -l

What is a good alternative to using an image map generator?

I have found Adobe Dreamweaver to be quite good at that. However, it's not free.

Convert dictionary to bytes and back again python?

If you need to convert the dictionary to binary, you need to convert it to a string (JSON) as described in the previous answer, then you can convert it to binary.

For example:

my_dict = {'key' : [1,2,3]}

import json
def dict_to_binary(the_dict):
    str = json.dumps(the_dict)
    binary = ' '.join(format(ord(letter), 'b') for letter in str)
    return binary


def binary_to_dict(the_binary):
    jsn = ''.join(chr(int(x, 2)) for x in the_binary.split())
    d = json.loads(jsn)  
    return d

bin = dict_to_binary(my_dict)
print bin

dct = binary_to_dict(bin)
print dct

will give the output

1111011 100010 1101011 100010 111010 100000 1011011 110001 101100 100000 110010 101100 100000 110011 1011101 1111101

{u'key': [1, 2, 3]}

Trigger insert old values- values that was updated

ALTER trigger ETU on Employee FOR UPDATE AS insert into Log (EmployeeId, LogDate, OldName) select EmployeeId, getdate(), name from deleted go

What is the difference between a web API and a web service?

All WebServices is API but all API is not WebServices, API which is exposed on Web is called web services.

Locate Git installation folder on Mac OS X

The installer from the git homepage installs into /usr/local/git by default. See also this answer. However, if you install XCode4, it will install a git version in /usr/bin. To ensure you can easily upgrade from the website and use the latest git version, edit either your profile information to place /usr/local/git/bin before /usr/bin in the $PATH or edit /etc/paths and insert /usr/local/git/bin as the first entry (see this answer).

Problems when trying to load a package in R due to rJava

Its because either one of the Java versions(32 bit/64 bit) is missing from your computer. Try installing both the Jdks and run the code.
After installing the Jdks open R and type the code

system("java -version")

This will give you the version of Jdk installed. Then try loading the rJava package. This worked for me.

Waiting until two async blocks are executed before starting another block

Answers above are all cool, but they all missed one thing. group executes tasks(blocks) in the thread where it entered when you use dispatch_group_enter/dispatch_group_leave.

- (IBAction)buttonAction:(id)sender {
      dispatch_queue_t demoQueue = dispatch_queue_create("com.demo.group", DISPATCH_QUEUE_CONCURRENT);
      dispatch_async(demoQueue, ^{
        dispatch_group_t demoGroup = dispatch_group_create();
        for(int i = 0; i < 10; i++) {
          dispatch_group_enter(demoGroup);
          [self testMethod:i
                     block:^{
                       dispatch_group_leave(demoGroup);
                     }];
        }

        dispatch_group_notify(demoGroup, dispatch_get_main_queue(), ^{
          NSLog(@"All group tasks are done!");
        });
      });
    }

    - (void)testMethod:(NSInteger)index block:(void(^)(void))completeBlock {
      NSLog(@"Group task started...%ld", index);
      NSLog(@"Current thread is %@ thread", [NSThread isMainThread] ? @"main" : @"not main");
      [NSThread sleepForTimeInterval:1.f];

      if(completeBlock) {
        completeBlock();
      }
    }

this runs in the created concurrent queue demoQueue. If i dont create any queue, it runs in main thread.

- (IBAction)buttonAction:(id)sender {
    dispatch_group_t demoGroup = dispatch_group_create();
    for(int i = 0; i < 10; i++) {
      dispatch_group_enter(demoGroup);
      [self testMethod:i
                 block:^{
                   dispatch_group_leave(demoGroup);
                 }];
    }

    dispatch_group_notify(demoGroup, dispatch_get_main_queue(), ^{
      NSLog(@"All group tasks are done!");
    });
    }

    - (void)testMethod:(NSInteger)index block:(void(^)(void))completeBlock {
      NSLog(@"Group task started...%ld", index);
      NSLog(@"Current thread is %@ thread", [NSThread isMainThread] ? @"main" : @"not main");
      [NSThread sleepForTimeInterval:1.f];

      if(completeBlock) {
        completeBlock();
      }
    }

and there's a third way to make tasks executed in another thread:

- (IBAction)buttonAction:(id)sender {
      dispatch_queue_t demoQueue = dispatch_queue_create("com.demo.group", DISPATCH_QUEUE_CONCURRENT);
      //  dispatch_async(demoQueue, ^{
      __weak ViewController* weakSelf = self;
      dispatch_group_t demoGroup = dispatch_group_create();
      for(int i = 0; i < 10; i++) {
        dispatch_group_enter(demoGroup);
        dispatch_async(demoQueue, ^{
          [weakSelf testMethod:i
                         block:^{
                           dispatch_group_leave(demoGroup);
                         }];
        });
      }

      dispatch_group_notify(demoGroup, dispatch_get_main_queue(), ^{
        NSLog(@"All group tasks are done!");
      });
      //  });
    }

Of course, as mentioned you can use dispatch_group_async to get what you want.

BEGIN - END block atomic transactions in PL/SQL

The default behavior of Commit PL/SQL block:

You should explicitly commit or roll back every transaction. Whether you issue the commit or rollback in your PL/SQL program or from a client program depends on the application logic. If you do not commit or roll back a transaction explicitly, the client environment determines its final state.

For example, in the SQLPlus environment, if your PL/SQL block does not include a COMMIT or ROLLBACK statement, the final state of your transaction depends on what you do after running the block. If you execute a data definition, data control, or COMMIT statement or if you issue the EXIT, DISCONNECT, or QUIT command, Oracle commits the transaction. If you execute a ROLLBACK statement or abort the SQLPlus session, Oracle rolls back the transaction.

https://docs.oracle.com/cd/B19306_01/appdev.102/b14261/sqloperations.htm#i7105

importing go files in same folder

./main.go (in package main)
./a/a.go (in package a)
./a/b.go (in package a)

in this case:
main.go import "./a"

It can call the function in the a.go and b.go,that with first letter caps on.

how does unix handle full path name with space and arguments?

You can quote the entire path as in windows or you can escape the spaces like in:

/foo\ folder\ with\ space/foo.sh -help

Both ways will work!

How to find substring from string?

Use strstr(const char *s , const char *t) and include<string.h>

You can write your own function which behaves same as strstr and you can modify according to your requirement also

char * str_str(const char *s, const char *t)
{
int i, j, k;
for (i = 0; s[i] != '\0'; i++) 
{
for (j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++);
if (k > 0 && t[k] == '\0')
return (&s[i]);
}
return NULL;
}

How to fix libeay32.dll was not found error

Download libeay32.dll and ssleay32.dll binary package for 32Bit and 64Bit from http://indy.fulgan.com/SSL/ then put it into executable or System32 directory.

What are some great online database modeling tools?

You may want to look at IBExpert Personal Edition. While not open source, this is a very good tool for designing, building, and administering Firebird and InterBase databases.

The Personal Edition is free, but some of the more advanced features are not available. Still, even without the slick extras, the free version is very powerful.

No module named 'pymysql'

If even sudo apt-get install python3-pymysql does not work for you try this:

  • Go to the PyMySQL page and download the zip file.
  • Then, via the terminal, cd to your Downloads folder and extract the folder
  • cd into the newly extracted folder
  • Install the setup.py file with: sudo python3 setup.py install

Comparing two input values in a form validation with AngularJS

I need to do this just in one form in my entire application and i see a directive like a super complicate for my case, so i use the ng-patter like some has point, but have some problems, when the string has special characters like .[\ this broke, so i create a function for scape special characters.

$scope.escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

and in the view

<form name="ExampleForm">
  <label>Password</label>
  <input ng-model="password" required />
  <br>
   <label>Confirm password</label>
  <input ng-model="confirmPassword" required ng-pattern="escapeRegExp(password)"/>  
</form>

The target principal name is incorrect. Cannot generate SSPI context

Check your clock matches between the client and server.

When I had this error intermittently, none of the above answers worked, then we found the time had drifted on some of our servers, once they were synced again the error went away. Search for w32tm or NTP to see how to automatically sync the time on Windows.

UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?

Depends, Do you need the data to be loaded each time you open the view? or only once?

enter image description here

  • Red : They don't require to change every time. Once they are loaded they stay as how they were.
  • Purple: They need to change over time or after you load each time. You don't want to see the same 3 suggested users to follow, it needs to be reloaded every time you come back to the screen. Their photos may get updated... you don't want to see a photo from 5 years ago...

viewDidLoad: Whatever processing you have that needs to be done once.
viewWilLAppear: Whatever processing that needs to change every time the page is loaded.

Labels, icons, button titles or most dataInputedByDeveloper usually don't change. Names, photos, links, button status, lists (input Arrays for your tableViews or collectionView) or most dataInputedByUser usually do change.

How can I get an int from stdio in C?

The typical way is with scanf:

int input_value;

scanf("%d", &input_value);

In most cases, however, you want to check whether your attempt at reading input succeeded. scanf returns the number of items it successfully converted, so you typically want to compare the return value against the number of items you expected to read. In this case you're expecting to read one item, so:

if (scanf("%d", &input_value) == 1)
    // it succeeded
else
    // it failed

Of course, the same is true of all the scanf family (sscanf, fscanf and so on).

Right Align button in horizontal LinearLayout

try this one

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_gravity="right" 
    android:layout_height="wrap_content"             
    android:orientation="horizontal"  >

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
   android:layout_height="wrap_content"   
   android:orientation="horizontal" >

<TextView
    android:id="@+id/lblExpenseCancel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="9dp"
    android:text="cancel"
    android:textColor="#ffff0000"
    android:textSize="20sp" />

<Button
    android:id="@+id/btnAddExpense"
    android:layout_width="wrap_content"
    android:layout_height="45dp"
    android:layout_alignParentRight="true"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="15dp"
     android:textColor="#ff0000ff"
    android:text="add" />

 </RelativeLayout>
  </LinearLayout>

How to set opacity to the background color of a div?

I think rgba is the quickest and easiest!

background: rgba(225, 225, 225, .8)

In Javascript, how to conditionally add a member to an object?

i prefere, using code this it, you can run this code

const three = {
  three: 3
}

// you can active this code, if you use object `three is null`
//const three = {}

const number = {
  one: 1,
  two: 2,
  ...(!!three && three),
  four: 4
}

console.log(number);

Get data from file input in JQuery

You can try the FileReader API. Do something like this:

_x000D_
_x000D_
<!DOCTYPE html>
<html>
  <head>
    <script>        
      function handleFileSelect()
      {               
        if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
          alert('The File APIs are not fully supported in this browser.');
          return;
        }   
      
        var input = document.getElementById('fileinput');
        if (!input) {
          alert("Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
          alert("This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
          alert("Please select a file before clicking 'Load'");               
        }
        else {
          var file = input.files[0];
          var fr = new FileReader();
          fr.onload = receivedText;
          //fr.readAsText(file);
          //fr.readAsBinaryString(file); //as bit work with base64 for example upload to server
          fr.readAsDataURL(file);
        }
      }
      
      function receivedText() {
        document.getElementById('editor').appendChild(document.createTextNode(fr.result));
      }           
      
    </script>
  </head>
  <body>
    <input type="file" id="fileinput"/>
    <input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();' />
    <div id="editor"></div>
  </body>
</html>
_x000D_
_x000D_
_x000D_

How can I implement custom Action Bar with custom buttons in Android?

Please write following code in menu.xml file:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:my_menu_tutorial_app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="com.example.mymenus.menu_app.MainActivity">
<item android:id="@+id/item_one"
      android:icon="@drawable/menu_icon"
      android:orderInCategory="l01"
      android:title="Item One"
      my_menu_tutorial_app:showAsAction="always">
      <!--sub-menu-->
      <menu>
          <item android:id="@+id/sub_one"
                android:title="Sub-menu item one" />
          <item android:id="@+id/sub_two"
                android:title="Sub-menu item two" />
      </menu>

Also write this java code in activity class file:

public boolean onOptionsItemSelected(MenuItem item)
{
    super.onOptionsItemSelected(item);
    Toast.makeText(this, "Menus item selected: " +
        item.getTitle(), Toast.LENGTH_SHORT).show();
    switch (item.getItemId())
    {
        case R.id.sub_one:
            isItemOneSelected = true;
            supportInvalidateOptionsMenu();
            return true;
        case MENU_ITEM + 1:
            isRemoveItem = true;
            supportInvalidateOptionsMenu();
            return true;
        default:
            return false;
    }
}

This is the easiest way to display menus in action bar.

How to subtract hours from a date in Oracle so it affects the day also

you should divide hours by 24 not 11
like this:
select to_char(sysdate - 2/24, 'dd-mon-yyyy HH24') from dual

load json into variable

<input  class="pull-right" id="currSpecID" name="currSpecID" value="">

   $.get("http://localhost:8080/HIS_API/rest/MriSpecimen/getMaxSpecimenID", function(data, status){
       alert("Data: " + data + "\nStatus: " + status);
    $("#currSpecID").val(data);
    });

enter image description here enter image description here

cURL POST command line on WINDOWS RESTful service

We can use below Curl command in Windows Command prompt to send the request. Use the Curl command below, replace single quote with double quotes, remove quotes where they are not there in below format and use the ^ symbol.

curl http://localhost:7101/module/url ^
  -d @D:/request.xml ^
  -H "Content-Type: text/xml" ^
  -H "SOAPAction: process" ^
  -H "Authorization: Basic xyz" ^
  -X POST

Kendo grid date column not formatting

This might be helpful:

columns.Bound(date=> date.START_DATE).Title("Start Date").Format("{0:MM dd, yyyy}");

How to create a density plot in matplotlib?

Option 1:

Use pandas dataframe plot (built on top of matplotlib):

import pandas as pd
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
pd.DataFrame(data).plot(kind='density') # or pd.Series()

enter image description here

Option 2:

Use distplot of seaborn:

import seaborn as sns
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
sns.distplot(data, hist=False)

enter image description here

c# regex matches example

It looks like most of post here described what you need here. However - something you might need more complex behavior - depending on what you're parsing. In your case it might be so that you won't need more complex parsing - but it depends what information you're extracting.

You can use regex groups as field name in class, after which could be written for example like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;

public class Info
{
    public String Identifier;
    public char nextChar;
};

class testRegex {

    const string input = "Lorem ipsum dolor sit %download%#456 amet, consectetur adipiscing %download%#3434 elit. " +
    "Duis non nunc nec mauris feugiat porttitor. Sed tincidunt blandit dui a viverra%download%#298. Aenean dapibus nisl %download%#893434 id nibh auctor vel tempor velit blandit.";

    static void Main(string[] args)
    {
        Regex regex = new Regex(@"%download%#(?<Identifier>[0-9]*)(?<nextChar>.)(?<thisCharIsNotNeeded>.)");
        List<Info> infos = new List<Info>();

        foreach (Match match in regex.Matches(input))
        {
            Info info = new Info();
            for( int i = 1; i < regex.GetGroupNames().Length; i++ )
            {
                String groupName = regex.GetGroupNames()[i];

                FieldInfo fi = info.GetType().GetField(regex.GetGroupNames()[i]);

                if( fi != null ) // Field is non-public or does not exists.
                    fi.SetValue( info, Convert.ChangeType( match.Groups[groupName].Value, fi.FieldType));
            }
            infos.Add(info);
        }

        foreach ( var info in infos )
        {
            Console.WriteLine(info.Identifier + " followed by '" + info.nextChar.ToString() + "'");
        }
    }

};

This mechanism uses C# reflection to set value to class. group name is matched against field name in class instance. Please note that Convert.ChangeType won't accept any kind of garbage.

If you want to add tracking of line / column - you can add extra Regex split for lines, but in order to keep for loop intact - all match patterns must have named groups. (Otherwise column index will be calculated incorrectly)

This will results in following output:

456 followed by ' '
3434 followed by ' '
298 followed by '.'
893434 followed by ' '

'python3' is not recognized as an internal or external command, operable program or batch file

If python2 is not installed on your computer, you can try with just python instead of python3

How to access the services from RESTful API in my angularjs page?

The $http service can be used for general purpose AJAX. If you have a proper RESTful API, you should take a look at ngResource.

You might also take a look at Restangular, which is a third party library to handle REST APIs easy.

How do I clear the dropdownlist values on button click event using jQuery?

If you want to reset bootstrap page with button click using jQuery :

function resetForm(){
        var validator = $( "#form_ID" ).validate();
        validator.resetForm();
}

Using above code you also have change the field colour as red to normal.

If you want to reset only fielded value then :

$("#form_ID")[0].reset();

PostgreSQL query to list all table names?

Open up the postgres terminal with the databse you would like:

psql dbname (run this line in a terminal)

then, run this command in the postgres environment

\d

This will describe all tables by name. Basically a list of tables by name ascending.

Then you can try this to describe a table by fields:

\d tablename.

Hope this helps.

How to resolve "local edit, incoming delete upon update" message

So you can just revert the file that you deleted but remember, If you are working on any type of project with a set project file (like iOS), reverting the file will add it to your system folder structure but not your project file structure. additional steps may be required if you are in this case

Converting file size in bytes to human-readable string

Based on cocco's idea, here's a less compact -but hopefully more comprehensive- example.

<!DOCTYPE html>
<html>
<head>
<title>File info</title>

<script>
<!--
function fileSize(bytes) {
    var exp = Math.log(bytes) / Math.log(1024) | 0;
    var result = (bytes / Math.pow(1024, exp)).toFixed(2);

    return result + ' ' + (exp == 0 ? 'bytes': 'KMGTPEZY'[exp - 1] + 'B');
}

function info(input) {
    input.nextElementSibling.textContent = fileSize(input.files[0].size);
} 
-->
</script>
</head>

<body>
<label for="upload-file"> File: </label>
<input id="upload-file" type="file" onchange="info(this)">
<div></div>
</body>
</html> 

jQuery Change event on an <input> element - any way to retain previous value?

I created these functions based on Joey Guerra's suggestion, thank you for that. I'm elaborating a little bit, perhaps someone can use it. The first function checkDefaults() is called when an input changes, the second is called when the form is submitted using jQuery.post. div.updatesubmit is my submit button, and class 'needsupdate' is an indicator that an update is made but not yet submitted.

function checkDefaults() {
    var changed = false;
        jQuery('input').each(function(){
            if(this.defaultValue != this.value) {
                changed = true;
            }
        });
        if(changed === true) {
            jQuery('div.updatesubmit').addClass("needsupdate");
        } else {
            jQuery('div.updatesubmit').removeClass("needsupdate");
        }
}

function renewDefaults() {
        jQuery('input').each(function(){
            this.defaultValue = this.value;
        });
        jQuery('div.updatesubmit').removeClass("needsupdate");
}

How to create a Java / Maven project that works in Visual Studio Code?

An alternative way is to install the Maven for Java plugin and create a maven project within Visual Studio. The steps are described in the official documentation:

  1. From the Command Palette (Crtl+Shift+P), select Maven: Generate from Maven Archetype and follow the instructions, or
  2. Right-click on a folder and select Generate from Maven Archetype.

How to diff a commit with its parent?

Use:

git diff 15dc8^!

as described in the following fragment of git-rev-parse(1) manpage (or in modern git gitrevisions(7) manpage):

Two other shorthands for naming a set that is formed by a commit and its parent commits exist. The r1^@ notation means all parents of r1. r1^! includes commit r1 but excludes all of its parents.

This means that you can use 15dc8^! as a shorthand for 15dc8^..15dc8 anywhere in git where revisions are needed. For diff command the git diff 15dc8^..15dc8 is understood as git diff 15dc8^ 15dc8, which means the difference between parent of commit (15dc8^) and commit (15dc8).

Note: the description in git-rev-parse(1) manpage talks about revision ranges, where it needs to work also for merge commits, with more than one parent. Then r1^! is "r1 --not r1^@" i.e. "r1 ^r1^1 ^r1^2 ..."


Also, you can use git show COMMIT to get commit description and diff for a commit. If you want only diff, you can use git diff-tree -p COMMIT

Remove part of string after "."

You just need to escape the period:

a <- c("NM_020506.1","NM_020519.1","NM_001030297.2","NM_010281.2","NM_011419.3", "NM_053155.2")

gsub("\\..*","",a)
[1] "NM_020506"    "NM_020519"    "NM_001030297" "NM_010281"    "NM_011419"    "NM_053155" 

How can I do factory reset using adb in android?

You can send intent MASTER_CLEAR in adb:

adb shell am broadcast -a android.intent.action.MASTER_CLEAR

or as root

adb shell  "su -c 'am broadcast -a android.intent.action.MASTER_CLEAR'"

XSS filtering function in PHP

function clean($data){
    $data = rawurldecode($data);
    return filter_var($data, FILTER_SANITIZE_SPEC_CHARS);
}

How to execute a query in ms-access in VBA code?

How about something like this...

Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")

Do While Not rs.EOF
   Debug.Print rs("PictureLocation") & " - " & rs("ID")
   rs.MoveNext
Loop

python: how to identify if a variable is an array or a scalar

Here is the best approach I have found: Check existence of __len__ and __getitem__.

You may ask why? The reasons includes:

  1. The popular method isinstance(obj, abc.Sequence) fails on some objects including PyTorch's Tensor because they do not implement __contains__.
  2. Unfortunately, there is nothing in Python's collections.abc that checks for only __len__ and __getitem__ which I feel are minimal methods for array-like objects.
  3. It works on list, tuple, ndarray, Tensor etc.

So without further ado:

def is_array_like(obj, string_is_array=False, tuple_is_array=True):
    result = hasattr(obj, "__len__") and hasattr(obj, '__getitem__') 
    if result and not string_is_array and isinstance(obj, (str, abc.ByteString)):
        result = False
    if result and not tuple_is_array and isinstance(obj, tuple):
        result = False
    return result

Note that I've added default parameters because most of the time you might want to consider strings as values, not arrays. Similarly for tuples.

Hide Show content-list with only CSS, no javascript used

I know it's an old post but what about this solution (I've made a JSFiddle to illustrate it)... Solution that uses the :after pseudo elements of <span> to show/hide the <span> switch link itself (in addition to the .alert message it must show/hide). When the pseudo element loses it's focus, the message is hidden.

The initial situation is a hidden message that appears when the <span> with the :after content : "Show Me"; is focused. When this <span> is focused, it's :after content becomes empty while the :after content of the second <span> (that was initially empty) turns to "Hide Me". So, when you click this second <span> the first one loses it's focus and the situation comes back to it's initial state.

I started on the solution offered by @Vector I kept the DOM'situation presented ky @Frederic Kizar

HTML:

<span class="span3" tabindex="0"></span>
<span class="span2" tabindex="0"></span>
<p class="alert" >Some message to show here</p>

CSS:

body {
    display: inline-block;
}
.span3 ~ .span2:after{
    content:"";
}
.span3:focus ~ .alert  {
    display:block;
}
.span3:focus ~ .span2:after  {
    content:"Hide Me";
}
.span3:after  {
    content: "Show Me";
}
.span3:focus:after  {
    content: "";
}
.alert  {
    display:none;
}

Batch file to run a command in cmd within a directory

Mine DID execute commands in order. Here's my version of what I was using it for:

START cmd.exe /k "U: & cd U:\Design_stuff\new_lcso_website_2017 & python -m http.server"

I needed to

  1. Change to my U drive
  2. CD to a specific folder containing a website I'm redesigning
  3. Execute python with the http server module (to display the contents in my browser).

If those commands are out of order, it would not display the correct files. I initially forgot to change to U: and, running the batch file on my Desktop, it created a web page in my browser at http://localhost:8000 showing me the contents of my Desktop instead of the folder I wanted.

Can I have H2 autocreate a schema in an in-memory database?

If you are using Spring Framework with application.yml and having trouble to make the test find the SQL file on the INIT property, you can use the classpath: notation.

For example, if you have a init.sql SQL file on the src/test/resources, just use:

url=jdbc:h2:~/test;INIT=RUNSCRIPT FROM 'classpath:init.sql';DB_CLOSE_DELAY=-1;

Reorder / reset auto increment primary key

My opinion is to create a new column called row_order. then reorder that column. I'm not accepting the changes to the primary key. As an example, if the order column is banner_position, I have done something like this, This is for deleting, updating, creating of banner position column. Call this function reorder them respectively.

public function updatePositions(){
    $offers = Offer::select('banner_position')->orderBy('banner_position')->get();
    $offersCount = Offer::max('banner_position');
    $range = range(1, $offersCount);

    $existingBannerPositions = [];
    foreach($offers as $offer){
        $existingBannerPositions[] = $offer->banner_position;
    }
    sort($existingBannerPositions);
    foreach($existingBannerPositions as $key => $position){
        $numbersLessThanPosition = range(1,$position);
        $freshNumbersLessThanPosition = array_diff($numbersLessThanPosition, $existingBannerPositions);
        if(count($freshNumbersLessThanPosition)>0) {
            $existingBannerPositions[$key] = current($freshNumbersLessThanPosition);
            Offer::where('banner_position',$position)->update(array('banner_position'=> current($freshNumbersLessThanPosition)));
        }
    }
}

How do I count columns of a table

$cs = mysql_query("describe tbl_info");
$column_count = mysql_num_rows($cs);

Or just:

$column_count = mysql_num_rows(mysql_query("describe tbl_info"));

How to make inactive content inside a div?

div[disabled]
{
  pointer-events: none;
  opacity: 0.7;
}

The above code makes the contents of the div disabled. You can make div disabled by adding disabled attribute.

<div disabled>
  /* Contents */
</div>

Cannot connect to local SQL Server with Management Studio

Open Sql server 2014 Configuration Manager.

Click Sql server services and start the sql server service if it is stopped

Then click Check SQL server Network Configuration for TCP/IP Enabled

then restart the sql server management studio (SSMS) and connect your local database engine

converting numbers in to words C#

When I had to solve this problem, I created a hard-coded data dictionary to map between numbers and their associated words. For example, the following might represent a few entries in the dictionary:

{1, "one"}
{2, "two"}
{30, "thirty"}

You really only need to worry about mapping numbers in the 10^0 (1,2,3, etc.) and 10^1 (10,20,30) positions because once you get to 100, you simply have to know when to use words like hundred, thousand, million, etc. in combination with your map. For example, when you have a number like 3,240,123, you get: three million two hundred forty thousand one hundred twenty three.

After you build your map, you need to work through each digit in your number and figure out the appropriate nomenclature to go with it.

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

I got the same error, I'm using laravel 5.4 with webpack, here package.json before:

{
  ...
  ...
  "devDependencies": {
    "jquery": "^1.12.4",
    ...
    ...
  },
  "dependencies": {
    "datatables.net": "^2.1.1",
    ...
    ...
  }
}

I had to move jquery and datatables.net npm packages under one of these "dependencies": {} or "devDependencies": {} in package.json and the error disappeared, after:

{
  ...
  ...
  "devDependencies": {
    "jquery": "^1.12.4",
    "datatables.net": "^2.1.1",
    ...
    ...
  }
}

I hope that helps!

yii2 hidden input value

you can also do this

$model->hidden1 = 'your value';// better put it on controller
$form->field($model, 'hidden1')->hiddenInput()->label(false);

this is a better option if you set value on controller

$model = new SomeModelName();

if ($model->load(Yii::$app->request->post()) && $model->save()) {
    return $this->redirect(['view', 'id' => $model->group_id]);
 } else {
    $model->hidden1 = 'your value';
    return $this->render('create', [
        'model' => $model,
    ]);
 }

JavaScript load a page on button click

Don't abuse form elements where <a> elements will suffice.

<style>
    /* or put this in your stylesheet */

    .button {
        display: inline-block;
        padding: 3px 5px;
        border: 1px solid #000;
        background: #eee;
    }

</style>

<!-- instead of abusing a button or input element -->
<a href="url" class="button">text</a>

Applying styles to tables with Twitter Bootstrap

Just another good looking table. I added "table-hover" class because it gives a nice hovering effect.

   <h3>NATO Phonetic Alphabet</h3>    
   <table class="table table-striped table-bordered table-condensed table-hover">
   <thead>
    <tr> 
        <th>Letter</th>
        <th>Phonetic Letter</th>

    </tr>
    </thead>
  <tr>
    <th>A</th>
    <th>Alpha</th>

  </tr>
  <tr>
    <td>B</td>
    <td>Bravo</td>

  </tr>
  <tr>
    <td>C</td>
    <td>Charlie</td>

  </tr>

</table>

Angularjs - simple form submit

I have been doing quite a bit of research and in attempt to resolve a different issue I ended up coming to a good portion of the solution in my other post here:

Angularjs - Form Post Data Not Posted?

The solution does not include uploading images currently but I intend to expand upon and create a clear and well working example. If updating these posts is possible I will keep them up to date all the way until a stable and easy to learn from example is compiled.

Android Pop-up message

Use This And Call This In OnCreate Method In Which Activity You Want

public void popupMessage(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("No Internet Connection. Check Your Wifi Or enter code hereMobile Data.");
        alertDialogBuilder.setIcon(R.drawable.ic_no_internet);
        alertDialogBuilder.setTitle("Connection Failed");
        alertDialogBuilder.setNegativeButton("ok", new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Log.d("internet","Ok btn pressed");
                finishAffinity();
                System.exit(0);
            }
        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

Function to get yesterday's date in Javascript in format DD/MM/YYYY

The problem here seems to be that you're reassigning $today by assigning a string to it:

$today = $dd+'/'+$mm+'/'+$yyyy;

Strings don't have getDate.

Also, $today.getDate()-1 just gives you the day of the month minus one; it doesn't give you the full date of 'yesterday'. Try this:

$today = new Date();
$yesterday = new Date($today);
$yesterday.setDate($today.getDate() - 1); //setDate also supports negative values, which cause the month to rollover.

Then just apply the formatting code you wrote:

var $dd = $yesterday.getDate();
var $mm = $yesterday.getMonth()+1; //January is 0!

var $yyyy = $yesterday.getFullYear();
if($dd<10){$dd='0'+$dd} if($mm<10){$mm='0'+$mm} $yesterday = $dd+'/'+$mm+'/'+$yyyy;

Because of the last statement, $yesterday is now a String (not a Date) containing the formatted date.

Convert SVG to image (JPEG, PNG, etc.) in the browser

I recently discovered a couple of image tracing libraries for JavaScript that indeed are able to build an acceptable approximation to the bitmap, both size and quality. I'm developing this JavaScript library and CLI :

https://www.npmjs.com/package/svg-png-converter

Which provides unified API for all of them, supporting browser and node, non depending on DOM, and a Command line tool.

For converting logos/cartoon/like images it does excellent job. For photos / realism some tweaking is needed since the output size can grow a lot.

It has a playground although right now I'm working on a better one, easier to use, since more features has been added:

https://cancerberosgx.github.io/demos/svg-png-converter/playground/#

How do I put hint in a asp:textbox

The placeholder attribute

You're looking for the placeholder attribute. Use it like any other attribute inside your ASP.net control:

<asp:textbox id="txtWithHint" placeholder="hint" runat="server"/>

Don't bother about your IDE (i.e. Visual Studio) maybe not knowing the attribute. Attributes which are not registered with ASP.net are passed through and rendered as is. So the above code (basically) renders to:

<input type="text" placeholder="hint"/>

Using placeholder in resources

A fine way of applying the hint to the control is using resources. This way you may have localized hints. Let's say you have an index.aspx file, your App_LocalResources/index.aspx.resx file contains

<data name="WithHint.placeholder">
    <value>hint</value>
</data>

and your control looks like

<asp:textbox id="txtWithHint" meta:resourcekey="WithHint" runat="server"/>

the rendered result will look the same as the one in the chapter above.

Add attribute in code behind

Like any other attribute you can add the placeholder to the AttributeCollection:

txtWithHint.Attributes.Add("placeholder", "hint");

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

Log.INFO vs. Log.DEBUG

I usually try to use it like this:

  • DEBUG: Information interesting for Developers, when trying to debug a problem.
  • INFO: Information interesting for Support staff trying to figure out the context of a given error
  • WARN to FATAL: Problems and Errors depending on level of damage.

MySQL Daemon Failed to Start - centos 6

You may need free up some space from root (/) partition. Stop mysql process by:

/etc/init.d/mysql stop

Delete an unused database from mySql by command:

rm -rf [Database-Directory]

Execute it in /var/lib/mysql. Now if you run df -h, you may confused by still full space. For removing the unused database 's directory to be affected, you need to kill processes are using current directory/partition.

Stopping mysql_safe or mysqld_safe and then mysqld:

ps -A

Then find mysql's process number (e.g. 2234). Then execute:

kill 2234

Now start again mysql:

/etc/init.d/mysql start

C++ Convert string (or char*) to wstring (or wchar_t*)

use this code to convert your string to wstring

std::wstring string2wString(const std::string& s){
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); 
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;
}

int main(){
    std::wstring str="your string";
    std::wstring wStr=string2wString(str);
    return 0;
}

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

How to convert a Map to List in Java?

"Map<String , String > map = new HapshMap<String , String>;
 map.add("one","java");
 map.add("two" ,"spring");
 Set<Entry<String,String>> set =  map.entrySet();
 List<Entry<String , String>> list = new ArrayList<Entry<String , String>>    (set);
 for(Entry<String , String> entry : list ) {
   System.out.println(entry.getKey());
   System.out.println(entry.getValue());
 } "

How do I view the full content of a text or varchar(MAX) column in SQL Server 2008 Management Studio?

One work-around is to right-click on the result set and select "Save Results As...". This exports it to a CSV file with the entire contents of the column. Not perfect but worked well enough for me.

Workaround

How to search in an array with preg_match?

$haystack = array (
   'say hello',
   'hello stackoverflow',
   'hello world',
   'foo bar bas'
);

$matches  = preg_grep('/hello/i', $haystack);

print_r($matches);

Output

Array
(
    [1] => say hello
    [2] => hello stackoverflow
    [3] => hello world
)

apc vs eaccelerator vs xcache

Check out benchmarks and comparisons:

here and here and there

How do I find out what keystore my JVM is using?

We encountered this issue on a Tomcat running from a jre directory that was (almost fully) removed after an automatic jre update, so that the running jre could no longer find jre.../lib/security/cacerts because it no longer existed.

Restarting Tomcat (after changing the configuration to run from the different jre location) fixed the problem.

if A vs if A is not None:

Most guides I've seen suggest that you should use

if A:

unless you have a reason to be more specific.

There are some slight differences. There are values other than None that return False, for example empty lists, or 0, so have a think about what it is you're really testing for.

How to pass boolean values to a PowerShell script from a command prompt

This is an older question, but there is actually an answer to this in the PowerShell documentation. I had the same problem, and for once RTFM actually solved it. Almost.

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe

Documentation for the -File parameter states that "In rare cases, you might need to provide a Boolean value for a switch parameter. To provide a Boolean value for a switch parameter in the value of the File parameter, enclose the parameter name and value in curly braces, such as the following: -File .\Get-Script.ps1 {-All:$False}"

I had to write it like this:

PowerShell.Exe -File MyFile.ps1 {-SomeBoolParameter:False}

So no '$' before the true/false statement, and that worked for me, on PowerShell 4.0

Converting rows into columns and columns into rows using R

Simply use the base transpose function t, wrapped with as.data.frame:

final_df <- as.data.frame(t(starting_df))
final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Above updated. As docendo discimus pointed out, t returns a matrix. As Mark suggested wrapping it with as.data.frame gets back a data frame instead of a matrix. Thanks!

Return a string method in C#

You're currently trying to access a method like a property

Console.WriteLine("{0}",x.fullNameMethod);

It should be

Console.WriteLine("{0}",x.fullNameMethod());

Alternatively you could turn it into a property using

public string fullName
{
   get
   {
        string x = firstName + " " + lastName;
        return x;
   }
}

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

I can't believe that in all this time, no one has mentioned:

sudo lshw -class cpu

to get details about the speed, quantity, size and capabilities of the CPU hardware.

How to open the command prompt and insert commands using Java?

public static void main(String[] args) {
    try {
        String ss = null;
        Process p = Runtime.getRuntime().exec("cmd.exe /c start dir ");
        BufferedWriter writeer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
        writeer.write("dir");
        writeer.flush();
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        System.out.println("Here is the standard output of the command:\n");
        while ((ss = stdInput.readLine()) != null) {
            System.out.println(ss);
        }
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((ss = stdError.readLine()) != null) {
            System.out.println(ss);
        }

    } catch (IOException e) {
        System.out.println("FROM CATCH" + e.toString());
    }

}

MySQL Error: #1142 - SELECT command denied to user

So the issue I ran into was this... the application I used to grant the permissions converted the Schema.TableName into a single DB statement in the wrong table, so the grant was indeed wrong, but looked correct when we did a SHOW GRANTS FOR UserName if you weren't paying very close attention to GRANT SELECT vs GRANT TABLE SELECT. Manually correcting the Grant Select on Table w/ proper escaping of Schema.Table solved my issue.

May be unrelated, but I can imagine if one client does this wrong, another might too.

Hope that's helpful.

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

pyinstaller myscript.py

You can find more information about how to use Pyinstaller and customize the build process via the documentation.


You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

What is "406-Not Acceptable Response" in HTTP?

You can also receive a 406 response when invalid cookies are stored or referenced in the browser - for example, when running a Rails server in Dev mode locally.

If you happened to run two different projects on the same port, the browser might reference a cookie from a different localhost session.

This has happened to me...tripped me up for a minute. Looking in browser > Developer Mode > Network showed it.

Counting the number of elements with the values of x in a vector

numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435 453,435,324,34,456,56,567,65,34,435)

> length(grep(435, numbers))
[1] 3


> length(which(435 == numbers))
[1] 3


> require(plyr)
> df = count(numbers)
> df[df$x == 435, ] 
     x freq
11 435    3


> sum(435 == numbers)
[1] 3


> sum(grepl(435, numbers))
[1] 3


> sum(435 == numbers)
[1] 3


> tabulate(numbers)[435]
[1] 3


> table(numbers)['435']
435 
  3 


> length(subset(numbers, numbers=='435')) 
[1] 3

Error in Eclipse: "The project cannot be built until build path errors are resolved"

If you can't find the build path error, sometimes menu Project ? Clean... works like a charm.

How to pass value from <option><select> to form action

instead of trying to catch both POST and GET responses - you can have everything you want in the POST.

Your code:

<form method="POST" action="index.php?action=contact_agent&agent_id=">
  <select>
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
</form>

can easily become:

<form method="POST" action="index.php">
  <input type="hidden" name="action" value="contact_agent">
  <select name="agent_id">
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
  <button type="submit">Submit POST Data</button>
</form>

then in index.php - these values will be populated

$_POST['action'] // "contact_agent"
$_POST['agent_id'] // 1, 2 or 3 based on selection in form... 

Svn switch from trunk to branch

In my case, I wanted to check out a new branch that has cut recently but it's it big in size and I want to save time and internet bandwidth, as I'm in a slow metered network

so I copped the previous branch that I already checked in

I went to the working directory, and from svn info, I can see it's on the previous branch I did the following command (you can find this command from svn switch --help)

svn switch ^/branches/newBranchName

go check svn info again you can see it is becoming the newBranchName go ahead and svn up

and this how I got the new branch easily, quickly with minimum data transmitting over the internet

hope sharing my case helps and speeds up your work

How to clear all <div>sā€™ contents inside a parent <div>?

$("#masterdiv div[id^='childdiv']").each(function(el){$(el).empty();});

or

$("#masterdiv").find("div[id^='childdiv']").each(function(el){$(el).empty();});

Rounding float in Ruby

For ruby 1.8.7 you could add the following to your code:

class Float
    alias oldround:round
    def round(precision = nil)
        if precision.nil?
            return self
        else
            return ((self * 10**precision).oldround.to_f) / (10**precision)
        end 
    end 
end

Order data frame rows according to vector with specific order

I prefer to use ***_join in dplyr whenever I need to match data. One possible try for this

left_join(data.frame(name=target),df,by="name")

Note that the input for ***_join require tbls or data.frame

Resize command prompt through commands

Most people will tell you to run this command:

mode con:cols=80 lines=100

but you should just try typing:

MODE 1000

as a line in your batch file or cmd prompt.

How to add SHA-1 to android application

MacOS just paste in the Terminal:

keytool -list -v -alias androiddebugkey -keystore ~/.android/debug.keystore -storepass android -keypass android

A fast way to delete all rows of a datatable at once

That's the easiest way to delete all rows from the table in dbms via DataAdapter. But if you want to do it in one batch, you can set the DataAdapter's UpdateBatchSize to 0(unlimited).

Another way would be to use a simple SqlCommand with CommandText DELETE FROM Table:

using(var con = new SqlConnection(ConfigurationSettings.AppSettings["con"]))
using(var cmd = new SqlCommand())
{
    cmd.CommandText = "DELETE FROM Table";
    cmd.Connection = con;
    con.Open();
    int numberDeleted = cmd.ExecuteNonQuery();  // all rows deleted
}

But if you instead only want to remove the DataRows from the DataTable, you just have to call DataTable.Clear. That would prevent any rows from being deleted in dbms.

C/C++ Struct vs Class

C++ uses structs primarily for 1) backwards compatibility with C and 2) POD types. C structs do not have methods, inheritance or visibility.

Eclipse: Java was started but returned error code=13

I also faced the error code when i upgraded my java version to 1.8. The problem was with my eclipse.

My jdk which was installed on my system is of 32 - bit and my eclipse was of 64 - bit.

So solve this problem i downloaded the 32 - bit eclipse.

IMO this Architecture miss match problem

Plese match your architecture type of JDK and eclipse.

Loop through childNodes

Try with for loop. It gives error in forEach because it is a collection of nodes nodelist.

Or this should convert node-list to array

function toArray(obj) {
  var array = [];
  for (var i = 0; i < obj.length; i++) { 
    array[i] = obj[i];
  }
return array;
}

Or you can use this

var array = Array.prototype.slice.call(obj);

PHP call Class method / function

You need to create Object for the class.

$obj = new Functions();
$var = $obj->filter($_GET['params']);

Add two textbox values and display the sum in a third textbox automatically

In below code i have done operation of sum and subtraction: because of using JavaScript if you want to call function, then you have to put your below code outside of document.ready(function{ }); and outside the script end tag.

I have taken one another script tag for this operation.And put below code between script starting tag // your code // script ending tag.

 function operation() 

 {

   var txtFirstNumberValue = parseInt(document.getElementById('basic').value);
   var txtSecondNumberValue =parseInt(document.getElementById('hra').value);
   var txtThirdNumberValue =parseInt(document.getElementById('transport').value);
   var txtFourthNumberValue =parseInt(document.getElementById('pt').value);
   var txtFiveNumberValue = parseInt(document.getElementById('pf').value);

   if (txtFirstNumberValue == "")
       txtFirstNumberValue = 0;
   if (txtSecondNumberValue == "")
       txtSecondNumberValue = 0;
   if (txtThirdNumberValue == "")
       txtThirdNumberValue = 0;
   if (txtFourthNumberValue == "")
       txtFourthNumberValue = 0;
   if (txtFiveNumberValue == "")
       txtFiveNumberValue = 0;



   var result = ((txtFirstNumberValue + txtSecondNumberValue + 
  txtThirdNumberValue) - (txtFourthNumberValue + txtFiveNumberValue));
   if (!isNaN(result)) {
       document.getElementById('total').value = result;
   }
 }

And put onkeyup="operation();" inside all 5 textboxes in your html form. This code running in both Firefox and Chrome.

Response to preflight request doesn't pass access control check

For python flask server, you can use the flask-cors plugin to enable cross domain requests.

See : https://flask-cors.readthedocs.io/en/latest/

Calculate execution time of a SQL query?

Why are you doing it in SQL? Admittedly that does show a "true" query time as opposed to the query time + time taken to shuffle data each way across the network, but it's polluting your database code. I doubt that your users will care - in fact, they'd probably rather include the network time, as it all contributes to the time taken for them to see the page.

Why not do the timing in your web application code? Aside from anything else, that means that for cases where you don't want to do any timing, but you want to execute the same proc, you don't need to mess around with something you don't need.

What is the 'dynamic' type in C# 4.0 used for?

An example of use :

You consume many classes that have a commun property 'CreationDate' :

public class Contact
{
    // some properties

    public DateTime CreationDate { get; set; }        
}

public class Company
{
    // some properties

    public DateTime CreationDate { get; set; }

}

public class Opportunity
{
    // some properties

    public DateTime CreationDate { get; set; }

}

If you write a commun method that retrieves the value of the 'CreationDate' Property, you'd have to use reflection:

    static DateTime RetrieveValueOfCreationDate(Object item)
    {
        return (DateTime)item.GetType().GetProperty("CreationDate").GetValue(item);
    }

With the 'dynamic' concept, your code is much more elegant :

    static DateTime RetrieveValueOfCreationDate(dynamic item)
    {
        return item.CreationDate;
    }

How can I determine if a date is between two dates in Java?

This might be a bit more readable:

Date min, max;   // assume these are set to something
Date d;          // the date in question

return d.after(min) && d.before(max);

How to iterate through range of Dates in Java?

You can try this:

OffsetDateTime currentDateTime = OffsetDateTime.now();
for (OffsetDateTime date = currentDateTime; date.isAfter(currentDateTime.minusYears(YEARS)); date = date.minusWeeks(1))
{
    ...
}

jQuery .each() index?

From the jQuery.each() documentation:

.each( function(index, Element) )
    function(index, Element)A function to execute for each matched element.

So you'll want to use:

$('#list option').each(function(i,e){
    //do stuff
});

...where index will be the index and element will be the option element in list

CSS transition when class removed

CSS transitions work by defining two states for the object using CSS. In your case, you define how the object looks when it has the class "saved" and you define how it looks when it doesn't have the class "saved" (it's normal look). When you remove the class "saved", it will transition to the other state according to the transition settings in place for the object without the "saved" class.

If the CSS transition settings apply to the object (without the "saved" class), then they will apply to both transitions.

We could help more specifically if you included all relevant CSS you're using to with the HTML you've provided.

My guess from looking at your HTML is that your transition CSS settings only apply to .saved and thus when you remove it, there are no controls to specify a CSS setting. You may want to add another class ".fade" that you leave on the object all the time and you can specify your CSS transition settings on that class so they are always in effect.

Pythonic way to print list items

OP's question is: does something like following exists, if not then why

print(p) for p in myList # doesn't work, OP's intuition

answer is, it does exist which is:

[p for p in myList] #works perfectly

Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this

How to run two jQuery animations simultaneously?

yes there is!

$(function () {
    $("#first").animate({
       width: '200px'
    }, { duration: 200, queue: false });

    $("#second").animate({
       width: '600px'
    }, { duration: 200, queue: false });
});

dyld: Library not loaded ... Reason: Image not found

Find all the boost libraries:

$ otool -L exefile
exefile:
        @executable_path/libboost_something.dylib (compatibility version 0.7.0, current version 0.7.0)
        /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 65.1.0)
        /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 169.3.0)

and for each libboost_xxx.dylib, do:

$ install_name_tool -change @executable_path/libboost_something.dylib /opt/local/lib/libboost_something.dylib exefile

and finally verify using otool again:

$ otool -L exefile
exefile:
        /opt/local/lib/libboost_something.dylib (compatibility version 0.7.0, current version 0.7.0)
        /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 65.1.0)
        /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 169.3.0)

Manpages: otool install_name_tool

EDIT A while back I wrote a python script (copy_dylibs.py) to work out all this stuff automatically when building an app. It will package up all libraries from /usr/local or /opt/local into the app bundle and fix references to those libraries to use @rpath. This means you can easily install third-party library using Homebrew and package them just as easily.

I have now made this script public on github.

Fit Image into PictureBox

Use the following lines of codes and you will find the solution...

pictureBox1.ImageLocation = @"C:\Users\Desktop\mypicture.jpg";
pictureBox1.SizeMode =PictureBoxSizeMode.StretchImage;

Why are you not able to declare a class as static in Java?

Everything we code in java goes into a class. Whenever we run a class JVM instantiates an object. JVM can create a number of objects, by definition Static means you have the same set of copy to all objects.

So, if Java would have allowed the top class to be static whenever you run a program it creates an Object and keeps overriding on to the same Memory Location.

If You are just replacing the object every time you run it whats the point of creating it?

So that is the reason Java got rid of the static for top-Level Class.

There might be more concrete reasons but this made much logical sense to me.

How do I get sed to read from standard input?

use the --expression option

grep searchterm myfile.csv | sed --expression='s/replaceme/withthis/g'

SQL Server find and replace specific word in all rows of specific column

You can also export the database and then use a program like notepad++ to replace words and then inmport aigain.

How to create a HashMap with two keys (Key-Pair, Value)?

Use a Pair as keys for the HashMap. JDK has no Pair, but you can either use a 3rd party libraray such as http://commons.apache.org/lang or write a Pair taype of your own.

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

There's a huge difference. As has been mentioned, <%@ include is a static include, <jsp:include is a dynamic include. Think of it as a difference between a macro and a function call (if you are familiar with those terms). Another way of putting it, a static include is exactly the same thing as copy-pasting the exact content of the included file (the "code") at the location of the <%@ include statement (which is exactly what the JSP compiler will do.

A dynamic include will make a request (using the request dispatcher) that will execute the indicated page and then include the output from the page in the output of the calling page, in place of the <jsp:include statement.

The big difference here is that with a dynamic include, the included page will execute in it's own pageContext. And since it's a request, you can send parameters to the page the same way you can send parameters along with any other request. A static include, on the other hand, is just a piece of code that will execute inside the context of the calling page. If you statically include the same file more than once, the code in that file will exist in multiple locations on the calling page so something like

<%
int i = 0;
%>

would generate a compiler error (since the same variable can't be declared more than once).

How do you get a query string on Flask?

We can do this by using request.query_string.

Example:

Lets consider view.py

from my_script import get_url_params

@app.route('/web_url/', methods=('get', 'post'))
def get_url_params_index():
    return Response(get_url_params())

You also make it more modular by using Flask Blueprints - https://flask.palletsprojects.com/en/1.1.x/blueprints/

Lets consider first name is being passed as a part of query string /web_url/?first_name=john

## here is my_script.py

## import required flask packages
from flask import request
def get_url_params():
    ## you might further need to format the URL params through escape.    
    firstName = request.args.get('first_name') 
    return firstName
    

As you see this is just a small example - you can fetch multiple values + formate those and use it or pass it onto the template file.

Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4

I use intelliJ and finally I created my own settings.xml and added the following content structure to it. In my project's pom.xml, the nexus repositories were defined but for some reason it was always hitting the external apache maven repo which is blocked in my company.

<settings>
  <mirrors>
     <id>nexus</id>
     <url>nexusURL </url>
     <mirrorOf>central</mirrorOf>
    <mirror>

<profiles>
  <profile>
    <repositories>
      <repository>

</settings>

keyCode values for numeric keypad?

To add to some of the other answers, note that:

  • keyup and keydown differ from keypress
  • if you want to use String.fromCharCode() to get the actual digit from keyup, you'll need to first normalize the keyCode.

Below is a self-documenting example that determines if the key is numeric, along with which number it is (example uses the range function from lodash).

const isKeypad = range(96, 106).includes(keyCode);
const normalizedKeyCode = isKeypad ? keyCode - 48 : keyCode;
const isDigit = range(48, 58).includes(normalizedKeyCode);
const digit = String.fromCharCode(normalizedKeyCode);

Difference between links and depends_on in docker_compose.yml

The post needs an update after the links option is deprecated.

Basically, links is no longer needed because its main purpose, making container reachable by another by adding environment variable, is included implicitly with network. When containers are placed in the same network, they are reachable by each other using their container name and other alias as host.

For docker run, --link is also deprecated and should be replaced by a custom network.

docker network create mynet
docker run -d --net mynet --name container1 my_image
docker run -it --net mynet --name container1 another_image

depends_on expresses start order (and implicitly image pulling order), which was a good side effect of links.

Get RETURN value from stored procedure in SQL

Assign after the EXEC token:

DECLARE @returnValue INT

EXEC @returnValue = SP_One

Binding a Button's visibility to a bool value in ViewModel

This can be achieved in a very simple way 1. Write this in the view.

<Button HorizontalAlignment="Center" VerticalAlignment="Center" Width="50" Height="30">
<Button.Style>
        <Style TargetType="Button">
                <Setter Property="Visibility" Value="Collapsed"/>
                        <Style.Triggers>
                                <DataTrigger Binding="{Binding IsHide}" Value="True">
                                        <Setter Property="Visibility" Value="Visible"/>
                                    </DataTrigger>
                            </Style.Triggers>
            </Style>
    </Button.Style>

  1. The following is the Boolean property which holds the true/ false value. The following is the code snippet. In my example this property is in UserNote class.

    public bool _isHide = false;
    
    public bool IsHide
    {
    
    get { return _isHide; }
    
    set
        {
            _isHide = value;
                OnPropertyChanged("IsHide");
        }
    } 
    
  2. This is the way the IsHide property gets the value.

    userNote.IsHide = userNote.IsNoteDeleted;
    

How to round up a number to nearest 10?

Hey i modify Kenny answer and custom it not always round function now it can be ceil and floor function

function roundToTheNearestAnything($value, $roundTo,$type='round')
    {
        $mod = $value%$roundTo;
        if($type=='round'){
            return $value+($mod<($roundTo/2)?-$mod:$roundTo-$mod);
        }elseif($type=='floor'){
            return $value+($mod<($roundTo/2)?-$mod:-$mod);
        }elseif($type=='ceil'){
            return $value+($mod<($roundTo/2)?$roundTo-$mod:$roundTo-$mod);
        }

    }

echo roundToTheNearestAnything(1872,25,'floor'); // 1850<br>
echo roundToTheNearestAnything(1872,25,'ceil'); // 1875<br>
echo roundToTheNearestAnything(1872,25,'round'); // 1875

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

After 7 years... the facelets solution still works fine for me as a jsf user

include the namespace as xmlns:fn="http://java.sun.com/jsp/jstl/functions"

and use the EL as #{fn:length(myBean.someList)} for example if using in jsf ui:fragment below example works fine

<ui:fragment rendered="#{fn:length(myBean.someList) gt 0}">
    <!-- Do something here-->
</ui:fragment>

How to hide a column (GridView) but still access its value?

When I want access some value from GridView before GridView was appears.

  1. I have a BoundField and bind DataField nomally.
  2. In RowDataBound event, I do some process in that event.
  3. Before GridView was appears I write this:

    protected void GridviewLecturer_PreRender(object sender, EventArgs e) 
    {
        GridviewLecturer.Columns[0].Visible = false;
    }
    

What are the JavaScript KeyCodes?

I needed something like this for a game's control configuration UI, so I compiled a list for the standard US keyboard layout keycodes and mapped them to their respective key names.

Here's a fiddle that contains a map for code -> name and visi versa: http://jsfiddle.net/vWx8V/

If you want to support other key layouts you'll need to modify these maps to accommodate for them separately.

That is unless you were looking for a list of keycode values that included the control characters and other special values that are not (or are rarely) possible to input using a keyboard and may be outside of the scope of the keydown/keypress/keyup events of Javascript. Many of them are control characters or special characters like null (\0) and you most likely won't need them.

Notice that the number of keys on a full keyboard is less than many of the keycode values.

How do I explicitly specify a Model's table-name mapping in Rails?

Rails >= 3.2 (including Rails 4+ and 5+):

class Countries < ActiveRecord::Base
  self.table_name = "cc"
end

Rails <= 3.1:

class Countries < ActiveRecord::Base
  self.set_table_name "cc"
  ...
end

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

In my case, the program was running fine, but after one day, I just ran into this problem without doing anything...

The solution was to manually add 'Main' as the Entry Point (before editing, the area was empty):

enter image description here

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

Try this in a Thread (not the UI-Thread):

final CountDownLatch latch = new CountDownLatch(1);
handler.post(new Runnable() {
  @Override
  public void run() {
    OnClickListener okListener = new OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      dialog.dismiss();
      latch.countDown();
    }
  };

  AlertDialog dialog = new AlertDialog.Builder(context).setTitle(title)
    .setMessage(msg).setPositiveButton("OK", okListener).create();
  dialog.show();
}
});
try {
  latch.await();
} catch (InterruptedException e) {
  e.printStackTrace();
}

How to properly URL encode a string in PHP?

You can use URL Encoding Functions PHP has the

rawurlencode() 

function

ASP has the

Server.URLEncode() 

function

In JavaScript you can use the

encodeURIComponent() 

function.

How to run multiple SQL commands in a single SQL connection?

I have not tested , but what the main idea is: put semicolon on each query.

SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = @"
     update table
     set somecol = somevalue;
     insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;

try
{
    connection.Open();
}
finally
{
    command.Dispose();
    connection.Dispose();
}

Update: you can follow Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property? too

Using success/error/finally/catch with Promises in AngularJS

In Angular $http case, the success() and error() function will have response object been unwrapped, so the callback signature would be like $http(...).success(function(data, status, headers, config))

for then(), you probably will deal with the raw response object. such as posted in AngularJS $http API document

$http({
        url: $scope.url,
        method: $scope.method,
        cache: $templateCache
    })
    .success(function(data, status) {
        $scope.status = status;
        $scope.data = data;
    })
    .error(function(data, status) {
        $scope.data = data || 'Request failed';
        $scope.status = status;
    });

The last .catch(...) will not need unless there is new error throw out in previous promise chain.

Parsing query strings on Android

using Guava:

Multimap<String,String> parseQueryString(String queryString, String encoding) {
    LinkedListMultimap<String, String> result = LinkedListMultimap.create();

    for(String entry : Splitter.on("&").omitEmptyStrings().split(queryString)) {
        String pair [] = entry.split("=", 2);
        try {
            result.put(URLDecoder.decode(pair[0], encoding), pair.length == 2 ? URLDecoder.decode(pair[1], encoding) : null);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    return result;
}

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

Reload chart data via JSON with Highcharts

Correct answer is:

$.each(lines, function(lineNo, line) {
                    var items = line.split(',');
                    var data = {};
                    $.each(items, function(itemNo, item) {
                        if (itemNo === 0) {
                            data.name = item;
                        } else {
                            data.y = parseFloat(item);
                        }
                    });
                    options.series[0].data.push(data);
                    data = {};
                });

You need to flush the 'data' array.

data = {};

Java Error opening registry key

Make sure to delete java references from system32, SysWOW64, and delete javapath from ProgramData\Oracle\Java. It solves the issue

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

Maybe your network is slow, so that jar isn't downloaded completely.

There are two methods:

a. find your .m2 folder, you can find some path like this 'org/apache/maven/plugins/maven-resources-plugin', you need only delete this foldler 'maven-resources-plugin', because others are downloaded well.

Then maven build your project.

If other problem occures, repeat this process again.

b. you can change a more quick maven source.

Firstly, you should find maven's settings file(window ->prefernces -> maven -> user settings). If it is empty, you can create a new one (any path, for example, .m2/settings).

Secondly, add sth like this (From https://blog.csdn.net/liangyihuai/article/details/57406870). This example uses aliyun's maven.

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

      <mirrors>
        <mirror>  
            <id>alimaven</id>  
            <name>aliyun maven</name>  
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>  
            <mirrorOf>central</mirrorOf>          
        </mirror>  
      </mirrors>
</settings>

Thirdly, maven build again. (before this, you should delete your .m2 folder's files)

How to create EditText with rounded corners?

Here is the same solution (with some extra bonus code) in just one XML file:

<?xml version="1.0" encoding="utf-8"?>
<!--  res/drawable/edittext_rounded_corners.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true" android:state_focused="true">
    <shape>
        <solid android:color="#FF8000"/>
        <stroke
            android:width="2.3dp"
            android:color="#FF8000" />
         <corners
            android:radius="15dp" />
    </shape>
</item>

<item android:state_pressed="true" android:state_focused="false">
    <shape>
        <solid android:color="#FF8000"/>
        <stroke
            android:width="2.3dp"
            android:color="#FF8000" />      
        <corners
            android:radius="15dp" />       
    </shape>
</item>

<item android:state_pressed="false" android:state_focused="true">
    <shape>
        <solid android:color="#FFFFFF"/>
        <stroke
            android:width="2.3dp"
            android:color="#FF8000" />  
        <corners
            android:radius="15dp" />                          
    </shape>
</item>

<item android:state_pressed="false" android:state_focused="false">
    <shape>
        <gradient 
            android:startColor="#F2F2F2"
            android:centerColor="#FFFFFF"
            android:endColor="#FFFFFF"
            android:angle="270"
        />
        <stroke
            android:width="0.7dp"                
            android:color="#BDBDBD" /> 
        <corners
            android:radius="15dp" />            
    </shape>
</item>

<item android:state_enabled="true">
    <shape>
        <padding 
                android:left="4dp"
                android:top="4dp"
                android:right="4dp"
                android:bottom="4dp"
            />
    </shape>
</item>

</selector>

You then just set the background attribute to edittext_rounded_corners.xml file:

<EditText  android:id="@+id/editText_name"
      android:background="@drawable/edittext_rounded_corners"/>

What's the best way to add a drop shadow to my UIView

On viewWillLayoutSubviews:

override func viewWillLayoutSubviews() {
    sampleView.layer.masksToBounds =  false
    sampleView.layer.shadowColor = UIColor.darkGrayColor().CGColor;
    sampleView.layer.shadowOffset = CGSizeMake(2.0, 2.0)
    sampleView.layer.shadowOpacity = 1.0
}

Using Extension of UIView:

extension UIView {

    func addDropShadowToView(targetView:UIView? ){
        targetView!.layer.masksToBounds =  false
        targetView!.layer.shadowColor = UIColor.darkGrayColor().CGColor;
        targetView!.layer.shadowOffset = CGSizeMake(2.0, 2.0)
        targetView!.layer.shadowOpacity = 1.0
    }
}

Usage:

sampleView.addDropShadowToView(sampleView)

Most efficient way to remove special characters from string

public static string RemoveSpecialCharacters(string str){
    return str.replaceAll("[^A-Za-z0-9_\\\\.]", "");
}

How does DISTINCT work when using JPA and Hibernate

You are close.

select DISTINCT(c.name) from Customer c

Python Accessing Nested JSON Data

I did not realize that the first nested element is actually an array. The correct way access to the post code key is as follows:

r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()

print j['state']
print j['places'][1]['post code']

Moving Average Pandas

A moving average can also be calculated and visualized directly in a line chart by using the following code:

Example using stock price data:

import pandas_datareader.data as web
import matplotlib.pyplot as plt
import datetime
plt.style.use('ggplot')

# Input variables
start = datetime.datetime(2016, 1, 01)
end = datetime.datetime(2018, 3, 29)
stock = 'WFC'

# Extrating data
df = web.DataReader(stock,'morningstar', start, end)
df = df['Close']

print df 

plt.plot(df['WFC'],label= 'Close')
plt.plot(df['WFC'].rolling(9).mean(),label= 'MA 9 days')
plt.plot(df['WFC'].rolling(21).mean(),label= 'MA 21 days')
plt.legend(loc='best')
plt.title('Wells Fargo\nClose and Moving Averages')
plt.show()

Tutorial on how to do this: https://youtu.be/XWAPpyF62Vg

SELECT from nothing?

You can. I'm using the following lines in a StackExchange Data Explorer query:

SELECT
(SELECT COUNT(*) FROM VotesOnPosts WHERE VoteTypeName = 'UpMod' AND UserId = @UserID AND PostTypeId = 2) AS TotalUpVotes,
(SELECT COUNT(*) FROM Answers WHERE UserId = @UserID) AS TotalAnswers

The Data Exchange uses Transact-SQL (the SQL Server proprietary extensions to SQL).

You can try it yourself by running a query like:

SELECT 'Hello world'

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

As Nayan said the Path has to updated properly in my case the apache-maven was installed in C:\apache-maven and settings.xml was found inside C:\apache-maven\conf\settings.xml

if this doesn't work go to your local repos
in my case C:\Users\<<"name">>.m2\
and search for .lastUpdated and delete them
then build the maven

jQuery if Element has an ID?

Simple way:

Fox example this is your html,

<div class='classname' id='your_id_name'>
</div>

Jquery code:

if($('.classname').prop('id')=='your_id_name')
{
    //works your_id_name exist (true part)
}
else
{ 
    //works your_id_name not exist (false part)
}