Programs & Examples On #Atomicboolean

Volatile boolean vs AtomicBoolean

I use volatile fields when said field is ONLY UPDATED by its owner thread and the value is only read by other threads, you can think of it as a publish/subscribe scenario where there are many observers but only one publisher. However if those observers must perform some logic based on the value of the field and then push back a new value then I go with Atomic* vars or locks or synchronized blocks, whatever suits me best. In many concurrent scenarios it boils down to get the value, compare it with another one and update if necessary, hence the compareAndSet and getAndSet methods present in the Atomic* classes.

Check the JavaDocs of the java.util.concurrent.atomic package for a list of Atomic classes and an excellent explanation of how they work (just learned that they are lock-free, so they have an advantage over locks or synchronized blocks)

Can't use Swift classes inside Objective-C

I had the same problem and finally it appeared that they weren't attached to the same targets. The ObjC class is attached to Target1 and Target2, the Swift class is only attached to the Target1 and is not visible inside the ObjC class.

Hope this helps someone.

error: expected unqualified-id before ‘.’ token //(struct)

The struct's name is ReducedForm; you need to make an object (instance of the struct or class) and use that. Do this:

ReducedForm MyReducedForm;
MyReducedForm.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;
MyReducedForm.iSimplifiedDenominator = iDenominator/iGreatCommDivisor;

Android error: Failed to install *.apk on device *: timeout

I get this a lot. I'm on a Galaxy S too. I unplug the cable from the phone, plug it back in and try launching the app again from Eclipse, and it usually does the trick. Eclipse seems to lose the connection to the phone occasionally but this seems to kick it back to life.

Does reading an entire file leave the file handle open?

The answer to that question depends somewhat on the particular Python implementation.

To understand what this is all about, pay particular attention to the actual file object. In your code, that object is mentioned only once, in an expression, and becomes inaccessible immediately after the read() call returns.

This means that the file object is garbage. The only remaining question is "When will the garbage collector collect the file object?".

in CPython, which uses a reference counter, this kind of garbage is noticed immediately, and so it will be collected immediately. This is not generally true of other python implementations.

A better solution, to make sure that the file is closed, is this pattern:

with open('Path/to/file', 'r') as content_file:
    content = content_file.read()

which will always close the file immediately after the block ends; even if an exception occurs.

Edit: To put a finer point on it:

Other than file.__exit__(), which is "automatically" called in a with context manager setting, the only other way that file.close() is automatically called (that is, other than explicitly calling it yourself,) is via file.__del__(). This leads us to the question of when does __del__() get called?

A correctly-written program cannot assume that finalizers will ever run at any point prior to program termination.

-- https://devblogs.microsoft.com/oldnewthing/20100809-00/?p=13203

In particular:

Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable.

[...]

CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references.

-- https://docs.python.org/3.5/reference/datamodel.html#objects-values-and-types

(Emphasis mine)

but as it suggests, other implementations may have other behavior. As an example, PyPy has 6 different garbage collection implementations!

Page redirect with successful Ajax request

Sure. Just put something at the the end of your success function like:

if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"

where your server returns the response no_errors when there are no errors present.

Append value to empty vector in R?

You have a few options:

  • c(vector, values)

  • append(vector, values)

  • vector[(length(vector) + 1):(length(vector) + length(values))] <- values

The first one is the standard approach. The second one gives you the option to append someplace other than the end. The last one is a bit contorted but has the advantage of modifying vector (though really, you could just as easily do vector <- c(vector, values).

Notice that in R you don't need to cycle through vectors. You can just operate on them in whole.

Also, this is fairly basic stuff, so you should go through some of the references.

Some more options based on OP feedback:

for(i in values) vector <- c(vector, i)

Differences in boolean operators: & vs && and | vs ||

& and | are bitwise operators on integral types (e.g. int): http://download.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

&& and || operate on booleans only (and short-circuit, as other answers have already said).

What is NODE_ENV and how to use it in Express?

I assume the original question included how does Express use this environment variable.

Express uses NODE_ENV to alter its own default behavior. For example, in development mode, the default error handler will send back a stacktrace to the browser. In production mode, the response is simply Internal Server Error, to avoid leaking implementation details to the world.

How to hide the soft keyboard from inside a fragment?

This worked for me in Kotlin class

fun hideKeyboard(activity: Activity) {
    try {
        val inputManager = activity
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val currentFocusedView = activity.currentFocus
        if (currentFocusedView != null) {
            inputManager.hideSoftInputFromWindow(currentFocusedView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }

}

How to put more than 1000 values into an Oracle IN clause

Put the values in a temporary table and then do a select where id in (select id from temptable)

Remove HTML Tags from an NSString on the iPhone

Here's the swift version :

func stripHTMLFromString(string: String) -> String {
  var copy = string
  while let range = copy.rangeOfString("<[^>]+>", options: .RegularExpressionSearch) {
    copy = copy.stringByReplacingCharactersInRange(range, withString: "")
  }
  copy = copy.stringByReplacingOccurrencesOfString("&nbsp;", withString: " ")
  copy = copy.stringByReplacingOccurrencesOfString("&amp;", withString: "&")
  return copy
}

Android ACTION_IMAGE_CAPTURE Intent

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CANCELED)
    {
        //do not process data, I use return; to resume activity calling camera intent
        enter code here
    }
}

"%%" and "%/%" for the remainder and the quotient

I think it is because % has often be associated with the modulus operator in many programming languages.

It is the case, e.g., in C, C++, C# and Java, and many other languages which derive their syntax from C (C itself took it from B).

DateTime.Compare how to check if a date is less than 30 days old?

Am I using DateTime Compare correctly?

No. Compare only offers information about the relative position of two dates: less, equal or greater. What you want is something like this:

if ((expiryDate - DateTime.Now).TotalDays < 30)
    matchFound = true;

This subtracts two DateTimes. The result is a TimeSpan object which has a TotalDays property.

Additionally, the conditional can be written directly as:

matchFound = (expiryDate - DateTime.Now).TotalDays < 30;

No if needed.

Any way to write a Windows .bat file to kill processes?

Download PSKill. Write a batch file that calls it for each process you want dead, passing in the name of the process for each.

Basic example for sharing text or image with UIActivityViewController in Swift

I found this to work flawlessly if you want to share whole screen.

@IBAction func shareButton(_ sender: Any) {

    let bounds = UIScreen.main.bounds
    UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
    self.view.drawHierarchy(in: bounds, afterScreenUpdates: false)
    let img = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    let activityViewController = UIActivityViewController(activityItems: [img!], applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view
    self.present(activityViewController, animated: true, completion: nil)
}

Resolve promises one after another (i.e. in sequence)?

I've had to run a lot of sequential tasks and used these answers to forge a function that would take care of handling any sequential task...

function one_by_one(objects_array, iterator, callback) {
    var start_promise = objects_array.reduce(function (prom, object) {
        return prom.then(function () {
            return iterator(object);
        });
    }, Promise.resolve()); // initial
    if(callback){
        start_promise.then(callback);
    }else{
        return start_promise;
    }
}

The function takes 2 arguments + 1 optional. First argument is the array on which we will be working. The second argument is the task itself, a function that returns a promise, the next task will be started only when this promise resolves. The third argument is a callback to run when all tasks have been done. If no callback is passed, then the function returns the promise it created so we can handle the end.

Here's an example of usage:

var filenames = ['1.jpg','2.jpg','3.jpg'];
var resize_task = function(filename){
    //return promise of async resizing with filename
};
one_by_one(filenames,resize_task );

Hope it saves someone some time...

TCP vs UDP on video stream

One of the biggest problems with delivering live events on Internet is 'scale', and TCP doesn’t scale well. For example when you are beaming a live football match -as opposed to an on demand movie playback- the number of people watching can easily be 1000 times more. In such a scenario using TCP is a death sentence for the CDNs (content delivery networks).

There are a couple of main reasons why TCP doesn't scale well:

  1. One of the largest tradeoffs of TCP is the variability of throughput achievable between the sender and the receiver. When streaming video over the Internet the video packets must traverse multiple routers over the Internet, each of these routers is connected with different speed connections. The TCP algorithm starts with TCP window off small, then grows until packet loss is detected, the packet loss is considered a sign of congestion and TCP responds to it by drastically reducing the window size to avoid congestion. Thus in turn reducing the effective throughput immediately. Now imagine a network with TCP transmission using 6-7 router hops to the client (a very normal scenario), if any of the intermediate router looses any packet, the TCP for that link will reduce the transmission rate. In-fact The traffic flow between routers follow an hourglass kind of a shape; always gong up and down in-between one of the intermediate routers. Rendering the effective through put much lower compared to best-effort UDP.

  2. As you may already know TCP is an acknowledgement-based protocol. Lets for example say a sender is 50ms away (i.e. latency btw two points). This would mean time it takes for a packet to be sent to a receiver and receiver to send an acknowledgement would be 100ms; thus maximum throughput possible as compared to UDP based transmission is already halved.

  3. The TCP doesn’t support multicasting or the new emerging standard of multicasting AMT. Which means the CDNs don’t have the opportunity to reduce network traffic by replicating the packets -when many clients are watching the same content. That itself is a big enough reason for CDNs (like Akamai or Level3) to not go with TCP for live streams.

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

For thumbor-aws, that used boto config, i needed to put this to the $AWS_CONFIG_FILE

[default]
aws_access_key_id = (your ID)
aws_secret_access_key = (your secret key)
s3 =
    signature_version = s3

So anything that used boto directly without changes, this may be useful

How to create and handle composite primary key in JPA

The MyKey class (@Embeddable) should not have any relationships like @ManyToOne

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

JQuery get data from JSON array

You need to iterate both the groups and the items. $.each() takes a collection as first parameter and data.response.venue.tips.groups.items.text tries to point to a string. Both groups and items are arrays.

Verbose version:

$.getJSON(url, function (data) {

    // Iterate the groups first.
    $.each(data.response.venue.tips.groups, function (index, value) {

        // Get the items
        var items = this.items; // Here 'this' points to a 'group' in 'groups'

        // Iterate through items.
        $.each(items, function () {
            console.log(this.text); // Here 'this' points to an 'item' in 'items'
        });
    });
});

Or more simply:

$.getJSON(url, function (data) {
    $.each(data.response.venue.tips.groups, function (index, value) {
        $.each(this.items, function () {
            console.log(this.text);
        });
    });
});

In the JSON you specified, the last one would be:

$.getJSON(url, function (data) {
    // Get the 'items' from the first group.
    var items = data.response.venue.tips.groups[0].items;

    // Find the last index and the last item.
    var lastIndex = items.length - 1;
    var lastItem = items[lastIndex];

    console.log("User: " + lastItem.user.firstName + " " + lastItem.user.lastName);
    console.log("Date: " + lastItem.createdAt);
    console.log("Text: " + lastItem.text);
});

This would give you:

User: Damir P.
Date: 1314168377
Text: ajd da vidimo hocu li znati ponoviti

How to make a UILabel clickable?

Swift 5

Similar to @liorco, but need to replace @objc with @IBAction.

class DetailViewController: UIViewController {

    @IBOutlet weak var tripDetails: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        ...

        let tap = UITapGestureRecognizer(target: self, action: #selector(DetailViewController.tapFunction))
        tripDetails.isUserInteractionEnabled = true
        tripDetails.addGestureRecognizer(tap)
    }

    @IBAction func tapFunction(sender: UITapGestureRecognizer) {
        print("tap working")
    }
}

This is working on Xcode 10.2.

PHP Session Destroy on Log Out Button

// logout

if(isset($_GET['logout'])) {
    session_destroy();
    unset($_SESSION['username']);
    header('location:login.php');
}

?>

Git copy file preserving history

Simply copy the file, add and commit it:

cp dir1/A.txt dir2/A.txt
git add dir2/A.txt
git commit -m "Duplicated file from dir1/ to dir2/"

Then the following commands will show the full pre-copy history:

git log --follow dir2/A.txt

To see inherited line-by-line annotations from the original file use this:

git blame -C -C -C dir2/A.txt

Git does not track copies at commit-time, instead it detects them when inspecting history with e.g. git blame and git log.

Most of this information comes from the answers here: Record file copy operation with Git

How to get the correct range to set the value to a cell?

Solution : SpreadsheetApp.getActiveSheet().getRange('F2').setValue('hello')

Explanation :

Setting value in a cell in spreadsheet to which script is attached

SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);

Setting value in a cell in sheet which is open currently and to which script is attached

SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(RANGE).setValue(VALUE);

Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet name known)

SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);

Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet position known)

SpreadsheetApp.openById(SHEET_ID).getSheets()[POSITION].getRange(RANGE).setValue(VALUE);

These are constants, you must define them yourself

SHEET_ID

SHEET_NAME

POSITION

VALUE

RANGE

By script attached to a sheet I mean that script is residing in the script editor of that sheet. Not attached means not residing in the script editor of that sheet. It can be in any other place.

How to resolve this System.IO.FileNotFoundException

I hate to point out the obvious, but System.IO.FileNotFoundException means the program did not find the file you specified. So what you need to do is check what file your code is looking for in production.

To see what file your program is looking for in production (look at the FileName property of the exception), try these techniques:

Then look at the file system on the machine and see if the file exists. Most likely the case is that it doesn't exist.

Returning value from Thread

Usually you would do it something like this

 public class Foo implements Runnable {
     private volatile int value;

     @Override
     public void run() {
        value = 2;
     }

     public int getValue() {
         return value;
     }
 }

Then you can create the thread and retrieve the value (given that the value has been set)

Foo foo = new Foo();
Thread thread = new Thread(foo);
thread.start();
thread.join();
int value = foo.getValue();

tl;dr a thread cannot return a value (at least not without a callback mechanism). You should reference a thread like an ordinary class and ask for the value.

How do I remove trailing whitespace using a regular expression?

If using Visual Studio 2012 and later (which uses .NET regular expressions), you can remove trailing whitespace without removing blank lines by using the following regex

Replace (?([^\r\n])\s)+(\r?\n)

With $1

Enter image description here


Some explanation

The reason you need the rather complicated expression is that the character class \s matches spaces, tabs and newline characters, so \s+ will match a group of lines containing only whitespace. It doesn't help adding a $ termination to this regex, because this will still match a group of lines containing only whitespace and newline characters.

You may also want to know (as I did) exactly what the (?([^\r\n])\s) expression means. This is an Alternation Construct, which effectively means match to the whitespace character class if it is not a carriage return or linefeed.

Alternation constructs normally have a true and false part,

(?( expression ) yes | no )

but in this case the false part is not specified.

How to get current foreground activity context in android?

I did the Following in Kotlin

  1. Create Application Class
  2. Edit the Application Class as Follows

    class FTApplication: MultiDexApplication() {
    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }
    
    init {
        instance = this
    }
    
    val mFTActivityLifecycleCallbacks = FTActivityLifecycleCallbacks()
    
    override fun onCreate() {
        super.onCreate()
    
        registerActivityLifecycleCallbacks(mFTActivityLifecycleCallbacks)
    }
    
    companion object {
        private var instance: FTApplication? = null
    
        fun currentActivity(): Activity? {
    
            return instance!!.mFTActivityLifecycleCallbacks.currentActivity
        }
    }
    
     }
    
  3. Create the ActivityLifecycleCallbacks class

    class FTActivityLifecycleCallbacks: Application.ActivityLifecycleCallbacks {
    
    var currentActivity: Activity? = null
    
    override fun onActivityPaused(activity: Activity?) {
        currentActivity = activity
    }
    
    override fun onActivityResumed(activity: Activity?) {
        currentActivity = activity
    }
    
    override fun onActivityStarted(activity: Activity?) {
        currentActivity = activity
    }
    
    override fun onActivityDestroyed(activity: Activity?) {
    }
    
    override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {
    }
    
    override fun onActivityStopped(activity: Activity?) {
    }
    
    override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
        currentActivity = activity
    }
    
    }
    
  4. you can now use it in any class by calling the following: FTApplication.currentActivity()

How do I capture response of form.submit

First of all we will need serializeObject();

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

then you make a basic post and get response

$.post("/Education/StudentSave", $("#frmNewStudent").serializeObject(), function (data) {
if(data){
//do true 
}
else
{
//do false
}

});

Output PowerShell variables to a text file

I usually construct custom objects in these loops, and then add these objects to an array that I can easily manipulate, sort, export to CSV, etc.:

# Construct an out-array to use for data export
$OutArray = @()

# The computer loop you already have
foreach ($server in $serverlist)
    {
        # Construct an object
        $myobj = "" | Select "computer", "Speed", "Regcheck"

        # Fill the object
        $myobj.computer = $computer
        $myobj.speed = $speed
        $myobj.regcheck = $regcheck

        # Add the object to the out-array
        $outarray += $myobj

        # Wipe the object just to be sure
        $myobj = $null
    }

# After the loop, export the array to CSV
$outarray | export-csv "somefile.csv"

MySQL stored procedure return value

You have done the stored procedure correctly but I think you have not referenced the valido variable properly. I was looking at some examples and they have put an @ symbol before the parameter like this @Valido

This statement SELECT valido; should be like this SELECT @valido;

Look at this link mysql stored-procedure: out parameter. Notice the solution with 7 upvotes. He has reference the parameter with an @ sign, hence I suggested you add an @ sign before your parameter valido

I hope that works for you. if it does vote up and mark it as the answer. If not, tell me.

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

I'd try something like:

#!/usr/bin/python
from __future__ import print_function

import shlex
from subprocess import Popen, PIPE

def shlep(cmd):
    '''shlex split and popen
    '''
    parsed_cmd = shlex.split(cmd)
    ## if parsed_cmd[0] not in approved_commands:
    ##    raise ValueError, "Bad User!  No output for you!"
    proc = Popen(parsed_command, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()
    return (proc.returncode, out, err)

... In other words let shlex.split() do most of the work. I would NOT attempt to parse the shell's command line, find pipe operators and set up your own pipeline. If you're going to do that then you'll basically have to write a complete shell syntax parser and you'll end up doing an awful lot of plumbing.

Of course this raises the question, why not just use Popen with the shell=True (keyword) option? This will let you pass a string (no splitting nor parsing) to the shell and still gather up the results to handle as you wish. My example here won't process any pipelines, backticks, file descriptor redirection, etc that might be in the command, they'll all appear as literal arguments to the command. Thus it is still safer then running with shell=True ... I've given a silly example of checking the command against some sort of "approved command" dictionary or set --- through it would make more sense to normalize that into an absolute path unless you intend to require that the arguments be normalized prior to passing the command string to this function.

iOS - UIImageView - how to handle UIImage image orientation

I converted the code from @Nicolas Miari answer to Swift 3 in case anybody needs it

func fixOrientation() -> UIImage
{

    if self.imageOrientation == UIImageOrientation.up {
        return self
    }

    var transform = CGAffineTransform.identity

    switch self.imageOrientation {
    case .down, .downMirrored:
        transform = transform.translatedBy(x: self.size.width, y: self.size.height)
        transform = transform.rotated(by: CGFloat(M_PI));

    case .left, .leftMirrored:
        transform = transform.translatedBy(x: self.size.width, y: 0);
        transform = transform.rotated(by: CGFloat(M_PI_2));

    case .right, .rightMirrored:
        transform = transform.translatedBy(x: 0, y: self.size.height);
        transform = transform.rotated(by: CGFloat(-M_PI_2));

    case .up, .upMirrored:
        break
    }


    switch self.imageOrientation {

    case .upMirrored, .downMirrored:
        transform = transform.translatedBy(x: self.size.width, y: 0)
        transform = transform.scaledBy(x: -1, y: 1)

    case .leftMirrored, .rightMirrored:
        transform = transform.translatedBy(x: self.size.height, y: 0)
        transform = transform.scaledBy(x: -1, y: 1);

    default:
        break;
    }

    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    let ctx = CGContext(
        data: nil,
        width: Int(self.size.width),
        height: Int(self.size.height),
        bitsPerComponent: self.cgImage!.bitsPerComponent,
        bytesPerRow: 0,
        space: self.cgImage!.colorSpace!,
        bitmapInfo: UInt32(self.cgImage!.bitmapInfo.rawValue)
    )



    ctx!.concatenate(transform);

    switch self.imageOrientation {

    case .left, .leftMirrored, .right, .rightMirrored:
        // Grr...
        ctx?.draw(self.cgImage!, in: CGRect(x:0 ,y: 0 ,width: self.size.height ,height:self.size.width))

    default:
        ctx?.draw(self.cgImage!, in: CGRect(x:0 ,y: 0 ,width: self.size.width ,height:self.size.height))
        break;
    }

    // And now we just create a new UIImage from the drawing context
    let cgimg = ctx!.makeImage()

    let img = UIImage(cgImage: cgimg!)

    return img;

}

How to write some data to excel file(.xlsx)

Hope here is the exact what we are looking for.

private void button2_Click(object sender, RoutedEventArgs e)
{
    UpdateExcel("Sheet3", 4, 7, "Namachi@gmail");
}

private void UpdateExcel(string sheetName, int row, int col, string data)
{
    Microsoft.Office.Interop.Excel.Application oXL = null;
    Microsoft.Office.Interop.Excel._Workbook oWB = null;
    Microsoft.Office.Interop.Excel._Worksheet oSheet = null;

    try
    {
        oXL = new Microsoft.Office.Interop.Excel.Application();
        oWB = oXL.Workbooks.Open("d:\\MyExcel.xlsx");
        oSheet = String.IsNullOrEmpty(sheetName) ? (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet : (Microsoft.Office.Interop.Excel._Worksheet)oWB.Worksheets[sheetName];

        oSheet.Cells[row, col] = data;

        oWB.Save();

        MessageBox.Show("Done!");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    finally
    {
        if (oWB != null)
        oWB.Close();
    }
}

How to return a table from a Stored Procedure?

Where is your problem??

For the stored procedure, just create:

CREATE PROCEDURE dbo.ReadEmployees @EmpID INT
AS
   SELECT *  -- I would *strongly* recommend specifying the columns EXPLICITLY
   FROM dbo.Emp
   WHERE ID = @EmpID

That's all there is.

From your ASP.NET application, just create a SqlConnection and a SqlCommand (don't forget to set the CommandType = CommandType.StoredProcedure)

DataTable tblEmployees = new DataTable();

using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
{
    _cmd.CommandType = CommandType.StoredProcedure;

    _cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
    _cmd.Parameters["@EmpID"].Value = 42;

    SqlDataAdapter _dap = new SqlDataAdapter(_cmd);

    _dap.Fill(tblEmployees);
}

YourGridView.DataSource = tblEmployees;
YourGridView.DataBind();

and then fill e.g. a DataTable with that data and bind it to e.g. a GridView.

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

Remote desktop connection protocol error 0x112f

A simple thing. Disable the vsphere options 3D for the virtual maschine . It works perfect. When you want, reinstall the vm-tools for the virtual maschine.

ReactJS and images in public folder

To reference images in public there are two ways I know how to do it straight forward. One is like above from Homam Bahrani.

using

    <img src={process.env.PUBLIC_URL + '/yourPathHere.jpg'} /> 

And since this works you really don't need anything else but, this also works...

    <img src={window.location.origin + '/yourPathHere.jpg'} />

How do I get into a non-password protected Java keystore or change the password?

The password of keystore by default is: "changeit". I functioned to my commands you entered here, for the import of the certificate. I hope you have already solved your problem.

How to get overall CPU usage (e.g. 57%) on Linux

Try mpstat from the sysstat package

> sudo apt-get install sysstat
Linux 3.0.0-13-generic (ws025)  02/10/2012  _x86_64_    (2 CPU)  

03:33:26 PM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest   %idle
03:33:26 PM  all    2.39    0.04    0.19    0.34    0.00    0.01    0.00    0.00   97.03

Then some cutor grepto parse the info you need:

mpstat | grep -A 5 "%idle" | tail -n 1 | awk -F " " '{print 100 -  $ 12}'a

Python loop counter in a for loop

You could also do:

 for option in options:
      if option == options[selected_index]:
           #print
      else:
           #print

Although you'd run into issues if there are duplicate options.

Difficulty with ng-model, ng-repeat, and inputs

how do something like:

<select ng-model="myModel($index+1)">

And in my inspector element be:

<select ng-model="myModel1">
...
<select ng-model="myModel2">

Removing nan values from an array

The accepted answer changes shape for 2d arrays. I present a solution here, using the Pandas dropna() functionality. It works for 1D and 2D arrays. In the 2D case you can choose weather to drop the row or column containing np.nan.

import pandas as pd
import numpy as np

def dropna(arr, *args, **kwarg):
    assert isinstance(arr, np.ndarray)
    dropped=pd.DataFrame(arr).dropna(*args, **kwarg).values
    if arr.ndim==1:
        dropped=dropped.flatten()
    return dropped

x = np.array([1400, 1500, 1600, np.nan, np.nan, np.nan ,1700])
y = np.array([[1400, 1500, 1600], [np.nan, 0, np.nan] ,[1700,1800,np.nan]] )


print('='*20+' 1D Case: ' +'='*20+'\nInput:\n',x,sep='')
print('\ndropna:\n',dropna(x),sep='')

print('\n\n'+'='*20+' 2D Case: ' +'='*20+'\nInput:\n',y,sep='')
print('\ndropna (rows):\n',dropna(y),sep='')
print('\ndropna (columns):\n',dropna(y,axis=1),sep='')

print('\n\n'+'='*20+' x[np.logical_not(np.isnan(x))] for 2D: ' +'='*20+'\nInput:\n',y,sep='')
print('\ndropna:\n',x[np.logical_not(np.isnan(x))],sep='')

Result:

==================== 1D Case: ====================
Input:
[1400. 1500. 1600.   nan   nan   nan 1700.]

dropna:
[1400. 1500. 1600. 1700.]


==================== 2D Case: ====================
Input:
[[1400. 1500. 1600.]
 [  nan    0.   nan]
 [1700. 1800.   nan]]

dropna (rows):
[[1400. 1500. 1600.]]

dropna (columns):
[[1500.]
 [   0.]
 [1800.]]


==================== x[np.logical_not(np.isnan(x))] for 2D: ====================
Input:
[[1400. 1500. 1600.]
 [  nan    0.   nan]
 [1700. 1800.   nan]]

dropna:
[1400. 1500. 1600. 1700.]

Using arrays or std::vectors in C++, what's the performance gap?

There is definitely a performance impact to using an std::vector vs a raw array when you want an uninitialized buffer (e.g. to use as destination for memcpy()). An std::vector will initialize all its elements using the default constructor. A raw array will not.

The c++ spec for the std:vector constructor taking a count argument (it's the third form) states:

`Constructs a new container from a variety of data sources, optionally using a user supplied allocator alloc.

  1. Constructs the container with count default-inserted instances of T. No copies are made.

Complexity

2-3) Linear in count

A raw array does not incur this initialization cost.

Note that with a custom allocator, it is possible to avoid "initialization" of the vector's elements (i.e. to use default initialization instead of value initialization). See these questions for more details:

Angular directive how to add an attribute to the element?

A directive which adds another directive to the same element:

Similar answers:

Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview

app.directive("myDir", function($compile) {
  return {
    priority:1001, // compiles first
    terminal:true, // prevent lower priority directives to compile after it
    compile: function(el) {
      el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
      el.attr('ng-click', 'fxn()');
      var fn = $compile(el);
      return function(scope){
        fn(scope);
      };
    }
  };
});

Much cleaner solution - not to use ngClick at all:

A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview

app.directive("myDir", function($parse) {
  return {
    compile: function(tElm,tAttrs){
      var exp = $parse('fxn()');
      return function (scope,elm){
        elm.bind('click',function(){
          exp(scope);
        });  
      };
    }
  };
});

parseInt with jQuery

var test = parseInt($("#testid").val(), 10);

You have to tell it you want the value of the input you are targeting.

And also, always provide the second argument (radix) to parseInt. It tries to be too clever and autodetect it if not provided and can lead to unexpected results.

Providing 10 assumes you are wanting a base 10 number.

How can I make a checkbox readonly? not disabled?

I personally like to do it this way:

<input type="checkbox" name="option" value="1" disabled="disabled" />
<input type="hidden" name="option" value="1">

I think this is better for two reasons:

  1. User clearly understand that he can't edit this value
  2. The value is sent when submitting the form.

Angular2 Routing with Hashtag to page anchor

A little late but here's an answer I found that works:

<a [routerLink]="['/path']" fragment="test" (click)="onAnchorClick()">Anchor</a>

And in the component:

constructor( private route: ActivatedRoute, private router: Router ) {}

  onAnchorClick ( ) {
    this.route.fragment.subscribe ( f => {
      const element = document.querySelector ( "#" + f )
      if ( element ) element.scrollIntoView ( element )
    });
  }

The above doesn't automatically scroll to the view if you land on a page with an anchor already, so I used the solution above in my ngInit so that it could work with that as well:

ngOnInit() {
    this.router.events.subscribe(s => {
      if (s instanceof NavigationEnd) {
        const tree = this.router.parseUrl(this.router.url);
        if (tree.fragment) {
          const element = document.querySelector("#" + tree.fragment);
          if (element) { element.scrollIntoView(element); }
        }
      }
    });
  }

Make sure to import Router, ActivatedRoute and NavigationEnd at the beginning of your component and it should be all good to go.

Source

What does the construct x = x || y mean?

Quote: "What does the construct x = x || y mean?"

Assigning a default value.

This means providing a default value of y to x, in case x is still waiting for its value but hasn't received it yet or was deliberately omitted in order to fall back to a default.

How to set Status Bar Style in Swift 3

There seems to be a small issue about the status bar text colour when dealing with navigation bars.

If you want the .plist entry View controller-based status bar appearance set to YES, it sometimes won't work when you have a coloured nav bar.

For example:

override func viewWillAppear(_ animated: Bool) {
    let nav = self.navigationController?.navigationBar
    nav?.barTintColor = .red
    nav?.tintColor = .white
    nav?.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
    setNeedsStatusBarAppearanceUpdate()
}

and

override var preferredStatusBarStyle: UIStatusBarStyle {return .lightContent}

The code above won't work even if you have set the following in the AppDelegate:

UIApplication.shared.statusBarStyle = .lightContent

For those still struggling, apparently it somehow judges if the status bar needs to be light or dark by the styles in the nav bar. So, I managed to fix this by adding the following line in viewWillAppear:

nav?.barStyle = UIBarStyle.black

When the bar style is black, then it listens to your overridden variable. Hope this helps someone :)

Check if URL has certain string with PHP

if( strpos( $url, $word ) !== false ) {
    // Do something
}

Can't bind to 'formGroup' since it isn't a known property of 'form'

You can get this error message even if you have already imported FormsModule and ReactiveFormsModule. I moved a component (that uses the [formGroup] directive) from one project to another, but failed to add the component to the declarations array in the new module. That resulted in the Can't bind to 'formGroup' since it isn't a known property of 'form' error message.

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

The JAX-WS dependency library “jaxws-rt.jar” is missing.

Go here http://jax-ws.java.net/. Download JAX-WS RI distribution. Unzip it and copy “jaxws-rt.jar” to Tomcat library folder “{$TOMCAT}/lib“. Restart Tomcat.

What is the significance of #pragma marks? Why do we need #pragma marks?

Just to add the information I was looking for: pragma mark is Xcode specific, so if you deal with a C++ project that you open in different IDEs, it does not have any effect there. In Qt Creator, for example, it does not add categories for methods, nor generate any warnings/errors.

EDIT

#pragma is a preprocessor directive which comes from C programming language. Its purpose is to specify implementation-dependent information to the compiler - that is, each compiler might choose to interpret this directive as it wants. That said, it is rather considered an extension which does not change/influence the code itself. So compilers might as well ignore it.

Xcode is an IDE which takes advantage of #pragma and uses it in its own specific way. The point is, #pragma is not Xcode and even Objective-C specific.

Is there a way to define a min and max value for EditText in Android?

I extended @Pratik Sharmas code to use BigDecimal objects instead of ints so that it can accept larger numbers, and account for any formatting in the EditText that isn't a number (like currency formatting i.e. spaces, commas and periods)

EDIT: note that this implementation has 2 as the minimum significant figures set on the BigDecimal (see the MIN_SIG_FIG constant) as I used it for currency, so there was always 2 leading numbers before the decimal point. Alter the MIN_SIG_FIG constant as necessary for your own implementation.

public class InputFilterMinMax implements InputFilter {
private static final int MIN_SIG_FIG = 2;
private BigDecimal min, max;

public InputFilterMinMax(BigDecimal min, BigDecimal max) {
    this.min = min;
    this.max = max;
}

public InputFilterMinMax(String min, String max) {
    this.min = new BigDecimal(min);
    this.max = new BigDecimal(max);
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
        int dend) {
    try {
        BigDecimal input = formatStringToBigDecimal(dest.toString()
                + source.toString());

        if (isInRange(min, max, input)) {

            return null;
        }
    } catch (NumberFormatException nfe) {

    }
    return "";
}

private boolean isInRange(BigDecimal a, BigDecimal b, BigDecimal c) {
    return b.compareTo(a) > 0 ? c.compareTo(a) >= 0 && c.compareTo(b) <= 0
            : c.compareTo(b) >= 0 && c.compareTo(a) <= 0;
}

public static BigDecimal formatStringToBigDecimal(String n) {

    Number number = null;
    try {
        number = getDefaultNumberFormat().parse(n.replaceAll("[^\\d]", ""));

        BigDecimal parsed = new BigDecimal(number.doubleValue()).divide(new BigDecimal(100), 2,
                BigDecimal.ROUND_UNNECESSARY);
        return parsed;
    } catch (ParseException e) {
        return new BigDecimal(0);
    }
}

private static NumberFormat getDefaultNumberFormat() {
    NumberFormat nf = NumberFormat.getInstance(Locale.getDefault());
    nf.setMinimumFractionDigits(MIN_SIG_FIG);
    return nf;
}

Put buttons at bottom of screen with LinearLayout?

first create file name it as footer.xml put this code inside it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="78dp"
    android:layout_gravity="bottom"
    android:gravity="bottom"
 android:layout_weight=".15"
    android:orientation="horizontal"
    android:background="@drawable/actionbar_dark_background_tile" >
    <ImageView
        android:id="@+id/lborder"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/overlay" />
    <ImageView
        android:id="@+id/unknown"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/notcolor" />
    <ImageView
        android:id="@+id/open"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/openit"
        />
    <ImageView
        android:id="@+id/color"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/colored" />
        <ImageView
        android:id="@+id/rborder"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/frames"
        android:layout_weight=".14" />


</LinearLayout>  

then create header.xml and put this code inside it.:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="@dimen/action_bar_height"
    android:layout_gravity="top"
    android:baselineAligned="true"
    android:orientation="horizontal"
    android:background="@drawable/actionbar_dark_background_tile" >
    <ImageView
        android:id="@+id/contact"
        android:layout_width="37dp"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:layout_weight=".18"
        android:scaleType="fitCenter"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/logo"/>

    <ImageView
        android:id="@+id/share"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/share" />

    <ImageView
        android:id="@+id/save"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/save" />

    <ImageView
        android:id="@+id/set"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/set" />

    <ImageView
        android:id="@+id/fix"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/light" />

    <ImageView
        android:id="@+id/rotate"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/ic_menu_rotate" />

    <ImageView
        android:id="@+id/stock"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/stock" />

</LinearLayout>

and then in your main_activity.xml and put this code inside it :-

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity"
android:id="@+id/relt"
android:background="@drawable/background" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="78dp"
    android:id="@+id/down"
    android:layout_alignParentBottom="true" >

    <include
        android:layout_width="fill_parent"
        android:layout_height="78dp"
        layout="@layout/footer" >
    </include>
</LinearLayout>
<ImageView
    android:id="@+id/view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/down"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/inc"
   >  
    </ImageView> 
    <include layout="@layout/header"
        android:id="@+id/inc"
        android:layout_width="fill_parent"
        android:layout_height="50dp"></include> 

happy coding :)

Freeze screen in chrome debugger / DevTools panel for popover inspection?

To be able to inspect any element do the following. This should work even if it's hard to duplicate the hover state:

  • Run the following javascript in the console. This will break into the debugger in 5 seconds.

    setTimeout(function(){debugger;}, 5000)

  • Go show your element (by hovering or however) and wait until Chrome breaks into the Debugger.

  • Now click on the Elements tab in the Chrome Inspector, and you can look for your element there.
  • You may also be able to click on the Find Element icon (looks like a magnifying glass) and Chrome will let you go and inspect and find your element on the page by right clicking on it, then choosing Inspect Element

Note that this approach is a slight variation to this other great answer on this page.

Setting device orientation in Swift iOS

Two suggestions with @Vivek Parihar's solution :

  1. If we are presenting any viewController we should check nil for “visibleViewController” in navigationController extension

    extension UINavigationController {
    public override func shouldAutorotate() -> Bool {
        var shouldAutorotate = false
        if visibleViewController != nil {
            shouldAutorotate = visibleViewController.shouldAutorotate()
        }
        return shouldAutorotate
    }
    
    public override func supportedInterfaceOrientations() -> Int {
        return visibleViewController.supportedInterfaceOrientations()
    }
    }
    
  2. If We are using any action sheet to present and user will rotate upsideDown, Your action sheet will open from top edge of the screen :P, to solve this, we should take Portrait only

    override func shouldAutorotate() -> Bool {
    if (UIDevice.currentDevice().orientation == UIDeviceOrientation.Portrait ||
        UIDevice.currentDevice().orientation == UIDeviceOrientation.Unknown) {
            return true
    }
    else {
        return false
    }
    

    }

    override func supportedInterfaceOrientations() -> Int {
        return Int(UIInterfaceOrientationMask.Portrait.rawValue)
    }
    

How do I create a branch?

Suppose you want to create a branch from a trunk name (as "TEST") then use:

svn cp -m "CREATE BRANCH TEST" $svn_url/trunk $svn_url/branches/TEST

What does 'wb' mean in this code, using Python?

That is the mode with which you are opening the file. "wb" means that you are writing to the file (w), and that you are writing in binary mode (b).

Check out the documentation for more: clicky

How to round a Double to the nearest Int in swift?

**In Swift**

var a = 14.123456789
var b = 14.123456789
var c = 14.123456789
var d = 14.123456789
var e = 14.123456789
var f = 14.123456789

a.rounded(.up)                      //15
b.rounded(.down)                    //14
c.rounded(.awayFromZero)            //15
d.rounded(.towardZero)              //14
e.rounded(.toNearestOrAwayFromZero) //14
f.rounded(.toNearestOrEven)         //14

SVN: Folder already under version control but not comitting?

I found a solution in case you have installed Eclipse(Luna) with the SVN Client JavaHL(JNI) 1.8.13 and Tortoise:

Open Eclipse: First try to add the project / maven module to Version Control (Project -> Context Menu -> Team -> Add to Version Control)

You will see the following Eclipse error message:

org.apache.subversion.javahl.ClientException: Entry already exists svn: 'PathToYouProject' is already under version control

After that you have to open your workspace directory in your explorer, select your project and resolve it via Tortoise (Project -> Context Menu -> TortoiseSVN -> Resolve)

You will see the following message dialog: "File list is empty"

Press cancel and refresh the project in Eclipse. Your project should be under version control again.

Unfortunately it is not possible to resolve more the one project at the same time ... you don't have to delete anything but depending on the size of your project it could be a little bit laborious.

PHP isset() with multiple parameters

You just need:

if (!empty($_POST['search_term']) && !empty($_POST['postcode']))

isset && !empty is redundant.

How can I load storyboard programmatically from class?

In attribute inspector give the identifier for that view controller and the below code works for me

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
DetailViewController *detailViewController = [storyboard instantiateViewControllerWithIdentifier:@"DetailViewController"];
[self.navigationController pushViewController:detailViewController animated:YES];

Force unmount of NFS-mounted directory

Try running

lsof | grep /mnt/data

That should list any process that is accessing /mnt/data that would prevent it from being unmounted.

Find current directory and file's directory

Answer to #1:

If you want the current directory, do this:

import os
os.getcwd()

If you want just any folder name and you have the path to that folder, do this:

def get_folder_name(folder):
    '''
    Returns the folder name, given a full folder path
    '''
    return folder.split(os.sep)[-1]

Answer to #2:

import os
print os.path.abspath(__file__)

Running code in main thread from another thread

With Kotlin, it is just like this inside any function:

runOnUiThread {
   // Do work..
}

Adding rows dynamically with jQuery

I have Tried something like this and its works fine;

enter image description here

this is the html part :

<table class="dd" width="100%" id="data">
<tr>
<td>Year</td>
<td>:</td>
<td><select name="year1" id="year1" >
<option value="2012">2012</option>
<option value="2011">2011</option>
</select></td>
<td>Month</td>
<td>:</td>
<td width="17%"><select name="month1" id="month1">
  <option value="1">January</option>
  <option value="2">February</option>
  <option value="3">March</option>
  <option value="4">April</option>
  <option value="5">May</option>
  <option value="6">June</option>
  <option value="7">July</option>
  <option value="8">August</option>
  <option value="9">September</option>
  <option value="10">October</option>
  <option value="11">November</option>
  <option value="12">December</option>
</select></td>
<td width="7%">Week</td>
<td width="3%">:</td>
<td width="17%"><select name="week1" id="week1" >
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select></td>
<td width="8%">&nbsp;</td>
<td colspan="2">&nbsp;</td>
</tr>
<tr>
<td>Actual</td>
<td>:</td>
<td width="17%"><input name="actual1" id="actual1" type="text" /></td>
<td width="7%">Max</td>
<td width="3%">:</td>
<td><input name="max1" id="max1" type="text" /></td>
<td>Target</td>
<td>:</td>
<td><input name="target1" id="target1" type="text" /></td>
</tr>

this is Javascript part;

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
var currentItem = 1;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td>Year</td><td>:</td><td><select name="year'+currentItem+'" id="year'+currentItem+'" ><option value="2012">2012</option><option value="2011">2011</option></select></td><td>Month</td><td>:</td><td width="17%"><select name="month'+currentItem+'" id="month'+currentItem+'"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select></td><td width="7%">Week</td><td width="3%">:</td><td width="17%"><select name="week'+currentItem+'" id="week'+currentItem+'" ><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></td><td width="8%"></td><td colspan="2"></td></tr><tr><td>Actual</td><td>:</td><td width="17%"><input name="actual'+currentItem+'" id="actual'+currentItem+'" type="text" /></td><td width="7%">Max</td> <td width="3%">:</td><td><input name="max'+currentItem+'" id ="max'+currentItem+'"type="text" /></td><td>Target</td><td>:</td><td><input name="target'+currentItem+'" id="target'+currentItem+'" type="text" /></td></tr>';
  $('#data').append(strToAdd);

 });
 });

 //]]>
 </script>

Finaly PHP submit part:

    for( $i = 1; $i <= $count; $i++ )
{
    $year = $_POST['year'.$i];
    $month = $_POST['month'.$i];
    $week = $_POST['week'.$i];
    $actual = $_POST['actual'.$i];
    $max = $_POST['max'.$i];
    $target = $_POST['target'.$i];
    $extreme = $_POST['extreme'.$i];
    $que = "insert INTO table_name(id,year,month,week,actual,max,target) VALUES ('".$_POST['type']."','".$year."','".$month."','".$week."','".$actual."','".$max."','".$target."')";
    mysql_query($que);

}

you can find more details via Dynamic table row inserter

How to redirect Valgrind's output to a file?

By default, Valgrind writes its output to stderr. So you need to do something like:

valgrind a.out > log.txt 2>&1

Alternatively, you can tell Valgrind to write somewhere else; see http://valgrind.org/docs/manual/manual-core.html#manual-core.comment (but I've never tried this).

How to set value of input text using jQuery

For element with id

<input id="id_input_text16" type="text" placeholder="Ender Data"></input>

You can set the value as

$("#id_input_text16").val("testValue");

Documentation here.

Get query from java.sql.PreparedStatement

You could try calling toString() on the prepared statement after you've set the bind values.

PreparedStatement query = connection.prepareStatement(aSQLStatement);
System.out.println("Before : " + query.toString());
query.setString(1, "Hello");
query.setString(2, "World");
System.out.println("After : " + query.toString());

This works when you use the JDBC MySQL driver, but I'm not sure if it will in other cases. You may have to keep track of all the bindings you make and then print those out.

Sample output from above code.

Before : com.mysql.jdbc.JDBC4PreparedStatement@fa9cf: SELECT * FROM test WHERE blah1=** NOT SPECIFIED ** and blah2=** NOT SPECIFIED **
After : com.mysql.jdbc.JDBC4PreparedStatement@fa9cf: SELECT * FROM test WHERE blah1='Hello' and blah2='World'

Dockerfile if else condition with external arguments

The accepted answer may solve the question, but if you want multiline if conditions in the dockerfile, you can do that placing \ at the end of each line (similar to how you would do in a shell script) and ending each command with ;. You can even define someting like set -eux as the 1st command.

Example:

RUN set -eux; \
  if [ -f /path/to/file ]; then \
    mv /path/to/file /dest; \
  fi; \
  if [ -d /path/to/dir ]; then \
    mv /path/to/dir /dest; \
  fi

In your case:

FROM centos:7
ARG arg
RUN if [ -z "$arg" ] ; then \
    echo Argument not provided; \
  else \
    echo Argument is $arg; \
  fi

Then build with:

docker build -t my_docker . --build-arg arg=42

'True' and 'False' in Python

From 6.11. Boolean operations:

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

The key phrasing here that I think you are misunderstanding is "interpreted as false" or "interpreted as true". This does not mean that any of those values are identical to True or False, or even equal to True or False.

The expression '/bla/bla/bla' will be treated as true where a Boolean expression is expected (like in an if statement), but the expressions '/bla/bla/bla' is True and '/bla/bla/bla' == True will evaluate to False for the reasons in Ignacio's answer.

CSV parsing in Java - working example..?

Writing your own parser is fun, but likely you should have a look at Open CSV. It provides numerous ways of accessing the CSV and also allows to generate CSV. And it does handle escapes properly. As mentioned in another post, there is also a CSV-parsing lib in the Apache Commons, but that one isn't released yet.

HTML 5 video or audio playlist

Yep, you can simply point your src tag to a .m3u playlist file. A .m3u file is easy to construct -

#hosted mp3's need absolute paths but file system links can use relative paths
http://servername.com/path/to/mp3.mp3
http://servername.com/path/to/anothermp3.mp3
/path/to/local-mp3.mp3

-----UPDATE-----

Well, it turns out playlist m3u files are supported on the iPhone, but not on much else including Safari 5 which is kind of sad. I'm not sure about Android phones but I doubt they support it either since Chrome doesn't. Sorry for the misinformation.

Allow anything through CORS Policy

Just encountered with this issue in my rails application in production. A lot of answers here gave me hints and helped me to finally come to an answer that worked fine for me.

I am running Nginx and it was simple enough to just modify the my_app.conf file (where my_app is your app name). You can find this file in /etc/nginx/conf.d

If you do not have location / {} already you can just add it under server {}, then add add_header 'Access-Control-Allow-Origin' '*'; under location / {}.

The final format should look something like this:

server {
    server_name ...;
    listen ...;
    root ...;

    location / {
        add_header 'Access-Control-Allow-Origin' '*';
    }
}

Recursive directory listing in DOS

I like to use the following to get a nicely sorted listing of the current dir:

> dir . /s /b sortorder:N

How to concatenate multiple column values into a single column in Panda dataframe

Possibly the fastest solution is to operate in plain Python:

Series(
    map(
        '_'.join,
        df.values.tolist()
        # when non-string columns are present:
        # df.values.astype(str).tolist()
    ),
    index=df.index
)

Comparison against @MaxU answer (using the big data frame which has both numeric and string columns):

%timeit big['bar'].astype(str) + '_' + big['foo'] + '_' + big['new']
# 29.4 ms ± 1.08 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)


%timeit Series(map('_'.join, big.values.astype(str).tolist()), index=big.index)
# 27.4 ms ± 2.36 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Comparison against @derchambers answer (using their df data frame where all columns are strings):

from functools import reduce

def reduce_join(df, columns):
    slist = [df[x] for x in columns]
    return reduce(lambda x, y: x + '_' + y, slist[1:], slist[0])

def list_map(df, columns):
    return Series(
        map(
            '_'.join,
            df[columns].values.tolist()
        ),
        index=df.index
    )

%timeit df1 = reduce_join(df, list('1234'))
# 602 ms ± 39 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit df2 = list_map(df, list('1234'))
# 351 ms ± 12.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

ggplot geom_text font size control

Here are a few options for changing text / label sizes

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

The size in the geom_text changes the size of the geom_text labels.

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)


For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?

Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text sizes to theme sizes.

So a horrible fix for uniform sizes is to scale by this ratio

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)

Showing which files have changed between two revisions

If anyone is trying to generate a diff file from two branches :

git diff master..otherbranch > myDiffFile.diff

Checking if sys.argv[x] is defined

I use this - it never fails:

startingpoint = 'blah'
if sys.argv[1:]:
   startingpoint = sys.argv[1]

How to Lock Android App's Orientation to Portrait in Phones and Landscape in Tablets?

Set the Screen orientation to portrait in Manifest file under the activity Tag.

Here the example

You need to enter in every Activity

Add The Following Lines in Activity

for portrait

android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity"

for landscape

android:screenOrientation="landscape"
tools:ignore="LockedOrientationActivity"

Here The Example of MainActivity

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="org.thcb.app">
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity"
            android:screenOrientation="portrait"
            tools:ignore="LockedOrientationActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

<activity android:name=".MainActivity2"
            android:screenOrientation="landscape"
            tools:ignore="LockedOrientationActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

C# try catch continue execution

Do you mean you want to execute code in function1 regardless of whether function2 threw an exception or not? Have you looked at the finally-block? http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx

Rewrite left outer join involving multiple tables from Informix to Oracle

I'm guessing that you want something like

SELECT tab1.a, tab2.b, tab3.c, tab4.d
  FROM table1 tab1 
       JOIN table2 tab2 ON (tab1.fg = tab2.fg)
       LEFT OUTER JOIN table4 tab4 ON (tab1.ss = tab4.ss)
       LEFT OUTER JOIN table3 tab3 ON (tab4.xya = tab3.xya and tab3.desc = 'XYZ')
       LEFT OUTER JOIN table5 tab5 on (tab4.kk = tab5.kk AND
                                       tab3.dd = tab5.dd)

Python memory leaks

Have a look at this article: Tracing python memory leaks

Also, note that the garbage collection module actually can have debug flags set. Look at the set_debug function. Additionally, look at this code by Gnibbler for determining the types of objects that have been created after a call.

How to validate a file upload field using Javascript/jquery

In Firefox at least, the DOM inspector is telling me that the File input elements have a property called files. You should be able to check its length.

document.getElementById('myFileInput').files.length

failed to open stream: HTTP wrapper does not support writeable connections

you could use fopen() function.

some example:

$url = 'http://doman.com/path/to/file.mp4';
$destination_folder = $_SERVER['DOCUMENT_ROOT'].'/downloads/';


    $newfname = $destination_folder .'myfile.mp4'; //set your file ext

    $file = fopen ($url, "rb");

    if ($file) {
      $newf = fopen ($newfname, "a"); // to overwrite existing file

      if ($newf)
      while(!feof($file)) {
        fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );

      }
    }

    if ($file) {
      fclose($file);
    }

    if ($newf) {
      fclose($newf);
    }

Android: Bitmaps loaded from gallery are rotated in ImageView

The cursor should be closed after opening it.

Here is an example.

 public static int getOrientation(Context context, Uri selectedImage)
{
    int orientation = -1;
    Cursor cursor = context.getContentResolver().query(selectedImage,
            new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
    if (cursor.getCount() != 1)
       return orientation;

    cursor.moveToFirst();
    orientation = cursor.getInt(0);
    cursor.close(); // ADD THIS LINE
   return orientation;
}

"Please provide a valid cache path" error in laravel

Ensure the below folders in storage directory:

  • logs
  • framework
  • framework/cache
  • framework/cache/data
  • framework/sessions
  • framework/testing
  • framework/views

Below is a command-line snippet that does for you

cd storage
mkdir logs
mkdir framework
mkdir framework/cache && framework/cache/data
mkdir framework/sessions
mkdir framework/testing
mkdir framework/views
chgrp -R www-data ../storage
chown -R www-data ../storage

is there any IE8 only css hack?

Can you not use the hack you've already shown, and then use an IE7 and below hack to override it?

How to access child's state in React?

Its 2020 and lots of you will come here looking for a similar solution but with Hooks ( They are great! ) and with latest approaches in terms of code cleanliness and syntax.

So as previous answers had stated, the best approach to this kind of problem is to hold the state outside of child component fieldEditor. You could do that in multiple ways.

The most "complex" is with global context (state) that both parent and children could access and modify. Its a great solution when components are very deep in the tree hierarchy and so its costly to send props in each level.

In this case I think its not worth it, and more simple approach will bring us the results we want, just using the powerful React.useState().

Approach with React.useState() hook, way simpler than with Class components

As said we will deal with changes and store the data of our child component fieldEditor in our parent fieldForm. To do that we will send a reference to the function that will deal and apply the changes to the fieldForm state, you could do that with:

function FieldForm({ fields }) {
  const [fieldsValues, setFieldsValues] = React.useState({});
  const handleChange = (event, fieldId) => {
    let newFields = { ...fieldsValues };
    newFields[fieldId] = event.target.value;

    setFieldsValues(newFields);
  };

  return (
    <div>
      {fields.map(field => (
        <FieldEditor
          key={field}
          id={field}
          handleChange={handleChange}
          value={fieldsValues[field]}
        />
      ))}
      <div>{JSON.stringify(fieldsValues)}</div>
    </div>
  );
}

Note that React.useState({}) will return an array with position 0 being the value specified on call (Empty object in this case), and position 1 being the reference to the function that modifies the value.

Now with the child component, FieldEditor, you don't even need to create a function with a return statement, a lean constant with an arrow function will do!

const FieldEditor = ({ id, value, handleChange }) => (
  <div className="field-editor">
    <input onChange={event => handleChange(event, id)} value={value} />
  </div>
);

Aaaaand we are done, nothing more, with just these two slime functional components we have our end goal "access" our child FieldEditor value and show it off in our parent.

You could check the accepted answer from 5 years ago and see how Hooks made React code leaner (By a lot!).

Hope my answer helps you learn and understand more about Hooks, and if you want to check a working example here it is.

How to make VS Code to treat other file extensions as certain language?

In Visual Studio Code, you can add persistent file associations for language highlighting to your settings.json file like this:

// Place your settings in this file to overwrite the default settings
{
  "some_setting": custom_value,
  ...

  "files.associations": {
    "*.thor": "ruby",
    "*.jsx": "javascript",
    "Jenkinsfile*": "groovy"
  }
}

You can use Ctrl+Shift+p and then type settings JSON. Choose Preferences: Open Settings (JSON) to open your settings.json.

The Files: Associations feature was first introduced in Visual Studio Code version 1.0 (March 2016). Check the available wildcard patterns in the release notes and the known language strings in the documentation.

How can I let a user download multiple files when a button is clicked?

I've solved this a different way by using window.location. It works in Chrome, which fortunately is the only browser I had to support. Might be useful to someone. I'd initally used Dan's answer, which also needed the timeout I've used here or it only downloaded one file.

var linkArray = [];
linkArray.push("http://example.com/downloadablefile1");
linkArray.push("http://example.com/downloadablefile2");
linkArray.push("http://example.com/downloadablefile3");    

function (linkArray) {
  for (var i = 0; i < linkArray.length; i++) { 
    setTimeout(function (path) { window.location = path; }, 200 + i * 200, linkArray[i]);
  }        
};

vertical-align image in div

you don't need define positioning when you need vertical align center for inline and block elements you can take mentioned below idea:-

inline-elements :- <img style="vertical-align:middle" ...>
                   <span style="display:inline-block; vertical-align:middle"> foo<br>bar </span>  

block-elements :- <td style="vertical-align:middle"> ... </td>
                  <div style="display:table-cell; vertical-align:middle"> ... </div>

see the demo:- http://jsfiddle.net/Ewfkk/2/

Floating Point Exception C++ Why and what is it?

Lots of reasons for a floating point exception. Looking at your code your for loop seems to be a bit "incorrect". Looks like a possible division by zero.

for (i>0; i--;){
c= input%i;

Thats division by zero at some point since you are decrementing i.

How to change default Anaconda python environment

Create a shortcut of anaconda prompt onto desktop or taskbar, and then in the properties of that shortcut make sure u modify the last path in "Target:" to the path of ur environment:

C:\Users\BenBouali\Anaconda3\ WILL CHANGE INTO C:\Users\BenBouali\Anaconda3\envs\tensorflow-gpu

preview

and this way u can use that shortcut to open a certain environment when clicking it, you can add it to ur path too and now you'll be able to run it from windows run box by just typing in the name of the shortcut.

Generate 'n' unique random numbers within a range

If you just need sampling without replacement:

>>> import random
>>> random.sample(range(1, 100), 3)
[77, 52, 45]

random.sample takes a population and a sample size k and returns k random members of the population.

If you have to control for the case where k is larger than len(population), you need to be prepared to catch a ValueError:

>>> try:
...   random.sample(range(1, 2), 3)
... except ValueError:
...   print('Sample size exceeded population size.')
... 
Sample size exceeded population size

Re-run Spring Boot Configuration Annotation Processor to update generated metadata

For me, other answers didn't work. I had to go to open Files and do Invalidate caches and restart on Intellij. After that, everything worked fine again.

Can't create handler inside thread which has not called Looper.prepare()

All the answers above are correct, but I think this is the easiest example possible:

public class ExampleActivity extends Activity {
    private Handler handler;
    private ProgressBar progress;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        progress = (ProgressBar) findViewById(R.id.progressBar1);
        handler = new Handler();
    }

    public void clickAButton(View view) {
        // Do something that takes a while
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                handler.post(new Runnable() { // This thread runs in the UI
                    @Override
                    public void run() {
                        progress.setProgress("anything"); // Update the UI
                    }
                });
            }
        };
        new Thread(runnable).start();
    }
}

What this does is update a progress bar in the UI thread from a completely different thread passed through the post() method of the handler declared in the activity.

Hope it helps!

Is it safe to clean docker/overlay2/

I had this issue... It was the log that was huge. Logs are here :

/var/lib/docker/containers/<container id>/<container id>-json.log

You can manage this in the run command line or in the compose file. See there : Configure logging drivers

I personally added these 3 lines to my docker-compose.yml file :

my_container:
  logging:
    options:
      max-size: 10m

"Cannot start compilation: the output path is not specified for module..."

You have to define a path in the "Project compiler output" field in

File > Project Structure... > Project > Project compiler output

This path will be used to store all project compilation results.

Jenkins Host key verification failed

Change to the jenkins user and run the command manually:

git ls-remote -h [email protected]:person/projectmarket.git HEAD

You will get the standard SSH warning when first connecting to a new host via SSH:

The authenticity of host 'bitbucket.org (207.223.240.181)' can't be established.
RSA key fingerprint is 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40.
Are you sure you want to continue connecting (yes/no)?

Type yes and press Enter. The host key for bitbucket.org will now be added to the ~/.ssh/known_hosts file and you won't get this error in Jenkins anymore.

Reverse order of foreach list items

array_reverse() does not alter the source array, but returns a new array. (See array_reverse().) So you either need to store the new array first or just use function within the declaration of your for loop.

<?php 
    $input = array('a', 'b', 'c');
    foreach (array_reverse($input) as $value) {
        echo $value."\n";
    }
?>

The output will be:

c
b
a

So, to address to OP, the code becomes:

<?php
    $j=1;     
    foreach ( array_reverse($skills_nav) as $skill ) {
        $a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
        $a .= $skill->name;                 
        $a .= '</a></li>';
        echo $a;
        echo "\n";
        $j++;
}

Lastly, I'm going to guess that the $j was either a counter used in an initial attempt to get a reverse walk of $skills_nav, or a way to count the $skills_nav array. If the former, it should be removed now that you have the correct solution. If the latter, it can be replaced, outside of the loop, with a $j = count($skills_nav).

Exception.Message vs Exception.ToString()

Well, I'd say it depends what you want to see in the logs, doesn't it? If you're happy with what ex.Message provides, use that. Otherwise, use ex.toString() or even log the stack trace.

How to do multiline shell script in Ansible

https://support.ansible.com/hc/en-us/articles/201957837-How-do-I-split-an-action-into-a-multi-line-format-

mentions YAML line continuations.

As an example (tried with ansible 2.0.0.2):

---
- hosts: all
  tasks:
    - name: multiline shell command
      shell: >
        ls --color
        /home
      register: stdout

    - name: debug output
      debug: msg={{ stdout }}

The shell command is collapsed into a single line, as in ls --color /home

Reset MySQL root password using ALTER USER statement after install on Mac

ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

Use this line...

How to determine the version of android SDK installed in computer?

C:\ <path to android sdk> \tools\source.properties (open with notepad)

There you will find it.

How do you debug PHP scripts?

1) I use print_r(). In TextMate, I have a snippet for 'pre' which expands to this:

echo "<pre>";
print_r();
echo "</pre>";

2) I use Xdebug, but haven't been able to get the GUI to work right on my Mac. It at least prints out a readable version of the stack trace.

Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?

math.sqrt is the C implementation of square root and is therefore different from using the ** operator which implements Python's built-in pow function. Thus, using math.sqrt actually gives a different answer than using the ** operator and there is indeed a computational reason to prefer numpy or math module implementation over the built-in. Specifically the sqrt functions are probably implemented in the most efficient way possible whereas ** operates over a large number of bases and exponents and is probably unoptimized for the specific case of square root. On the other hand, the built-in pow function handles a few extra cases like "complex numbers, unbounded integer powers, and modular exponentiation".

See this Stack Overflow question for more information on the difference between ** and math.sqrt.

In terms of which is more "Pythonic", I think we need to discuss the very definition of that word. From the official Python glossary, it states that a piece of code or idea is Pythonic if it "closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages." In every single other language I can think of, there is some math module with basic square root functions. However there are languages that lack a power operator like ** e.g. C++. So ** is probably more Pythonic, but whether or not it's objectively better depends on the use case.

How do I mock an autowired @Value field in Spring with Mockito?

I'd like to suggest a related solution, which is to pass the @Value-annotated fields as parameters to the constructor, instead of using the ReflectionTestUtils class.

Instead of this:

public class Foo {

    @Value("${foo}")
    private String foo;
}

and

public class FooTest {

    @InjectMocks
    private Foo foo;

    @Before
    public void setUp() {
        ReflectionTestUtils.setField(Foo.class, "foo", "foo");
    }

    @Test
    public void testFoo() {
        // stuff
    }
}

Do this:

public class Foo {

    private String foo;

    public Foo(@Value("${foo}") String foo) {
        this.foo = foo;
    }
}

and

public class FooTest {

    private Foo foo;

    @Before
    public void setUp() {
        foo = new Foo("foo");
    }

    @Test
    public void testFoo() {
        // stuff
    }
}

Benefits of this approach: 1) we can instantiate the Foo class without a dependency container (it's just a constructor), and 2) we're not coupling our test to our implementation details (reflection ties us to the field name using a string, which could cause a problem if we change the field name).

Border Radius of Table is not working

border-collapse: separate !important; worked.

Thanks.

HTML

<table class="bordered">
    <thead>
        <tr>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <td><label>Value</label></td>
            <td><label>Value</label></td>
            <td><label>Value</label></td>
            <td><label>Value</label></td>
            <td><label>Value</label></td>                            
        </tr>
    </tbody>                    
</table>

CSS

table {
    border-collapse: separate !important;
    border-spacing: 0;
    width: 600px;
    margin: 30px;
}
.bordered {
    border: solid #ccc 1px;
    -moz-border-radius: 6px;
    -webkit-border-radius: 6px;
    border-radius: 6px;
    -webkit-box-shadow: 0 1px 1px #ccc;
    -moz-box-shadow: 0 1px 1px #ccc;
    box-shadow: 0 1px 1px #ccc;
}
.bordered tr:hover {
    background: #ECECEC;    
    -webkit-transition: all 0.1s ease-in-out;
    -moz-transition: all 0.1s ease-in-out;
    transition: all 0.1s ease-in-out;
}
.bordered td, .bordered th {
    border-left: 1px solid #ccc;
    border-top: 1px solid #ccc;
    padding: 10px;
    text-align: left;
}
.bordered th {
    background-color: #ECECEC;
    background-image: -webkit-gradient(linear, left top, left bottom, from(#F8F8F8), to(#ECECEC));
    background-image: -webkit-linear-gradient(top, #F8F8F8, #ECECEC);
    background-image: -moz-linear-gradient(top, #F8F8F8, #ECECEC);    
    background-image: linear-gradient(top, #F8F8F8, #ECECEC);
    -webkit-box-shadow: 0 1px 0 rgba(255,255,255,.8) inset;
    -moz-box-shadow:0 1px 0 rgba(255,255,255,.8) inset;
    box-shadow: 0 1px 0 rgba(255,255,255,.8) inset;
    border-top: none;
    text-shadow: 0 1px 0 rgba(255,255,255,.5);
}
.bordered td:first-child, .bordered th:first-child {
    border-left: none;
}
.bordered th:first-child {
    -moz-border-radius: 6px 0 0 0;
    -webkit-border-radius: 6px 0 0 0;
    border-radius: 6px 0 0 0;
}
.bordered th:last-child {
    -moz-border-radius: 0 6px 0 0;
    -webkit-border-radius: 0 6px 0 0;
    border-radius: 0 6px 0 0;
}
.bordered th:only-child{
    -moz-border-radius: 6px 6px 0 0;
    -webkit-border-radius: 6px 6px 0 0;
    border-radius: 6px 6px 0 0;
}
.bordered tr:last-child td:first-child {
    -moz-border-radius: 0 0 0 6px;
    -webkit-border-radius: 0 0 0 6px;
    border-radius: 0 0 0 6px;
}
.bordered tr:last-child td:last-child {
    -moz-border-radius: 0 0 6px 0;
    -webkit-border-radius: 0 0 6px 0;
    border-radius: 0 0 6px 0;
} 

jsFiddle

How to redirect back to form with input - Laravel 5

this will work definately !!!

  $v = Validator::make($request->all(),[
  'name' => ['Required','alpha']
  ]);

   if($v->passes()){
     print_r($request->name);
   }
   else{
     //this will return the errors & to check put "dd($errors);" in your blade(view)
     return back()->withErrors($v)->withInput();
   }

What are the rules about using an underscore in a C++ identifier?

The rules to avoid collision of names are both in the C++ standard (see Stroustrup book) and mentioned by C++ gurus (Sutter, etc.).

Personal rule

Because I did not want to deal with cases, and wanted a simple rule, I have designed a personal one that is both simple and correct:

When naming a symbol, you will avoid collision with compiler/OS/standard libraries if you:

  • never start a symbol with an underscore
  • never name a symbol with two consecutive underscores inside.

Of course, putting your code in an unique namespace helps to avoid collision, too (but won't protect against evil macros)

Some examples

(I use macros because they are the more code-polluting of C/C++ symbols, but it could be anything from variable name to class name)

#define _WRONG
#define __WRONG_AGAIN
#define RIGHT_
#define WRONG__WRONG
#define RIGHT_RIGHT
#define RIGHT_x_RIGHT

Extracts from C++0x draft

From the n3242.pdf file (I expect the final standard text to be similar):

17.6.3.3.2 Global names [global.names]

Certain sets of names and function signatures are always reserved to the implementation:

— Each name that contains a double underscore _ _ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.

— Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

But also:

17.6.3.3.5 User-defined literal suffixes [usrlit.suffix]

Literal suffix identifiers that do not start with an underscore are reserved for future standardization.

This last clause is confusing, unless you consider that a name starting with one underscore and followed by a lowercase letter would be Ok if not defined in the global namespace...

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

compile function -

  1. is called before the controller and link function.
  2. In compile function, you have the original template DOM so you can make changes on original DOM before AngularJS creates an instance of it and before a scope is created
  3. ng-repeat is perfect example - original syntax is template element, the repeated elements in HTML are instances
  4. There can be multiple element instances and only one template element
  5. Scope is not available yet
  6. Compile function can return function and object
  7. returning a (post-link) function - is equivalent to registering the linking function via the link property of the config object when the compile function is empty.
  8. returning an object with function(s) registered via pre and post properties - allows you to control when a linking function should be called during the linking phase. See info about pre-linking and post-linking functions below.

syntax

function compile(tElement, tAttrs, transclude) { ... }

controller

  1. called after the compile function
  2. scope is available here
  3. can be accessed by other directives (see require attribute)

pre - link

  1. The link function is responsible for registering DOM listeners as well as updating the DOM. It is executed after the template has been cloned. This is where most of the directive logic will be put.

  2. You can update the dom in the controller using angular.element but this is not recommended as the element is provided in the link function

  3. Pre-link function is used to implement logic that runs when angular js has already compiled the child elements but before any of the child element's post link have been called

post-link

  1. directive that only has link function, angular treats the function as a post link

  2. post will be executed after compile, controller and pre-link funciton, so that's why this is considered the safest and default place to add your directive logic

Sublime text 3. How to edit multiple lines?

Use CTRL+D at each line and it will find the matching words and select them then you can use multiple cursors.

You can also use find to find all the occurrences and then it would be multiple cursors too.

Matching exact string with JavaScript

Write your regex differently:

var r = /^a$/;
r.test('a'); // true
r.test('ba'); // false

Hide all elements with class using plain Javascript

I would propose a different approach. Instead of changing the properties of all objects manually, let's add a new CSS to the document:

/* License: CC0 */
var newStylesheet = document.createElement('style');
newStylesheet.textContent = '.classname { display: none; }';
document.head.appendChild(newStylesheet);

Run Button is Disabled in Android Studio

If you have changed jdk version then go to File->Project Structure->Select SDK Location from left bar->update JDK Location in editbar in right bar.

HTML5 Pre-resize images before uploading

I tackled this problem a few years ago and uploaded my solution to github as https://github.com/rossturner/HTML5-ImageUploader

robertc's answer uses the solution proposed in the Mozilla Hacks blog post, however I found this gave really poor image quality when resizing to a scale that was not 2:1 (or a multiple thereof). I started experimenting with different image resizing algorithms, although most ended up being quite slow or else were not great in quality either.

Finally I came up with a solution which I believe executes quickly and has pretty good performance too - as the Mozilla solution of copying from 1 canvas to another works quickly and without loss of image quality at a 2:1 ratio, given a target of x pixels wide and y pixels tall, I use this canvas resizing method until the image is between x and 2 x, and y and 2 y. At this point I then turn to algorithmic image resizing for the final "step" of resizing down to the target size. After trying several different algorithms I settled on bilinear interpolation taken from a blog which is not online anymore but accessible via the Internet Archive, which gives good results, here's the applicable code:

ImageUploader.prototype.scaleImage = function(img, completionCallback) {
    var canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);

    while (canvas.width >= (2 * this.config.maxWidth)) {
        canvas = this.getHalfScaleCanvas(canvas);
    }

    if (canvas.width > this.config.maxWidth) {
        canvas = this.scaleCanvasWithAlgorithm(canvas);
    }

    var imageData = canvas.toDataURL('image/jpeg', this.config.quality);
    this.performUpload(imageData, completionCallback);
};

ImageUploader.prototype.scaleCanvasWithAlgorithm = function(canvas) {
    var scaledCanvas = document.createElement('canvas');

    var scale = this.config.maxWidth / canvas.width;

    scaledCanvas.width = canvas.width * scale;
    scaledCanvas.height = canvas.height * scale;

    var srcImgData = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
    var destImgData = scaledCanvas.getContext('2d').createImageData(scaledCanvas.width, scaledCanvas.height);

    this.applyBilinearInterpolation(srcImgData, destImgData, scale);

    scaledCanvas.getContext('2d').putImageData(destImgData, 0, 0);

    return scaledCanvas;
};

ImageUploader.prototype.getHalfScaleCanvas = function(canvas) {
    var halfCanvas = document.createElement('canvas');
    halfCanvas.width = canvas.width / 2;
    halfCanvas.height = canvas.height / 2;

    halfCanvas.getContext('2d').drawImage(canvas, 0, 0, halfCanvas.width, halfCanvas.height);

    return halfCanvas;
};

ImageUploader.prototype.applyBilinearInterpolation = function(srcCanvasData, destCanvasData, scale) {
    function inner(f00, f10, f01, f11, x, y) {
        var un_x = 1.0 - x;
        var un_y = 1.0 - y;
        return (f00 * un_x * un_y + f10 * x * un_y + f01 * un_x * y + f11 * x * y);
    }
    var i, j;
    var iyv, iy0, iy1, ixv, ix0, ix1;
    var idxD, idxS00, idxS10, idxS01, idxS11;
    var dx, dy;
    var r, g, b, a;
    for (i = 0; i < destCanvasData.height; ++i) {
        iyv = i / scale;
        iy0 = Math.floor(iyv);
        // Math.ceil can go over bounds
        iy1 = (Math.ceil(iyv) > (srcCanvasData.height - 1) ? (srcCanvasData.height - 1) : Math.ceil(iyv));
        for (j = 0; j < destCanvasData.width; ++j) {
            ixv = j / scale;
            ix0 = Math.floor(ixv);
            // Math.ceil can go over bounds
            ix1 = (Math.ceil(ixv) > (srcCanvasData.width - 1) ? (srcCanvasData.width - 1) : Math.ceil(ixv));
            idxD = (j + destCanvasData.width * i) * 4;
            // matrix to vector indices
            idxS00 = (ix0 + srcCanvasData.width * iy0) * 4;
            idxS10 = (ix1 + srcCanvasData.width * iy0) * 4;
            idxS01 = (ix0 + srcCanvasData.width * iy1) * 4;
            idxS11 = (ix1 + srcCanvasData.width * iy1) * 4;
            // overall coordinates to unit square
            dx = ixv - ix0;
            dy = iyv - iy0;
            // I let the r, g, b, a on purpose for debugging
            r = inner(srcCanvasData.data[idxS00], srcCanvasData.data[idxS10], srcCanvasData.data[idxS01], srcCanvasData.data[idxS11], dx, dy);
            destCanvasData.data[idxD] = r;

            g = inner(srcCanvasData.data[idxS00 + 1], srcCanvasData.data[idxS10 + 1], srcCanvasData.data[idxS01 + 1], srcCanvasData.data[idxS11 + 1], dx, dy);
            destCanvasData.data[idxD + 1] = g;

            b = inner(srcCanvasData.data[idxS00 + 2], srcCanvasData.data[idxS10 + 2], srcCanvasData.data[idxS01 + 2], srcCanvasData.data[idxS11 + 2], dx, dy);
            destCanvasData.data[idxD + 2] = b;

            a = inner(srcCanvasData.data[idxS00 + 3], srcCanvasData.data[idxS10 + 3], srcCanvasData.data[idxS01 + 3], srcCanvasData.data[idxS11 + 3], dx, dy);
            destCanvasData.data[idxD + 3] = a;
        }
    }
};

This scales an image down to a width of config.maxWidth, maintaining the original aspect ratio. At the time of development this worked on iPad/iPhone Safari in addition to major desktop browsers (IE9+, Firefox, Chrome) so I expect it will still be compatible given the broader uptake of HTML5 today. Note that the canvas.toDataURL() call takes a mime type and image quality which will allow you to control the quality and output file format (potentially different to input if you wish).

The only point this doesn't cover is maintaining the orientation information, without knowledge of this metadata the image is resized and saved as-is, losing any metadata within the image for orientation meaning that images taken on a tablet device "upside down" were rendered as such, although they would have been flipped in the device's camera viewfinder. If this is a concern, this blog post has a good guide and code examples on how to accomplish this, which I'm sure could be integrated to the above code.

Set formula to a range of cells

I would update the formula in C1. Then copy the formula from C1 and paste it till C10...

Not sure about a more elegant solution

Range("C1").Formula = "=A1+B1"
Range("C1").Copy
Range("C1:C10").Pastespecial(XlPasteall)

Launch an app from within another (iPhone)

You can only launch apps that have registered a URL scheme. Then just like you open the SMS app by using sms:, you'll be able to open the app using their URL scheme.

There is a very good example available in the docs called LaunchMe which demonstrates this.

LaunchMe sample code as of 6th Nov 2017.

Jquery: how to trigger click event on pressing enter key

You were almost there. Here is what you can try though.

$(function(){
  $("#txtSearchProdAssign").keyup(function (e) {
    if (e.which == 13) {
      $('input[name="butAssignProd"]').trigger('click');
    }
  });
});

I have used trigger() to execute click and bind it on the keyup event insted of keydown because click event comprises of two events actually i.e. mousedown then mouseup. So to resemble things same as possible with keydown and keyup.

Here is a Demo

Class constants in python

Expanding on betabandido's answer, you could write a function to inject the attributes as constants into the module:

def module_register_class_constants(klass, attr_prefix):
    globals().update(
        (name, getattr(klass, name)) for name in dir(klass) if name.startswith(attr_prefix)
    )

class Animal(object):
    SIZE_HUGE = "Huge"
    SIZE_BIG = "Big"

module_register_class_constants(Animal, "SIZE_")

class Horse(Animal):
    def printSize(self):
        print SIZE_BIG

PSQLException: current transaction is aborted, commands ignored until end of transaction block

I think that the best solution is to use java.sql.Savepoint.

Before you execute a query which can throw SQLException, use the method Connection.setSavepoint(), and if an exception is thrown you only rollback to this savepoint, not the whole transaction.

Example code:

Connection conn = null;
Savepoint savepoint = null;
try {
    conn = getConnection();
    savepoint = conn.setSavepoint();
    //execute some query
} catch(SQLException e) {
    if(conn != null && savepoint != null) {
        conn.rollback(savepoint);
    }
} finally {
   if(conn != null) {
      try {
          conn.close();
      } catch(SQLException e) {}

   }
}

Check if number is prime number

I've implemented a different method to check for primes because:

  • Most of these solutions keep iterating through the same multiple unnecessarily (for example, they check 5, 10, and then 15, something that a single % by 5 will test for).
  • A % by 2 will handle all even numbers (all integers ending in 0, 2, 4, 6, or 8).
  • A % by 5 will handle all multiples of 5 (all integers ending in 5).
  • What's left is to test for even divisions by integers ending in 1, 3, 7, or 9. But the beauty is that we can increment by 10 at a time, instead of going up by 2, and I will demonstrate a solution that is threaded out.
  • The other algorithms are not threaded out, so they don't take advantage of your cores as much as I would have hoped.
  • I also needed support for really large primes, so I needed to use the BigInteger data-type instead of int, long, etc.

Here is my implementation:

public static BigInteger IntegerSquareRoot(BigInteger value)
{
    if (value > 0)
    {
        int bitLength = value.ToByteArray().Length * 8;
        BigInteger root = BigInteger.One << (bitLength / 2);
        while (!IsSquareRoot(value, root))
        {
            root += value / root;
            root /= 2;
        }
        return root;
    }
    else return 0;
}

private static Boolean IsSquareRoot(BigInteger n, BigInteger root)
{
    BigInteger lowerBound = root * root;
    BigInteger upperBound = (root + 1) * (root + 1);
    return (n >= lowerBound && n < upperBound);
}

static bool IsPrime(BigInteger value)
{
    Console.WriteLine("Checking if {0} is a prime number.", value);
    if (value < 3)
    {
        if (value == 2)
        {
            Console.WriteLine("{0} is a prime number.", value);
            return true;
        }
        else
        {
            Console.WriteLine("{0} is not a prime number because it is below 2.", value);
            return false;
        }
    }
    else
    {
        if (value % 2 == 0)
        {
            Console.WriteLine("{0} is not a prime number because it is divisible by 2.", value);
            return false;
        }
        else if (value == 5)
        {
            Console.WriteLine("{0} is a prime number.", value);
            return true;
        }
        else if (value % 5 == 0)
        {
            Console.WriteLine("{0} is not a prime number because it is divisible by 5.", value);
            return false;
        }
        else
        {
            // The only way this number is a prime number at this point is if it is divisible by numbers ending with 1, 3, 7, and 9.
            AutoResetEvent success = new AutoResetEvent(false);
            AutoResetEvent failure = new AutoResetEvent(false);
            AutoResetEvent onesSucceeded = new AutoResetEvent(false);
            AutoResetEvent threesSucceeded = new AutoResetEvent(false);
            AutoResetEvent sevensSucceeded = new AutoResetEvent(false);
            AutoResetEvent ninesSucceeded = new AutoResetEvent(false);
            BigInteger squareRootedValue = IntegerSquareRoot(value);
            Thread ones = new Thread(() =>
            {
                for (BigInteger i = 11; i <= squareRootedValue; i += 10)
                {
                    if (value % i == 0)
                    {
                        Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
                        failure.Set();
                    }
                }
                onesSucceeded.Set();
            });
            ones.Start();
            Thread threes = new Thread(() =>
            {
                for (BigInteger i = 3; i <= squareRootedValue; i += 10)
                {
                    if (value % i == 0)
                    {
                        Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
                        failure.Set();
                    }
                }
                threesSucceeded.Set();
            });
            threes.Start();
            Thread sevens = new Thread(() =>
            {
                for (BigInteger i = 7; i <= squareRootedValue; i += 10)
                {
                    if (value % i == 0)
                    {
                        Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
                        failure.Set();
                    }
                }
                sevensSucceeded.Set();
            });
            sevens.Start();
            Thread nines = new Thread(() =>
            {
                for (BigInteger i = 9; i <= squareRootedValue; i += 10)
                {
                    if (value % i == 0)
                    {
                        Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
                        failure.Set();
                    }
                }
                ninesSucceeded.Set();
            });
            nines.Start();
            Thread successWaiter = new Thread(() =>
            {
                AutoResetEvent.WaitAll(new WaitHandle[] { onesSucceeded, threesSucceeded, sevensSucceeded, ninesSucceeded });
                success.Set();
            });
            successWaiter.Start();
            int result = AutoResetEvent.WaitAny(new WaitHandle[] { success, failure });
            try
            {
                successWaiter.Abort();
            }
            catch { }
            try
            {
                ones.Abort();
            }
            catch { }
            try
            {
                threes.Abort();
            }
            catch { }
            try
            {
                sevens.Abort();
            }
            catch { }
            try
            {
                nines.Abort();
            }
            catch { }
            if (result == 1)
            {
                return false;
            }
            else
            {
                Console.WriteLine("{0} is a prime number.", value);
                return true;
            }
        }
    }
}

Update: If you want to implement a solution with trial division more rapidly, you might consider having a cache of prime numbers. A number is only prime if it is not divisible by other prime numbers that are up to the value of its square root. Other than that, you might consider using the probabilistic version of the Miller-Rabin primality test to check for a number's primality if you are dealing with large enough values (taken from Rosetta Code in case the site ever goes down):

// Miller-Rabin primality test as an extension method on the BigInteger type.
// Based on the Ruby implementation on this page.
public static class BigIntegerExtensions
{
  public static bool IsProbablePrime(this BigInteger source, int certainty)
  {
    if(source == 2 || source == 3)
      return true;
    if(source < 2 || source % 2 == 0)
      return false;

    BigInteger d = source - 1;
    int s = 0;

    while(d % 2 == 0)
    {
      d /= 2;
      s += 1;
    }

    // There is no built-in method for generating random BigInteger values.
    // Instead, random BigIntegers are constructed from randomly generated
    // byte arrays of the same length as the source.
    RandomNumberGenerator rng = RandomNumberGenerator.Create();
    byte[] bytes = new byte[source.ToByteArray().LongLength];
    BigInteger a;

    for(int i = 0; i < certainty; i++)
    {
      do
      {
        // This may raise an exception in Mono 2.10.8 and earlier.
        // http://bugzilla.xamarin.com/show_bug.cgi?id=2761
        rng.GetBytes(bytes);
        a = new BigInteger(bytes);
      }
      while(a < 2 || a >= source - 2);

      BigInteger x = BigInteger.ModPow(a, d, source);
      if(x == 1 || x == source - 1)
        continue;

      for(int r = 1; r < s; r++)
      {
        x = BigInteger.ModPow(x, 2, source);
        if(x == 1)
          return false;
        if(x == source - 1)
          break;
      }

      if(x != source - 1)
        return false;
    }

    return true;
  }
}

Better way to remove specific characters from a Perl string

You've misunderstood how character classes are used:

$varTemp =~ s/[\$#@~!&*()\[\];.,:?^ `\\\/]+//g;

does the same as your regex (assuming you didn't mean to remove ' characters from your strings).

Edit: The + allows several of those "special characters" to match at once, so it should also be faster.

Should I use `import os.path` or `import os`?

Common sense works here: os is a module, and os.path is a module, too. So just import the module you want to use:

  • If you want to use functionalities in the os module, then import os.

  • If you want to use functionalities in the os.path module, then import os.path.

  • If you want to use functionalities in both modules, then import both modules:

    import os
    import os.path
    

For reference:

List<Object> and List<?>

Why cant I do this:

List<Object> object = new List<Object>();

You can't do this because List is an interface, and interfaces cannot be instantiated. Only (concrete) classes can be. Examples of concrete classes implementing List include ArrayList, LinkedList etc.

Here is how one would create an instance of ArrayList:

List<Object> object = new ArrayList<Object>();

I have a method that returns a List<?>, how would I turn that into a List<Object>

Show us the relevant code and I'll update the answer.

Create a rounded button / button with border-radius in Flutter

Now we have Icon Button to achieve rounded button click and overlay. However background color is not yet available but the same can be achieved by Circle avatar widget as follows:

CircleAvatar(
            backgroundColor: const Color(0xffF4F3FA),
            child: IconButton(
              onPressed: () => FlushbarHelper.createInformation(
                      message: 'Work in progress...')
                  .show(context),
              icon: Icon(Icons.more_vert),
            ),
          ),

Hope this helps some one.

Stashing only staged changes in git - is it possible?

TL;DR; git stash-staged

After creating an alias:

git config --global alias.stash-staged '!bash -c "git stash -- \$(git diff --staged --name-only)"'

Here git diff returns list of --staged files --name-only
And then we pass this list as pathspec to git stash commad.

From man git stash:

git stash [--] [<pathspec>...]

<pathspec>...
   The new stash entry records the modified states only for the files
   that match the pathspec. The index entries and working tree
   files are then rolled back to the state in HEAD only for these
   files, too, leaving files that do not match the pathspec intact.

How to call one shell script from another shell script?

Assume the new file is "/home/satya/app/app_specific_env" and the file contents are as follows

#!bin/bash

export FAV_NUMBER="2211"

Append this file reference to ~/.bashrc file

source /home/satya/app/app_specific_env

When ever you restart the machine or relogin, try echo $FAV_NUMBER in the terminal. It will output the value.

Just in case if you want to see the effect right away, source ~/.bashrc in the command line.

Nesting optgroups in a dropdownlist/select

I think if you have something that structured and complex, you might consider something other than a single drop-down box.

AngularJS: How to run additional code after AngularJS has rendered a template?

i've had to do this quite often. i have a directive and need to do some jquery stuff after model stuff is fully loaded into the DOM. so i put my logic in the link: function of the directive and wrap the code in a setTimeout(function() { ..... }, 1); the setTimout will fire after the DOM is loaded and 1 milisecond is the shortest amount of time after DOM is loaded before code would execute. this seems to work for me but i do wish angular raised an event once a template was done loading so that directives used by that template could do jquery stuff and access DOM elements. hope this helps.

How can I create a dynamically sized array of structs?

In C++, use a vector. It's like an array but you can easily add and remove elements and it will take care of allocating and deallocating memory for you.

I know the title of the question says C, but you tagged your question with C and C++...

Select n random rows from SQL Server table

Depending on your needs, TABLESAMPLE will get you nearly as random and better performance. this is available on MS SQL server 2005 and later.

TABLESAMPLE will return data from random pages instead of random rows and therefore deos not even retrieve data that it will not return.

On a very large table I tested

select top 1 percent * from [tablename] order by newid()

took more than 20 minutes.

select * from [tablename] tablesample(1 percent)

took 2 minutes.

Performance will also improve on smaller samples in TABLESAMPLE whereas it will not with newid().

Please keep in mind that this is not as random as the newid() method but will give you a decent sampling.

See the MSDN page.

Facebook share link - can you customize the message body text?

Facebook does not allow you to change the "What's on your mind?" text box, unless of course you're developing an application for use on Facebook.

How to check whether a file is empty or not?

import os    
os.path.getsize(fullpathhere) > 0

How to declare std::unique_ptr and what is the use of it?

The constructor of unique_ptr<T> accepts a raw pointer to an object of type T (so, it accepts a T*).

In the first example:

unique_ptr<int> uptr (new int(3));

The pointer is the result of a new expression, while in the second example:

unique_ptr<double> uptr2 (pd);

The pointer is stored in the pd variable.

Conceptually, nothing changes (you are constructing a unique_ptr from a raw pointer), but the second approach is potentially more dangerous, since it would allow you, for instance, to do:

unique_ptr<double> uptr2 (pd);
// ...
unique_ptr<double> uptr3 (pd);

Thus having two unique pointers that effectively encapsulate the same object (thus violating the semantics of a unique pointer).

This is why the first form for creating a unique pointer is better, when possible. Notice, that in C++14 we will be able to do:

unique_ptr<int> p = make_unique<int>(42);

Which is both clearer and safer. Now concerning this doubt of yours:

What is also not clear to me, is how pointers, declared in this way will be different from the pointers declared in a "normal" way.

Smart pointers are supposed to model object ownership, and automatically take care of destroying the pointed object when the last (smart, owning) pointer to that object falls out of scope.

This way you do not have to remember doing delete on objects allocated dynamically - the destructor of the smart pointer will do that for you - nor to worry about whether you won't dereference a (dangling) pointer to an object that has been destroyed already:

{
    unique_ptr<int> p = make_unique<int>(42);
    // Going out of scope...
}
// I did not leak my integer here! The destructor of unique_ptr called delete

Now unique_ptr is a smart pointer that models unique ownership, meaning that at any time in your program there shall be only one (owning) pointer to the pointed object - that's why unique_ptr is non-copyable.

As long as you use smart pointers in a way that does not break the implicit contract they require you to comply with, you will have the guarantee that no memory will be leaked, and the proper ownership policy for your object will be enforced. Raw pointers do not give you this guarantee.

Why do some functions have underscores "__" before and after the function name?

Added an example to understand the use of __ in python. Here is the list of All __

https://docs.python.org/3/genindex-all.html#_

Certain classes of identifiers (besides keywords) have special meanings. Any use of * names, in any other context, that does not follow explicitly documented use, is subject to breakage without warning

Access restriction using __

"""
Identifiers:
-  Contain only (A-z, 0-9, and _ )
-  Start with a lowercase letter or _.
-  Single leading _ :  private
-  Double leading __ :  strong private
-  Start & End  __ : Language defined Special Name of Object/ Method
-  Class names start with an uppercase letter.
-

"""


class BankAccount(object):
    def __init__(self, name, money, password):
        self.name = name            # Public
        self._money = money         # Private : Package Level
        self.__password = password  # Super Private

    def earn_money(self, amount):
        self._money += amount
        print("Salary Received: ", amount, " Updated Balance is: ", self._money)

    def withdraw_money(self, amount):
        self._money -= amount
        print("Money Withdraw: ", amount, " Updated Balance is: ", self._money)

    def show_balance(self):
        print(" Current Balance is: ", self._money)


account = BankAccount("Hitesh", 1000, "PWD")  # Object Initalization

# Method Call
account.earn_money(100)

# Show Balance
print(account.show_balance())

print("PUBLIC ACCESS:", account.name)  # Public Access

# account._money is accessible because it is only hidden by convention
print("PROTECTED ACCESS:", account._money)  # Protected Access

# account.__password will throw error but account._BankAccount__password will not
# because __password is super private
print("PRIVATE ACCESS:", account._BankAccount__password)

# Method Call
account.withdraw_money(200)

# Show Balance
print(account.show_balance())

# account._money is accessible because it is only hidden by convention
print(account._money)  # Protected Access

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

You can modify the path on the config.xml file in the default directory

<projectNamingStrategy class="jenkins.model.ProjectNamingStrategy$DefaultProjectNamingStrategy"/>
<workspaceDir>D:/Workspace/${ITEM_FULL_NAME}</workspaceDir>
<buildsDir>D:/Logs/${ITEM_ROOTDIR}/Build</buildsDir>

Float vs Decimal in ActiveRecord

I remember my CompSci professor saying never to use floats for currency.

The reason for that is how the IEEE specification defines floats in binary format. Basically, it stores sign, fraction and exponent to represent a Float. It's like a scientific notation for binary (something like +1.43*10^2). Because of that, it is impossible to store fractions and decimals in Float exactly.

That's why there is a Decimal format. If you do this:

irb:001:0> "%.47f" % (1.0/10)
=> "0.10000000000000000555111512312578270211815834045" # not "0.1"!

whereas if you just do

irb:002:0> (1.0/10).to_s
=> "0.1" # the interprer rounds the number for you

So if you are dealing with small fractions, like compounding interests, or maybe even geolocation, I would highly recommend Decimal format, since in decimal format 1.0/10 is exactly 0.1.

However, it should be noted that despite being less accurate, floats are processed faster. Here's a benchmark:

require "benchmark" 
require "bigdecimal" 

d = BigDecimal.new(3) 
f = Float(3)

time_decimal = Benchmark.measure{ (1..10000000).each { |i| d * d } } 
time_float = Benchmark.measure{ (1..10000000).each { |i| f * f } }

puts time_decimal 
#=> 6.770960 seconds 
puts time_float 
#=> 0.988070 seconds

Answer

Use float when you don't care about precision too much. For example, some scientific simulations and calculations only need up to 3 or 4 significant digits. This is useful in trading off accuracy for speed. Since they don't need precision as much as speed, they would use float.

Use decimal if you are dealing with numbers that need to be precise and sum up to correct number (like compounding interests and money-related things). Remember: if you need precision, then you should always use decimal.

Plotting in a non-blocking way with Matplotlib

A lot of these answers are super inflated and from what I can find, the answer isn't all that difficult to understand.

You can use plt.ion() if you want, but I found using plt.draw() just as effective

For my specific project I'm plotting images, but you can use plot() or scatter() or whatever instead of figimage(), it doesn't matter.

plt.figimage(image_to_show)
plt.draw()
plt.pause(0.001)

Or

fig = plt.figure()
...
fig.figimage(image_to_show)
fig.canvas.draw()
plt.pause(0.001)

If you're using an actual figure.
I used @krs013, and @Default Picture's answers to figure this out
Hopefully this saves someone from having launch every single figure on a separate thread, or from having to read these novels just to figure this out

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

"Class.forName()" returns the Class-Type for the given name. "newInstance()" does return an instance of this class.

On the type you can't call directly any instance methods but can only use reflection for the class. If you want to work with an object of the class you have to create an instance of it (same as calling "new MyClass()").

Example for "Class.forName()"

Class myClass = Class.forName("test.MyClass");
System.out.println("Number of public methods: " + myClass.getMethods().length);

Example for "Class.forName().newInstance()"

MyClass myClass = (MyClass) Class.forName("test.MyClass").newInstance();
System.out.println("String representation of MyClass instance: " + myClass.toString());

how to use free cloud database with android app?

As Wingman said, Google App Engine is a great solution for your scenario.

You can get some information about GAE+Android here: https://developers.google.com/eclipse/docs/appengine_connected_android

And from this Google IO 2012 session: http://www.youtube.com/watch?v=NU_wNR_UUn4

How to get the request parameters in Symfony 2?

Inside a controller:

$request = $this->getRequest();
$username = $request->get('username');

Jersey Exception : SEVERE: A message body reader for Java class

Try adding:

<dependency>
    <groupId>com.owlike</groupId>
    <artifactId>genson</artifactId>
    <version>1.4</version>
</dependency>

Also this problem may occur if you're using HTTP GET with message body so in this case adding jersey-json lib, @XmlRootElement or modifying web.xml won't help. You should use URL QueryParam or HTTP POST.

Unable to create migrations after upgrading to ASP.NET Core 2.0

I had this problem and this solved By Set -> Web Application(Included Program.cs) Project to -> "Set as Startup Project"

Then run -> add-migration initial -verbose

in Package Manager Console

Set as Startup Project

Pass correct "this" context to setTimeout callback?

If you're using underscore, you can use bind.

E.g.

if (this.options.destroyOnHide) {
     setTimeout(_.bind(this.tip.destroy, this), 1000);
}

How to store file name in database, with other info while uploading image to server using PHP?

You have an ID for each photo so my suggestion is you rename the photo. For example you rename it by the date

<?php
 $date = getdate();
 $name .= $date[hours];
 $name .= $date[minutes];
 $name .= $date[seconds];
 $name .= $date[year];
 $name .= $date[mon];
 $name .= $date[mday];
?>

note: don't forget the file extension of your file or you can generate random string for the photo, but I would not recommend that. I would also recommend you to check the file extension before you upload it to your directory.

<?php 
if ((($_FILES["photo"]["type"] == "image/jpeg")
            || ($_FILES["photo"]["type"] == "image/pjpg"))
            && ($_FILES["photo"]["size"] < 100000000))
            {
                move_uploaded_file($_FILES["photo"]["tmp_name"], $target.$name);

                if(mysql_query("your query"))
                {
                    //success handling
                }
                else 
                {
                    //failed handling
                }
            }
            else
            {
                //error handling
            }
?>

Hope this might help.

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

Or use a cast with split to uniform type of str

unique, counts = numpy.unique(str(a).split(), return_counts=True)

How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

Here is a tested and working generic solution:

I have a large number UpDownNumeric controls, some in the main form, some in groupboxes within the form. I want only the one last selected control to change back-color to green, for which I first set all others to white, using this method: (can also expand to grandchildren)

    public void setAllUpDnBackColorWhite()
    {
        //To set the numericUpDown background color of the selected control to white: 
        //and then the last selected control will change to green.

        foreach (Control cont in this.Controls)
        {
           if (cont.HasChildren)
            {
                foreach (Control contChild in cont.Controls)
                    if (contChild.GetType() == typeof(NumericUpDown))
                        contChild.BackColor = Color.White;
            }
            if (cont.GetType() == typeof(NumericUpDown))
                cont.BackColor = Color.White;
       }
    }   

PHP header() redirect with POST variables

It would be beneficial to verify the form's data before sending it via POST. You should create a JavaScript function to check the form for errors and then send the form. This would prevent the data from being sent over and over again, possibly slowing the browser and using transfer volume on the server.

Edit:

If security is a concern, performing an AJAX request to verify the data would be the best way. The response from the AJAX request would determine whether the form should be submitted.

Converting unix time into date-time via excel

in case the above does not work for you. for me this did not for some reasons;

the UNIX numbers i am working on are from the Mozilla place.sqlite dates.

to make it work : i splitted the UNIX cells into two cells : one of the first 10 numbers (the date) and the other 4 numbers left (the seconds i believe)

Then i used this formula, =(A1/86400)+25569 where A1 contains the cell with the first 10 number; and it worked

How to show Page Loading div until the page has finished loading?

Create a <div> element that contains your loading message, give the <div> an ID, and then when your content has finished loading, hide the <div>:

$("#myElement").css("display", "none");

...or in plain JavaScript:

document.getElementById("myElement").style.display = "none";

How to customize the background/border colors of a grouped table view cell?

I have been having problems with this and tried lots of combinations of things as I noticed that for some cells it worked fine but not for others.

Strangely I found out that it is possible to set the cell.backgroundColor to lightGrayColor and all works perfectly - but blueColor caused me problems of not updating the outside edges.

Unless it is really important to use green - perhaps you might want to try this. It might be that this is a feature to get people to use only grey colours when indicating a cell is selected.

How to include libraries in Visual Studio 2012?

Typically you need to do 5 things to include a library in your project:

1) Add #include statements necessary files with declarations/interfaces, e.g.:

#include "library.h"

2) Add an include directory for the compiler to look into

-> Configuration Properties/VC++ Directories/Include Directories (click and edit, add a new entry)

3) Add a library directory for *.lib files:

-> project(on top bar)/properties/Configuration Properties/VC++ Directories/Library Directories (click and edit, add a new entry)

4) Link the lib's *.lib files

-> Configuration Properties/Linker/Input/Additional Dependencies (e.g.: library.lib;

5) Place *.dll files either:

-> in the directory you'll be opening your final executable from or into Windows/system32

Make HTML5 video poster be same size as video itself

I had a similar issue and just fixed it by creating an image with the same aspect ratio as my video (16:9). My width is set to 100% on the video tag and now the image (320 x 180) fits perfectly. Hope that helps!

Deleting all records in a database table

If your model is called BlogPost, it would be:

BlogPost.all.map(&:destroy)

XPath test if node value is number

I'm not trying to provide a yet another alternative solution, but a "meta view" to this problem.

Answers already provided by Oded and Dimitre Novatchev are correct but what people really might mean with phrase "value is a number" is, how would I say it, open to interpretation.

In a way it all comes to this bizarre sounding question: "how do you want to express your numeric values?"

XPath function number() processes numbers that have

  • possible leading or trailing whitespace
  • preceding sign character only on negative values
  • dot as an decimal separator (optional for integers)
  • all other characters from range [0-9]

Note that this doesn't include expressions for numerical values that

  • are expressed in exponential form (e.g. 12.3E45)
  • may contain sign character for positive values
  • have a distinction between positive and negative zero
  • include value for positive or negative infinity

These are not just made up criteria. An element with content that is according to schema a valid xs:float value might contain any of the above mentioned characteristics. Yet number() would return value NaN.

So answer to your question "How i can check with XPath if a node value is number?" is either "Use already mentioned solutions using number()" or "with a single XPath 1.0 expression, you can't". Think about the possible number formats you might encounter, and if needed, write some kind of logic for validation/number parsing. Within XSLT processing, this can be done with few suitable extra templates, for example.

PS. If you only care about non-zero numbers, the shortest test is

<xsl:if test="number(myNode)">
    <!-- myNode is a non-zero number -->
</xsl:if>

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

Also, you can use event.preventDefault inside onclick attribute.

<a href="#" onclick="event.preventDefault(); doSmth();">doSmth</a>

No need to write exstra click event.

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Typescript ReferenceError: exports is not defined

for me, removing "esModuleInterop": true from tsconfig.json did the trick.

How to add not null constraint to existing column in MySQL

Just use an ALTER TABLE... MODIFY... query and add NOT NULL into your existing column definition. For example:

ALTER TABLE Person MODIFY P_Id INT(11) NOT NULL;

A word of caution: you need to specify the full column definition again when using a MODIFY query. If your column has, for example, a DEFAULT value, or a column comment, you need to specify it in the MODIFY statement along with the data type and the NOT NULL, or it will be lost. The safest practice to guard against such mishaps is to copy the column definition from the output of a SHOW CREATE TABLE YourTable query, modify it to include the NOT NULL constraint, and paste it into your ALTER TABLE... MODIFY... query.

How do I check the difference, in seconds, between two dates?

if you want to compute differences between two known dates, use total_seconds like this:

import datetime as dt

a = dt.datetime(2013,12,30,23,59,59)
b = dt.datetime(2013,12,31,23,59,59)

(b-a).total_seconds()

86400.0

#note that seconds doesn't give you what you want:
(b-a).seconds

0

How to redirect to Login page when Session is expired in Java web application?

Check for session is new.

HttpSession session = request.getSession(false);
if (!session.isNew()) {
  // Session is valid
}
else {
  //Session has expired - redirect to login.jsp
}

How to replace all occurrences of a string in Javascript?

If you are trying to ensure that the string you are looking for won't exist even after the replacement, you need to use a loop.

For example:

var str = 'test aabcbc';
str = str.replace(/abc/g, '');

When complete, you will still have 'test abc'!

The simplest loop to solve this would be:

var str = 'test aabcbc';
while (str != str.replace(/abc/g, '')){
   str.replace(/abc/g, '');
}

But that runs the replacement twice for each cycle. Perhaps (at risk of being voted down) that can be combined for a slightly more efficient but less readable form:

var str = 'test aabcbc';
while (str != (str = str.replace(/abc/g, ''))){}
// alert(str); alerts 'test '!

This can be particularly useful when looking for duplicate strings.
For example, if we have 'a,,,b' and we wish to remove all duplicate commas.
[In that case, one could do .replace(/,+/g,','), but at some point the regex gets complex and slow enough to loop instead.]

Make child div stretch across width of page

You can do:

margin-left: -50%;
margin-right: -50%;

"NoClassDefFoundError: Could not initialize class" error

Realised that I was using OpenJDK when I saw this error. Fixed it once I installed the Oracle JDK instead.

Make Bootstrap 3 Tabs Responsive

The solution is just 3 lines:

@media only screen and (max-width: 479px) {
   .nav-tabs > li {
      width: 100%;
   }
}

..but you have to accept the idea of tabs that wrap to more lines in other dimensions.

Of course you can achieve a horizontal scrolling area with white-space: nowrap trick but the scrollbars look ugly on desktops so you have to write js code and the whole thing starts becoming no trivial at all!

Unable to open a file with fopen()

How are you running the file? Is it from the command line or from an IDE? The directory that your executable is in is not necessarily your working directory.

Try using the full path name in the fopen and see if that fixes it. If so, then the problem is as described.

For example:

file = fopen("c:\\MyDirectory\\TestFile1.txt", "r");
file = fopen("/full/path/to/TestFile1.txt", "r");

Or open up a command window and navigate to the directory where your executable is, then run it manually.

As an aside, you can insert a simple (for Windows or Linux/UNIX/BSD/etc respectively):

system ("cd")
system("pwd")

before the fopen to show which directory you're actually in.

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

1920 is a generic error code that means the service didn't start. My hunch is this:

http://blog.iswix.com/2008/09/different-year-same-problem.html

To confirm, with the installer on the abort, retry, ignore, cancel dialog up... go into services.msc and set the username and password manually. If you get a message saying the user was granted logon as service right, try hitting retry on the MSI dialog and see if it starts.

It could also be missing dependencies or exceptions being thrown in your code.

ReactJS: Warning: setState(...): Cannot update during an existing state transition

That usually happens when you call

onClick={this.handleButton()} - notice the () instead of:

onClick={this.handleButton} - notice here we are not calling the function when we initialize it

How to get a variable value if variable name is stored as string?

For my fellow zsh users, the way to accomplish the same thing as the accepted answer is to use:

${(P)a}

It is appropriately called Parameter name replacement

This forces the value of the parameter name to be interpreted as a further parameter name, whose value will be used where appropriate. Note that flags set with one of the typeset family of commands (in particular case transformations) are not applied to the value of name used in this fashion.

If used with a nested parameter or command substitution, the result of that will be taken as a parameter name in the same way. For example, if you have ‘foo=bar’ and ‘bar=baz’, the strings ${(P)foo}, ${(P)${foo}}, and ${(P)$(echo bar)} will be expanded to ‘baz’.

Likewise, if the reference is itself nested, the expression with the flag is treated as if it were directly replaced by the parameter name. It is an error if this nested substitution produces an array with more than one word. For example, if ‘name=assoc’ where the parameter assoc is an associative array, then ‘${${(P)name}[elt]}’ refers to the element of the associative subscripted ‘elt’.

How to force reloading php.ini file?

TL;DR; If you're still having trouble after restarting apache or nginx, also try restarting the php-fpm service.

The answers here don't always satisfy the requirement to force a reload of the php.ini file. On numerous occasions I've taken these steps to be rewarded with no update, only to find the solution I need after also restarting the php-fpm service. So if restarting apache or nginx doesn't trigger a php.ini update although you know the files are updated, try restarting php-fpm as well.

To restart the service:

Note: prepend sudo if not root

Using SysV Init scripts directly:

/etc/init.d/php-fpm restart        # typical
/etc/init.d/php5-fpm restart       # debian-style
/etc/init.d/php7.0-fpm restart     # debian-style PHP 7

Using service wrapper script

service php-fpm restart        # typical
service php5-fpm restart       # debian-style
service php7.0-fpm restart.    # debian-style PHP 7

Using Upstart (e.g. ubuntu):

restart php7.0-fpm         # typical (ubuntu is debian-based) PHP 7
restart php5-fpm           # typical (ubuntu is debian-based)
restart php-fpm            # uncommon

Using systemd (newer servers):

systemctl restart php-fpm.service        # typical
systemctl restart php5-fpm.service       # uncommon
systemctl restart php7.0-fpm.service     # uncommon PHP 7

Or whatever the equivalent is on your system.

The above commands taken directly from this server fault answer

Pandas group-by and sum

df.groupby(['Fruit','Name'])['Number'].sum()

You can select different columns to sum numbers.

How do I add my new User Control to the Toolbox or a new Winform?

Assuming I understand what you mean:

  1. If your UserControl is in a library you can add this to you Toolbox using

    Toolbox -> right click -> Choose Items -> Browse

    Select your assembly with the UserControl.

  2. If the UserControl is part of your project you only need to build the entire solution. After that, your UserControl should appear in the toolbox.

In general, it is not possible to add a Control from Solution Explorer, only from the Toolbox.

Enter image description here

How to convert date format to DD-MM-YYYY in C#

string formatted = date.ToString("dd-MM-yyyy");

will do it.

Here is a good reference for different formats.

Android eclipse DDMS - Can't access data/data/ on phone to pull files

If it retures "permission denied" on adb shell -> su...

Go to "Developer Options" -> Root access -> "Apps and ADB"

Custom designing EditText

edit_text.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#ffffff" />
    <corners android:radius="5dp"/>
    <stroke android:width="2dip" android:color="@color/button_color_submit" />
</shape>

use here

<EditText
 -----
 ------
 android:background="@drawable/edit_text.xml"
/>

How do I make a LinearLayout scrollable?

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center|left"
        android:orientation="vertical">

        Your views go here...

    </LinearLayout>

</ScrollView>

how to use DEXtoJar

You can decompile your .apk files and download online.

http://www.javadecompilers.com/

IE Driver download location Link for Selenium

Use the below link to download IE Driver latest version

IE Driver

Stop form refreshing page on submit

This problem becomes more complex when you give the user 2 possibilities to submit the form:

  1. by clicking on an ad hoc button
  2. by hitting Enter key

In such a case you will need a function which detects the pressed key in which you will submit the form if Enter key was hit.

And now comes the problem with IE (in any case version 11) Remark: This issue does not exist with Chrome nor with FireFox !

  • When you click the submit button the form is submitted once; fine.
  • When you hit Enter the form is submitted twice ... and your servlet will be executed twice. If you don't have PRG (post redirect get) architecture serverside the result might be unexpected.

Even though the solution looks trivial, it tooks me many hours to solve this problem, so I hope it might be usefull for other folks. This solution has been successfully tested, among others, on IE (v 11.0.9600.18426), FF (v 40.03) & Chrome (v 53.02785.143 m 64 bit)

The source code HTML & js are in the snippet. The principle is described there. Warning:

You can't test it in the snippet because the post action is not defined and hitting Enter key might interfer with stackoverflow.

If you faced this issue, then just copy/paste js code to your environment and adapt it to your context.

_x000D_
_x000D_
/*_x000D_
 * inForm points to the form_x000D_
 */_x000D_
var inForm = document.getElementById('idGetUserFrm');_x000D_
/*_x000D_
 * IE submits the form twice_x000D_
 * To avoid this the boolean isSumbitted is:_x000D_
 *  1) initialized to false when the form is displayed 4 the first time_x000D_
 * Remark: it is not the same event as "body load"_x000D_
 */_x000D_
var isSumbitted = false;_x000D_
_x000D_
function checkEnter(e) {_x000D_
  if (e && e.keyCode == 13) {_x000D_
    inForm.submit();_x000D_
    /*_x000D_
      * 2) set to true after the form submission was invoked_x000D_
      */_x000D_
    isSumbitted = true;_x000D_
  }_x000D_
}_x000D_
function onSubmit () {_x000D_
  if (isSumbitted) {_x000D_
    /*_x000D_
    * 3) reset to false after the form submission executed_x000D_
    */_x000D_
    isSumbitted = false;_x000D_
    return false;_x000D_
  }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<form id="idGetUserFrm" method="post" action="servletOrSomePhp" onsubmit="return onSubmit()">_x000D_
   First name:<br>_x000D_
   <input type="text" name="firstname" value="Mickey">_x000D_
   <input type="submit" value="Submit">_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Keyboard shortcut to comment lines in Sublime Text 3

This is a keyboard internationalisation issue.

On a standard US QWERTY keyboard, as used in Australia where Sublime Text is made, / is readily available: US QWERTY keyboard

This is not the case with many other keyboards. Take for example the German QWERTZ keyboard. One needs to hit SHIFT+7 to get a /. This is why commenting does not work properly on these keyboards. German QWERTZ keyboard

Changing the user keybindings to those listed below, will work for the German QWERTZ keyboard.

{ "keys": ["ctrl+7"], "command": "toggle_comment", "args": { "block": false } },
{ "keys": ["ctrl+shift+7"], "command": "toggle_comment", "args": { "block": true } }

If the problems are occurring with still a different keyboard layout, change the keybindings accordingly.

jquery live hover

$('.hoverme').live('mouseover mouseout', function(event) {
  if (event.type == 'mouseover') {
    // do something on mouseover
  } else {
    // do something on mouseout
  }
});

http://api.jquery.com/live/

ASP.NET Custom Validator Client side & Server Side validation not firing

Thanks for that info on the ControlToValidate LukeH!

What I was trying to do in my code was to only ensure that some text field A has some text in the field when text field B has a particular value. Otherwise, A can be blank or whatever else. Getting rid of the ControlToValidate="A" in my mark up fixed the issue for me.

Cheers!

How can I resize an image dynamically with CSS as the browser width/height changes?

Try

.img{
   width:100vw; /* Matches to the Viewport Width */
   height:auto;
   max-width:100% !important;
}

Only works with display block and inline block, this has no effect on flex items as I've just spent ages trying to find out.

Comma separated results in SQL

If you're stuck with SQL Server <2017, you can use GroupConcat. The syntax and the performance is far better than the FOR XML PATH sollution.

Installation:

-- https://codeplexarchive.blob.core.windows.net/archive/projects/groupconcat/groupconcat.zip
create assembly [GroupConcat] from 0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C01030058898C510000000000000000E00002210B010B00001E000000080000000000007E3D0000002000000040000000000010002000000002000004000000000000000400000000000000008000000002000000000000030040850000100000100000000010000010000000000000100000000000000000000000243D000057000000004000003804000000000000000000000000000000000000006000000C00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E74657874000000841D000000200000001E000000020000000000000000000000000000200000602E7273726300000038040000004000000006000000200000000000000000000000000000400000402E72656C6F6300000C0000000060000000020000002600000000000000000000000000004000004200000000000000000000000000000000603D0000000000004800000002000500C02C00006410000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003202731100000A7D010000042A0000001330040047000000010000110F01281200000A2D3D0F01281300000A0A027B01000004066F1400000A2C1A027B01000004250B06250C07086F1500000A17586F1600000A2A027B0100000406176F1700000A2A001B30050089000000020000110F017B010000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B01000004076F1400000A2C29027B01000004250D072513040911046F1500000A0F017B01000004076F1500000A586F1600000A2B19027B01000004070F017B01000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A0000000110000002000D006D7A000E000000001B3003009B00000003000011027B010000043989000000027B010000046F1D00000A16317B731E00000A0A027B010000046F1800000A0D2B341203281900000A0B160C2B1E061201281A00000A6F1F00000A260672010000706F1F00000A260817580C081201282000000A32D81203281B00000A2DC3DE0E1203FE160300001B6F1C00000ADC06066F2100000A1759176F2200000A6F2300000A282400000A2A14282400000A2A000110000002002B00416C000E00000000133003003900000004000011036F2500000A0A0206732600000A7D01000004160B2B1B027B01000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF2A0000001B3002005B0000000500001103027B010000046F1D00000A6F2800000A027B010000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC2A000110000002001D002F4C000E000000001330020024000000060000110F01FE16060000016F2300000A0A027B0300000406282A00000A2C0702067D030000042A5E02731100000A7D02000004027E2B00000A7D030000042A133004004F000000010000110F01281200000A2D450F01281300000A0A027B02000004066F1400000A2C1B027B02000004250B06250C07086F1500000A17586F1600000A2B0D027B0200000406176F1700000A020428070000062A001B300500A300000002000011027B03000004282C00000A2C0D020F017B030000047D030000040F017B020000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B02000004076F1400000A2C29027B02000004250D072513040911046F1500000A0F017B02000004076F1500000A586F1600000A2B19027B02000004070F017B02000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A0001100000020027006D94000E000000001B300300B300000003000011027B0200000439A1000000027B020000046F1D00000A163E90000000731E00000A0A027B020000046F1800000A0D2B351203281900000A0B160C2B1F061201281A00000A6F1F00000A2606027B030000046F1F00000A260817580C081201282000000A32D71203281B00000A2DC2DE0E1203FE160300001B6F1C00000ADC06066F2100000A027B030000046F2D00000A59027B030000046F2D00000A6F2200000A6F2300000A282400000A2A14282400000A2A000110000002002E004270000E00000000133003004500000004000011036F2500000A0A0206732600000A7D02000004160B2B1B027B02000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF02036F2700000A7D030000042A0000001B300200670000000500001103027B020000046F1D00000A6F2800000A027B020000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC03027B030000046F2900000A2A000110000002001D002F4C000E000000001330020024000000060000110F01FE16060000016F2300000A0A027B0500000406282A00000A2C0702067D050000042AEA027B060000042D310F01282E00000A172E150F01282E00000A182E0B7205000070732F00000A7A020F01282E00000A283000000A7D060000042A7A02731100000A7D04000004027E2B00000A7D0500000402167D060000042A00001330040056000000010000110F01281200000A2D4C0F01281300000A0A027B04000004066F1400000A2C1B027B04000004250B06250C07086F1500000A17586F1600000A2B0D027B0400000406176F1700000A0204280E0000060205280F0000062A00001B300500B800000002000011027B05000004282C00000A2C0D020F017B050000047D05000004027B060000042D0D020F017B060000047D060000040F017B040000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B04000004076F1400000A2C29027B04000004250D072513040911046F1500000A0F017B04000004076F1500000A586F1600000A2B19027B04000004070F017B04000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A0110000002003C006DA9000E000000001B300300D700000007000011027B0400000439C5000000027B040000046F1D00000A163EB4000000731E00000A0B027B06000004183313027B04000004731E000006733100000A0A2B0C027B04000004733200000A0A066F3300000A13042B351204283400000A0C160D2B1F071202281A00000A6F1F00000A2607027B050000046F1F00000A260917580D091202282000000A32D71204283500000A2DC2DE0E1204FE160600001B6F1C00000ADC07076F2100000A027B050000046F2D00000A59027B050000046F2D00000A6F2200000A6F2300000A282400000A2A14282400000A2A0001100000020052004294000E00000000133003005100000004000011036F2500000A0A0206732600000A7D04000004160B2B1B027B04000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF02036F2700000A7D0500000402036F3600000A7D060000042A0000001B300200730000000500001103027B040000046F1D00000A6F2800000A027B040000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC03027B050000046F2900000A03027B060000046F3700000A2A000110000002001D002F4C000E00000000EA027B080000042D310F01282E00000A172E150F01282E00000A182E0B7205000070732F00000A7A020F01282E00000A283000000A7D080000042A4E02731100000A7D0700000402167D080000042A00133004004F000000010000110F01281200000A2D450F01281300000A0A027B07000004066F1400000A2C1B027B07000004250B06250C07086F1500000A17586F1600000A2B0D027B0700000406176F1700000A020428160000062A001B3005009E00000002000011027B080000042D0D020F017B080000047D080000040F017B070000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B07000004076F1400000A2C29027B07000004250D072513040911046F1500000A0F017B07000004076F1500000A586F1600000A2B19027B07000004070F017B07000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A000001100000020022006D8F000E000000001B300300C800000008000011027B0700000439B6000000027B070000046F1D00000A163EA5000000731E00000A0B027B08000004183313027B07000004731E000006733100000A0A2B0C027B07000004733200000A0A066F3300000A13052B3A1205283400000A0C1202281A00000A0D1613042B1A07096F1F00000A260772010000706F1F00000A2611041758130411041202282000000A32DB1205283500000A2DBDDE0E1205FE160600001B6F1C00000ADC07076F2100000A1759176F2200000A6F2300000A282400000A2A14282400000A2A01100000020052004799000E00000000133003004500000004000011036F2500000A0A0206732600000A7D07000004160B2B1B027B07000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF02036F3600000A7D080000042A0000001B300200670000000500001103027B070000046F1D00000A6F2800000A027B070000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC03027B080000046F3700000A2A000110000002001D002F4C000E000000002204036F3800000A2A1E02283900000A2A00000042534A4201000100000000000C00000076322E302E35303732370000000005006C000000C4060000237E0000300700006405000023537472696E677300000000940C00006C00000023555300000D0000100000002347554944000000100D00005403000023426C6F6200000000000000020000015717A2090900000000FA253300160000010000002500000006000000080000001E0000001E0000000500000039000000180000000800000003000000040000000400000006000000010000000300000000000A00010000000000060081007A000A00B20097000600C3007A000600E500CA000600F100CA000A001F010A0106004E0144010600600144010A009C010A010A00CA01970006001702050206002E02050206004B02050206006A02050206008302050206009C0205020600B70205020600D202050206000A03EB0206001E030502060057033703060077033703060095037A000A00AB0397000A00CC0397000600D303EB020600E903EB0217002B04000006004404CA00060070047A0006009A048E040600EB047A00060014057A0006001E057A000E002D05CA0006004005CA008F002B0400000000000001000000000001000100092110001A00270005000100010009211000330027000500020007000921100042002700050004000E00092110005200270005000700160001001000610027000D0009001D000100FE0010000100FE0010000100730139000100FE001000010073013900010095014F000100FE001000010095014F005020000000008600050118000100602000000000860029011C000100B4200000000086003401220002005C210000000086003A0128000300142200000000E6015B012D0004005C2200000000E6016D0133000500D4220000000081087D011C00060004230000000086000501180007001C2300000000860029013C000700782300000000860034014400090038240000000086003A0128000A00082500000000E6015B012D000B005C2500000000E6016D0133000C00E0250000000081087D011C000D001026000000008108A40152000E004B26000000008600050118000F006C26000000008600290158000F00D026000000008600340162001200A4270000000086003A0128001300982800000000E6015B012D001400F82800000000E6016D01330015008829000000008108A40152001600C329000000008600050118001700D82900000000860029016D001700342A000000008600340175001900F02A0000000086003A0128001A00D42B00000000E6015B012D001B00282C00000000E6016D0133001C00AC2C00000000E601B6017B001D00B52C000000008618BE0118001F0000000100C40100000100DC0100000000000000000100E20100000100E40100000100E60100000100C40100000200EC0100000100DC0100000000000000000100E20100000100E40100000100E60100000100E60100000100C40100000200EC0100000300F60100000100DC0100000000000000000100E20100000100E40100000100E60100000100C40100000200F60100000100DC0100000000000000000100E20100000100E40100000100010200000200030202000900030009000400090005000900060006005100BE0118005900BE01BA006100BE01BA006900BE01BA007100BE01BA007900BE01BA008100BE01BA008900BE01BA009100BE01BA009900BE01BF00A100BE01BA00A900BE01C400B100BE011800B900BE011800C100BE01C900D100BE0142011400BE0118003100F4034F013100FF035301140009045701140015045D0114001E0464011400270464011400360477011C005304890124005F049B011C0067044F01F1007C04180014008404B701F900BE011800F900A804BB012400FF03C101F900AF04B701F900BA04C6011900C10453013100CA04CD013900D604B7011400BE01C4003900E004530141006D01C40041006D01BA000101F204F9010101000539000101060503020101AF04B7014900FF0308020901BE01BA00110126050C022C00BE0119022C00BE012C022C0036043902340053048901340067044F0139004E05080241006D0167020101570587021900BE01180024000B0081002E006B0035032E002B000E032E0013008C022E001B009D022E0023000E032E003B0014032E0033008C022E0043000E032E0053000E032E0063002C0343007B00CF0063007B00CF0064000B00940083007B00CF00A3007B00CF00E4000B00810004010B00A70044010B009400E4010B00810004020B00A70064020B009400E4020B00810044030B0094006C01A001D301E501EA01FF014D026C0203000100040002000500040000008B014A0000008B014A000000AF0168000000AF01680001000700030001000E00050001000F0007000100160009000A004801820194011102450204800000010000000D13F49F00000000000027000000020000000000000000000000010071000000000002000000000000000000000001008B000000000002000000000000000000000001007A000000000000000000003C4D6F64756C653E0047726F7570436F6E6361742E646C6C0047524F55505F434F4E4341540047726F7570436F6E6361740047524F55505F434F4E4341545F440047524F55505F434F4E4341545F44530047524F55505F434F4E4341545F530052657665727365436F6D7061726572006D73636F726C69620053797374656D0056616C7565547970650053797374656D2E44617461004D6963726F736F66742E53716C5365727665722E536572766572004942696E61727953657269616C697A65004F626A6563740053797374656D2E436F6C6C656374696F6E732E47656E657269630049436F6D706172657260310044696374696F6E61727960320076616C75657300496E69740053797374656D2E446174612E53716C54797065730053716C537472696E6700416363756D756C617465004D65726765005465726D696E6174650053797374656D2E494F0042696E61727952656164657200526561640042696E6172795772697465720057726974650064656C696D69746572007365745F44656C696D697465720044656C696D6974657200736F727442790053716C42797465007365745F536F7274427900536F7274427900436F6D70617265002E63746F720056414C55450053716C46616365744174747269627574650047726F7570007200770076616C75650044454C494D4954455200534F52545F4F52444552007800790053797374656D2E5265666C656374696F6E00417373656D626C795469746C6541747472696275746500417373656D626C794465736372697074696F6E41747472696275746500417373656D626C79436F6E66696775726174696F6E41747472696275746500417373656D626C79436F6D70616E7941747472696275746500417373656D626C7950726F6475637441747472696275746500417373656D626C79436F7079726967687441747472696275746500417373656D626C7954726164656D61726B41747472696275746500417373656D626C7943756C747572654174747269627574650053797374656D2E52756E74696D652E496E7465726F70536572766963657300436F6D56697369626C6541747472696275746500417373656D626C7956657273696F6E4174747269627574650053797374656D2E52756E74696D652E436F6D70696C6572536572766963657300436F6D70696C6174696F6E52656C61786174696F6E734174747269627574650052756E74696D65436F6D7061746962696C6974794174747269627574650053657269616C697A61626C654174747269627574650053716C55736572446566696E656441676772656761746541747472696275746500466F726D6174005374727563744C61796F7574417474726962757465004C61796F75744B696E64006765745F49734E756C6C006765745F56616C756500436F6E7461696E734B6579006765745F4974656D007365745F4974656D0041646400456E756D657261746F7200476574456E756D657261746F72004B657956616C7565506169726032006765745F43757272656E74006765745F4B6579004D6F76654E6578740049446973706F7361626C6500446973706F7365006765745F436F756E740053797374656D2E5465787400537472696E674275696C64657200417070656E64006765745F4C656E6774680052656D6F766500546F537472696E67006F705F496D706C696369740052656164496E7433320052656164537472696E6700537472696E67006F705F496E657175616C69747900456D7074790049734E756C6C4F72456D70747900457863657074696F6E00436F6E7665727400546F4279746500536F7274656444696374696F6E6172796032004944696374696F6E617279603200526561644279746500436F6D70617265546F0000000000032C00006549006E00760061006C0069006400200053006F0072007400420079002000760061006C00750065003A00200075007300650020003100200066006F007200200041005300430020006F00720020003200200066006F007200200044004500530043002E0000008002D97266C26949A672EA780F71C8980008B77A5C561934E08905151211010E0706151215020E0803200001052001011119052001011108042000111905200101121D05200101122102060E072002011119111905200101110C04280011190206050520010111250920030111191119112505200101111004280011250720020111191125052001011114052002080E0E12010001005408074D617853697A65A00F000012010001005408074D617853697A65FFFFFFFF12010001005408074D617853697A6504000000042001010E0420010102042001010805200101116572010002000000050054080B4D61784279746553697A65FFFFFFFF5402124973496E76617269616E74546F4E756C6C73015402174973496E76617269616E74546F4475706C696361746573005402124973496E76617269616E74546F4F726465720154020D49734E756C6C4966456D7074790105200101116D06151215020E08032000020320000E0520010213000620011301130007200201130013010A07030E151215020E080E0A2000151171021300130106151171020E080A2000151175021300130106151175020E080420001300160705151175020E080E151171020E08151215020E080E03200008052001127D0E0420001301062002127D080805000111190E110704127D151175020E0808151171020E0804070208080E0702151175020E08151171020E08050002020E0E0307010E040001020E032000050400010505071512808D020E08122002011512809102130013011512110113000C2001011512809102130013010B20001511809502130013010715118095020E081907051512808D020E08127D151175020E080815118095020E0804200101051A07061512808D020E08127D151175020E080E0815118095020E08042001080E1001000B47726F7570436F6E63617400007001006B537472696E6720636F6E636174656E6174696F6E2061676772656761746520666F722053514C205365727665722E2044726F702D696E207265706C6163656D656E7420666F72206275696C742D696E204D7953514C2047524F55505F434F4E4341542066756E74696F6E2E000005010000000017010012436F7079726967687420C2A920203230313100000801000800000000001E01000100540216577261704E6F6E457863657074696F6E5468726F7773014C3D000000000000000000006E3D0000002000000000000000000000000000000000000000000000603D00000000000000000000000000000000000000005F436F72446C6C4D61696E006D73636F7265652E646C6C0000000000FF25002000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100100000001800008000000000000000000000000000000100010000003000008000000000000000000000000000000100000000004800000058400000E00300000000000000000000E00334000000560053005F00560045005200530049004F004E005F0049004E0046004F0000000000BD04EFFE0000010000000100F49F0D1300000100F49F0D133F000000000000000400000002000000000000000000000000000000440000000100560061007200460069006C00650049006E0066006F00000000002400040000005400720061006E0073006C006100740069006F006E00000000000000B00440030000010053007400720069006E006700460069006C00650049006E0066006F0000001C0300000100300030003000300030003400620030000000F0006C00010043006F006D006D0065006E0074007300000053007400720069006E006700200063006F006E0063006100740065006E006100740069006F006E002000610067006700720065006700610074006500200066006F0072002000530051004C0020005300650072007600650072002E002000440072006F0070002D0069006E0020007200650070006C006100630065006D0065006E007400200066006F00720020006200750069006C0074002D0069006E0020004D007900530051004C002000470052004F00550050005F0043004F004E004300410054002000660075006E00740069006F006E002E00000040000C000100460069006C0065004400650073006300720069007000740069006F006E0000000000470072006F007500700043006F006E00630061007400000040000F000100460069006C006500560065007200730069006F006E000000000031002E0030002E0034003800370037002E00340030003900340038000000000040001000010049006E007400650072006E0061006C004E0061006D0065000000470072006F007500700043006F006E006300610074002E0064006C006C0000004800120001004C006500670061006C0043006F007000790072006900670068007400000043006F0070007900720069006700680074002000A90020002000320030003100310000004800100001004F0072006900670069006E0061006C00460069006C0065006E0061006D0065000000470072006F007500700043006F006E006300610074002E0064006C006C00000038000C000100500072006F0064007500630074004E0061006D00650000000000470072006F007500700043006F006E00630061007400000044000F000100500072006F006400750063007400560065007200730069006F006E00000031002E0030002E0034003800370037002E00340030003900340038000000000048000F00010041007300730065006D0062006C0079002000560065007200730069006F006E00000031002E0030002E0034003800370037002E003400300039003400380000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000C000000803D00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 with permission_set = safe;
create aggregate [dbo].[GROUP_CONCAT]    (@VALUE [nvarchar](4000))                                                      returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT];
create aggregate [dbo].[GROUP_CONCAT_D]  (@VALUE [nvarchar](4000), @DELIMITER [nvarchar](4))                            returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT_D];
create aggregate [dbo].[GROUP_CONCAT_DS] (@VALUE [nvarchar](4000), @DELIMITER [nvarchar](4), @SORT_ORDER [tinyint])     returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT_DS];
create aggregate [dbo].[GROUP_CONCAT_S]  (@VALUE [nvarchar](4000), @SORT_ORDER [tinyint])                               returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT_S];

go

Usage:

declare @liststr varchar(max)
select @liststr = dbo.group_concat_d(institutionname, ',')
from education
where studentnumber = '111'
group by studentnumber;
select @liststr

GroupConcat does not support ordering, though. You could use PIVOT, CTE's and windows functions if you need ordering:

drop table if exists #students;
create table #students (
    name        varchar(20),
    institution varchar(20),
    year        int -- order by year
)
go

insert into #students(name, institution, year)
values
    ('Simon', 'INSTITUTION1', 2005),
    ('Simon', 'INSTITUTION2', 2008);

with cte as (
    select name,
           institution,
           rn = row_number() over (partition by name order by year)
    from #students
)
select name,
       [1] +
       isnull((',' + [2]), '') +
       isnull((',' + [3]), '') +
       isnull((',' + [4]), '') +
       isnull((',' + [5]), '') +
       isnull((',' + [6]), '') +
       isnull((',' + [7]), '') +
       isnull((',' + [8]), '') +
       isnull((',' + [9]), '') +
       isnull((',' + [10]), '') +
       isnull((',' + [11]), '') +
       isnull((',' + [12]), '') +
       isnull((',' + [13]), '') +
       isnull((',' + [14]), '') +
       isnull((',' + [15]), '') +
       isnull((',' + [16]), '') +
       isnull((',' + [17]), '') +
       isnull((',' + [18]), '') +
       isnull((',' + [19]), '') +
       isnull((',' + [20]), '')
from cte
    pivot (
    max(institution)
    for rn in ([1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20])
    ) as piv

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

Debug/run standard java in Visual Studio Code IDE and OS X?

I can tell you for Windows.

  1. Install Java Extension Pack and Code Runner Extension from VS Code Extensions.

  2. Edit your java home location in VS Code settings, "java.home": "C:\\Program Files\\Java\\jdk-9.0.4".

  3. Check if javac is recognized in VS Code internal terminal. If this check fails, try opening VS Code as administrator.

  4. Create a simple Java program in Main.java file as:

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world");     
    }
}

Note: Do not add package in your main class.

  1. Right click anywhere on the java file and select run code.

  2. Check the output in the console.

Done, hope this helps.

How to update (append to) an href in jquery?

$("a.directions-link").attr("href", $("a.directions-link").attr("href")+"...your additions...");

React-router urls don't work when refreshing or writing manually

Solution for Preact with preact-router

Works with refresh and direct access

For those discovering this via Google, here's a demo of preact-router + hash history:

const { h, Component, render } = preact; /** @jsx h */
const { Router } = preactRouter;
const { createHashHistory } = History;
const App = () => (
    <div>
        <AddressBar />

        <Router history={createHashHistory()}>
            <div path="/">
                <p>
                    all paths in preact-router are still /normal/urls.
                    using hash history rewrites them to /#/hash/urls
                </p>
                Example: <a href="/page2">page 2</a>
            </div>
            <div path="/page2">
                <p>Page Two</p>
                <a href="/">back to home</a><br/>
            </div>
        </Router>
    </div>
);

jsfiddle

syntax for creating a dictionary into another dictionary in python

dict1 = {}

dict1['dict2'] = {}

print dict1

>>> {'dict2': {},}

this is commonly known as nesting iterators into other iterators I think

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

I was getting this too, had me baffled for a while, even with the module and types already installed and reloading my IDE several times.

What fixed it in my case was terminating terminal processes, removing node_modules, clearing the node package manager cache and doing a fresh install then re-loading the editor.

Why does a base64 encoded string have an = sign at the end

http://www.hcidata.info/base64.htm

Encoding "Mary had" to Base 64

In this example we are using a simple text string ("Mary had") but the principle holds no matter what the data is (e.g. graphics file). To convert each 24 bits of input data to 32 bits of output, Base 64 encoding splits the 24 bits into 4 chunks of 6 bits. The first problem we notice is that "Mary had" is not a multiple of 3 bytes - it is 8 bytes long. Because of this, the last group of bits is only 4 bits long. To remedy this we add two extra bits of '0' and remember this fact by putting a '=' at the end. If the text string to be converted to Base 64 was 7 bytes long, the last group would have had 2 bits. In this case we would have added four extra bits of '0' and remember this fact by putting '==' at the end.

How do I read input character-by-character in Java?

Wrap your input stream in a buffered reader then use the read method to read one byte at a time until the end of stream.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Reader {

    public static void main(String[] args) throws IOException {

        BufferedReader buffer = new BufferedReader(
                 new InputStreamReader(System.in));
        int c = 0;
        while((c = buffer.read()) != -1) {
            char character = (char) c;          
            System.out.println(character);          
        }       
    }   
}