Programs & Examples On #Execution

Refers to the act of running a process.

Oracle query execution time

I'd recommend looking at consistent gets/logical reads as a better proxy for 'work' than run time. The run time can be skewed by what else is happening on the database server, how much stuff is in the cache etc.

But if you REALLY want SQL executing time, the V$SQL view has both CPU_TIME and ELAPSED_TIME.

WPF Image Dynamically changing Image source during runtime

Try Stretch="UniformToFill" on the Image

Can I pass an argument to a VBScript (vbs file launched with cscript)?

Inside of VBS you can access parameters with

Wscript.Arguments(0)
Wscript.Arguments(1)

and so on. The number of parameter:

Wscript.Arguments.Count

Asynchronous vs synchronous execution, what does it really mean?

In a nutshell, synchronization refers to two or more processes' start and end points, NOT their executions. In this example, Process A's endpoint is synchronized with Process B's start point:

SYNCHRONOUS
   |--------A--------|
                     |--------B--------|

Asynchronous processes, on the other hand, do not have their start and endpoints synchronized:

ASYNCHRONOUS
   |--------A--------|
         |--------B--------|

Where Process A overlaps Process B, they're running concurrently or synchronously (dictionary definition), hence the confusion.

UPDATE: Charles Bretana improved his answer, so this answer is now just a simple (potentially oversimplified) mnemonic.

How to tell PowerShell to wait for each command to end before starting the next?

Normally, for internal commands PowerShell does wait before starting the next command. One exception to this rule is external Windows subsystem based EXE. The first trick is to pipeline to Out-Null like so:

Notepad.exe | Out-Null

PowerShell will wait until the Notepad.exe process has been exited before continuing. That is nifty but kind of subtle to pick up from reading the code. You can also use Start-Process with the -Wait parameter:

Start-Process <path to exe> -NoNewWindow -Wait

If you are using the PowerShell Community Extensions version it is:

$proc = Start-Process <path to exe> -NoNewWindow -PassThru
$proc.WaitForExit()

Another option in PowerShell 2.0 is to use a background job:

$job = Start-Job { invoke command here }
Wait-Job $job
Receive-Job $job

Gradle to execute Java class (without modifying build.gradle)

You just need to use the Gradle Application plugin:

apply plugin:'application'
mainClassName = "org.gradle.sample.Main"

And then simply gradle run.

As Teresa points out, you can also configure mainClassName as a system property and run with a command line argument.

How to stop/terminate a python script from running?

You can also do it if you use the exit() function in your code. More ideally, you can do sys.exit(). sys.exit() which might terminate Python even if you are running things in parallel through the multiprocessing package.

Note: In order to use the sys.exit(), you must import it: import sys

.do extension in web pages?

.do comes from the Struts framework. See this question: Why do Java webapps use .do extension? Where did it come from? Also you can change what your urls look like using mod_rewrite (on Apache).

How to force Sequential Javascript Execution?

Put your code in a string, iterate, eval, setTimeout and recursion to continue with the remaining lines. No doubt I'll refine this or just throw it out if it doesn't hit the mark. My intention is to use it to simulate really, really basic user testing.

The recursion and setTimeout make it sequential.

Thoughts?

var line_pos = 0;
var string =`
    console.log('123');
    console.log('line pos is '+ line_pos);
SLEEP
    console.log('waited');
    console.log('line pos is '+ line_pos);
SLEEP
SLEEP
    console.log('Did i finish?');
`;

var lines = string.split("\n");
var r = function(line_pos){
    for (i = p; i < lines.length; i++) { 
        if(lines[i] == 'SLEEP'){
            setTimeout(function(){r(line_pos+1)},1500);
            return;
        }
        eval (lines[line_pos]);
    }
    console.log('COMPLETED READING LINES');
    return;
}
console.log('STARTED READING LINES');
r.call(this,line_pos);

OUTPUT

STARTED READING LINES
123
124
1 p is 0
undefined
waited
p is 5
125
Did i finish?
COMPLETED READING LINES

php timeout - set_time_limit(0); - don't work

Checkout this, This is from PHP MANUAL, This may help you.

If you're using PHP_CLI SAPI and getting error "Maximum execution time of N seconds exceeded" where N is an integer value, try to call set_time_limit(0) every M seconds or every iteration. For example:

<?php

require_once('db.php');

$stmt = $db->query($sql);

while ($row = $stmt->fetchRow()) {
    set_time_limit(0);
    // your code here
}

?>

Adding delay between execution of two following lines

Like @Sunkas wrote, performSelector:withObject:afterDelay: is the pendant to the dispatch_after just that it is shorter and you have the normal objective-c syntax. If you need to pass arguments to the block you want to delay, you can just pass them through the parameter withObject and you will receive it in the selector you call:

[self performSelector:@selector(testStringMethod:) 
           withObject:@"Test Test" 
           afterDelay:0.5];

- (void)testStringMethod:(NSString *)string{
    NSLog(@"string  >>> %@", string);
}

If you still want to choose yourself if you execute it on the main thread or on the current thread, there are specific methods which allow you to specify this. Apples Documentation tells this:

If you want the message to be dequeued when the run loop is in a mode other than the default mode, use the performSelector:withObject:afterDelay:inModes: method instead. If you are not sure whether the current thread is the main thread, you can use the performSelectorOnMainThread:withObject:waitUntilDone: or performSelectorOnMainThread:withObject:waitUntilDone:modes: method to guarantee that your selector executes on the main thread. To cancel a queued message, use the cancelPreviousPerformRequestsWithTarget: or cancelPreviousPerformRequestsWithTarget:selector:object: method.

How to print colored text to the terminal?

This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some Python code from the Blender build scripts:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

To use code like this, you can do something like:

print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)

Or, with Python 3.6+:

print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")

This will work on unixes including OS X, Linux and Windows (provided you use ANSICON, or in Windows 10 provided you enable VT100 emulation). There are ANSI codes for setting the color, moving the cursor, and more.

If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the "curses" module, which handles a lot of the complicated parts of this for you. The Python Curses HowTO is a good introduction.

If you are not using extended ASCII (i.e., not on a PC), you are stuck with the ASCII characters below 127, and '#' or '@' is probably your best bet for a block. If you can ensure your terminal is using a IBM extended ASCII character set, you have many more options. Characters 176, 177, 178 and 219 are the "block characters".

Some modern text-based programs, such as "Dwarf Fortress", emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the Dwarf Fortress Wiki see (user-made tilesets).

The Text Mode Demo Contest has more resources for doing graphics in text mode.

How to update only one field using Entity Framework?

You can tell EF which properties have to be updated in this way:

public void ChangePassword(int userId, string password)
{
  var user = new User { Id = userId, Password = password };
  using (var context = new ObjectContext(ConnectionString))
  {
    var users = context.CreateObjectSet<User>();
    users.Attach(user);
    context.ObjectStateManager.GetObjectStateEntry(user)
      .SetModifiedProperty("Password");
    context.SaveChanges();
  }
}

Executing Batch File in C#

This should work. You could try to dump out the contents of the output and error streams in order to find out what's happening:

static void ExecuteCommand(string command)
{
    int exitCode;
    ProcessStartInfo processInfo;
    Process process;

    processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
    processInfo.CreateNoWindow = true;
    processInfo.UseShellExecute = false;
    // *** Redirect the output ***
    processInfo.RedirectStandardError = true;
    processInfo.RedirectStandardOutput = true;

    process = Process.Start(processInfo);
    process.WaitForExit();

    // *** Read the streams ***
    // Warning: This approach can lead to deadlocks, see Edit #2
    string output = process.StandardOutput.ReadToEnd();
    string error = process.StandardError.ReadToEnd();

    exitCode = process.ExitCode;

    Console.WriteLine("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
    Console.WriteLine("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
    Console.WriteLine("ExitCode: " + exitCode.ToString(), "ExecuteCommand");
    process.Close();
}

static void Main()
{
    ExecuteCommand("echo testing");
}   

* EDIT *

Given the extra information in your comment below, I was able to recreate the problem. There seems to be some security setting that results in this behaviour (haven't investigated that in detail).

This does work if the batch file is not located in C:\Windows\System32. Try moving it to some other location, e.g. the location of your executable. Note that keeping custom batch files or executables in the Windows directory is bad practice anyway.

* EDIT 2 * It turns out that if the streams are read synchronously, a deadlock can occur, either by reading synchronously before WaitForExit or by reading both stderr and stdout synchronously one after the other.

This should not happen if using the asynchronous read methods instead, as in the following example:

static void ExecuteCommand(string command)
{
    var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
    processInfo.CreateNoWindow = true;
    processInfo.UseShellExecute = false;
    processInfo.RedirectStandardError = true;
    processInfo.RedirectStandardOutput = true;

    var process = Process.Start(processInfo);

    process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
        Console.WriteLine("output>>" + e.Data);
    process.BeginOutputReadLine();

    process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
        Console.WriteLine("error>>" + e.Data);
    process.BeginErrorReadLine();

    process.WaitForExit();

    Console.WriteLine("ExitCode: {0}", process.ExitCode);
    process.Close();
}

Calculate the display width of a string in Java

I personally was searching for something to let me compute the multiline string area, so I could determine if given area is big enough to print the string - with preserving specific font.

private static Hashtable hash = new Hashtable();
private Font font;
private LineBreakMeasurer lineBreakMeasurer;
private int start, end;

public PixelLengthCheck(Font font) {
    this.font = font;
}

public boolean tryIfStringFits(String textToMeasure, Dimension areaToFit) {
    AttributedString attributedString = new AttributedString(textToMeasure, hash);
    attributedString.addAttribute(TextAttribute.FONT, font);
    AttributedCharacterIterator attributedCharacterIterator =
            attributedString.getIterator();
    start = attributedCharacterIterator.getBeginIndex();
    end = attributedCharacterIterator.getEndIndex();

    lineBreakMeasurer = new LineBreakMeasurer(attributedCharacterIterator,
            new FontRenderContext(null, false, false));

    float width = (float) areaToFit.width;
    float height = 0;
    lineBreakMeasurer.setPosition(start);

    while (lineBreakMeasurer.getPosition() < end) {
        TextLayout textLayout = lineBreakMeasurer.nextLayout(width);
        height += textLayout.getAscent();
        height += textLayout.getDescent() + textLayout.getLeading();
    }

    boolean res = height <= areaToFit.getHeight();

    return res;
}

Serialize and Deserialize Json and Json Array in Unity

Assume you got a JSON like this

[
    {
        "type": "qrcode",
        "symbol": [
            {
                "seq": 0,
                "data": "HelloWorld9887725216",
                "error": null
            }
        ]
    }
]

To parse the above JSON in unity, you can create JSON model like this.

[System.Serializable]
public class QrCodeResult
{
    public QRCodeData[] result;
}

[System.Serializable]
public class Symbol
{
    public int seq;
    public string data;
    public string error;
}

[System.Serializable]
public class QRCodeData
{
    public string type;
    public Symbol[] symbol;
}

And then simply parse in the following manner...

var myObject = JsonUtility.FromJson<QrCodeResult>("{\"result\":" + jsonString.ToString() + "}");

Now you can modify the JSON/CODE according to your need. https://docs.unity3d.com/Manual/JSONSerialization.html

Eloquent Collection: Counting and Detect Empty

I think you are looking for:

$result->isEmpty()

This is different from empty($result), which will not be true because the result will be an empty collection. Your suggestion of count($result) is also a good solution. I cannot find any reference in the docs

Node.js version on the command line? (not the REPL)

Repl Command to find the Nodejs Version

$node
>process.version
`v8.x`

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

Implement Validation for WPF TextBoxes

When it comes to DiSaSteR's answer, I noticed a different behavior. textBox.Text shows the text in the TextBox as it was before the user entered a new character, while e.Text shows the single character the user just entered. One challenge is that this character might not get appended to the end, but it will be inserted at the carret position:

private void salary_texbox_PreviewTextInput(object sender, TextCompositionEventArgs e){
  Regex regex = new Regex ( "[^0-9]+" );

  string text;
  if (textBox.CaretIndex==textBox.Text.Length) {
    text = textBox.Text + e.Text;
  } else {
    text = textBox.Text.Substring(0, textBox.CaretIndex)  + e.Text + textBox.Text.Substring(textBox.CaretIndex);
  }

  if(regex.IsMatch(text)){
      MessageBox.Show("Error");
  }
}

Redis: How to access Redis log file

Found it with:

sudo tail /var/log/redis/redis-server.log -n 100

So if the setup was more standard that should be:

sudo tail /var/log/redis_6379.log -n 100

This outputs the last 100 lines of the file.

Where your log file is located is in your configs that you can access with:

redis-cli CONFIG GET *

The log file may not always be shown using the above. In that case use

tail -f `less  /etc/redis/redis.conf | grep logfile|cut -d\  -f2`

Rails server says port already used, how to kill that process?

All the answers above are really good but I needed a way to type as little as possible in the terminal so I created a gem for that. You can install the gem only once and run the command 'shutup' every time you wanna kill the Rails process (while being in the current folder).

gem install shutup

then go in the current folder of your rails project and run

shutup # this will kill the Rails process currently running

You can use the command 'shutup' every time you want

DICLAIMER: I am the creator of this gem

NOTE: if you are using rvm install the gem globally

rvm @global do gem install shutup

How can I change the color of AlertDialog title and the color of the line under it

check this is useful for you...

public void setCustomTitle (View customTitleView)

you get detail from following link.

http://developer.android.com/reference/android/app/AlertDialog.Builder.html#setCustomTitle%28android.view.View%29

CustomDialog.java

Dialog alert = new Dialog(this);
    alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
    alert.setContentView(R.layout.title);
    TextView msg = (TextView)alert.findViewById(R.id.textView1);
    msg.setText("Hello Friends.\nIP address : 111.111.1.111");
    alert.show();

title.xml

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

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Set IP address"
    android:textColor="#ff0000"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<ImageView 
    android:layout_width="fill_parent"
    android:layout_height="2dp"
    android:layout_marginTop="5dp"
    android:background="#00ff00"
    />
<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#775500"
    android:textAppearance="?android:attr/textAppearanceLarge" />

enter image description here

Change Twitter Bootstrap Tooltip content on click

This works if the tooltip has been instantiated (possibly with javascript):

$("#tooltip_id").data('tooltip').options.title="New_value!";
$("#tooltip_id").tooltip('hide').tooltip('show');

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

This error might occur when you return an object instead of a string in your __unicode__ method. For example:

class Author(models.Model):
    . . . 
    name = models.CharField(...)


class Book(models.Model):
    . . .
    author = models.ForeignKey(Author, ...)
    . . .
    def __unicode__(self):
        return self.author  # <<<<<<<< this causes problems

To avoid this error you can cast the author instance to unicode:

class Book(models.Model):
    . . . 
    def __unicode__(self):
        return unicode(self.author)  # <<<<<<<< this is OK

How to merge specific files from Git branches

If you only care about the conflict resolution and not about keeping the commit history, the following method should work. Say you want to merge a.py b.py from BRANCHA into BRANCHB. First, make sure any changes in BRANCHB are either committed or stashed away, and that there are no untracked files. Then:

git checkout BRANCHB
git merge BRANCHA
# 'Accept' all changes
git add .
# Clear staging area
git reset HEAD -- .
# Stash only the files you want to keep
git stash push a.py b.py
# Remove all other changes
git add .
git reset --hard
# Now, pull the changes
git stash pop

git won't recognize that there are conflicts in a.py b.py, but the merge conflict markers are there if there were in fact conflicts. Using a third-party merge tool, such as VSCode, one will be able to resolve conflicts more comfortably.

What is the difference between Sublime text and Github's Atom

One major difference is the support of "Indic Fonts" aka South Asian Scripts (including Southeast Asian languages such as Khmer, Lao, Myanmar and Thai). Also, there is much better support for East Asian languages (Chinese, Japanese, Korean). These are known bugs (actually the most highly rated bugs) that have been going on for years (thought it appears East Asian language support used to work better but have now become difficult to use):

What does the variable $this mean in PHP?

when you create a class you have (in many cases) instance variables and methods (aka. functions). $this accesses those instance variables so that your functions can take those variables and do what they need to do whatever you want with them.

another version of meder's example:

class Person {

    protected $name;  //can't be accessed from outside the class

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}
// this line creates an instance of the class Person setting "Jack" as $name.  
// __construct() gets executed when you declare it within the class.
$jack = new Person("Jack"); 

echo $jack->getName();

Output:

Jack

why is plotting with Matplotlib so slow?

To start, Joe Kington's answer provides very good advice using a gui-neutral approach, and you should definitely take his advice (especially about Blitting) and put it into practice. More info on this approach, read the Matplotlib Cookbook

However, the non-GUI-neutral (GUI-biased?) approach is key to speeding up the plotting. In other words, the backend is extremely important to plot speed.

Put these two lines before you import anything else from matplotlib:

import matplotlib
matplotlib.use('GTKAgg') 

Of course, there are various options to use instead of GTKAgg, but according to the cookbook mentioned before, this was the fastest. See the link about backends for more options.

jQuery: value.attr is not a function

The second parameter of the callback function passed to each() will contain the actual DOM element and not a jQuery wrapper object. You can call the getAttribute() method of the element:

$('#category_sorting_form_save').click(function() {
    var elements = $("#category_sorting_elements > div");
    $.each(elements, function(key, value) {
        console.info(key, ": ", value);
        console.info("cat_id: ", value.getAttribute('cat_id'));
    });
});

Or wrap the element in a jQuery object yourself:

$('#category_sorting_form_save').click(function() {
    var elements = $("#category_sorting_elements > div");
    $.each(elements, function(key, value) {
        console.info(key, ": ", value);
        console.info("cat_id: ", $(value).attr('cat_id'));
    });
});

Or simply use $(this):

$('#category_sorting_form_save').click(function() {
    var elements = $("#category_sorting_elements > div");
    $.each(elements, function() {
        console.info("cat_id: ", $(this).attr('cat_id'));
    });
});

Compiler error: "class, interface, or enum expected"

You forgot your class declaration:

public class MyClass {
...

How to clear APC cache entries?

I know it's not for everyone but: why not to do a graceful Apache restart?

For e.g. in case of Centos/RedHat Linux:

sudo service httpd graceful

Ubuntu:

sudo service apache2 graceful

How to set a border for an HTML div tag

I guess this is where you are pointing at ..

<div id="divActivites" name="divActivites" style="border:thin">
    <textarea id="inActivities" name="inActivities" style="border:solid">
    </textarea> 
</div> 

Well. it must be written as border-width:thin

Here you go with the link (click here) check out the different types of Border-styles

you can also set the border width by writing the width in terms of pixels.. (like border-width:1px), minimum width is 1px.

Handling the null value from a resultset in JAVA

The String being null is a very good chance, but when you see values in your table, yet a null is printed by the ResultSet, it might mean that the connection was closed before the value of ResultSet was used.

Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:My_db.db");
String sql = ("select * from cust where cust_id='" + cus + "'");
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
con.close();
System.out.println(rs.getString(1));

Would print null even if there are values.

Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:My_db.db");
String sql = ("select * from cust where cust_id='" + cus + "'");
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
System.out.println(rs.getString(1));
con.close();

Wouldn't print null if there are values in the table.

Finding a branch point with Git?

I seem to be getting some joy with

git rev-list branch...master

The last line you get is the first commit on the branch, so then it's a matter of getting the parent of that. So

git rev-list -1 `git rev-list branch...master | tail -1`^

Seems to work for me and doesn't need diffs and so on (which is helpful as we don't have that version of diff)

Correction: This doesn't work if you are on the master branch, but I'm doing this in a script so that's less of an issue

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

If working with classes you need to make sure you reference member variables using $this:

class Person
{
    protected $firstName;
    protected $lastName;

    public function setFullName($first, $last)
    {
        // Correct
        $this->firstName = $first;

        // Incorrect
        $lastName = $last;

        // Incorrect
        $this->$lastName = $last;
    }
}

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

Sadly none of the solutions worked for me! I solved my problem by uninstalling existing APK from my phone and it all started working perfectly!

This started happening after I've updated android studio to latest version.

"unary operator expected" error in Bash if condition

Took me a while to find this but note that if you have a spacing error you will also get the same error:

[: =: unary operator expected

Correct:

if [ "$APP_ENV" = "staging" ]

vs

if ["$APP_ENV" = "staging" ]

As always setting -x debug variable helps to find these:

set -x

MAMP mysql server won't start. No mysql processes are running

I just had this problem. These are the steps that worked for me.

  1. Open Preferences in MAMP, make a note of your current Apache and MySQL Port numbers.

    enter image description here

  2. Click both Set to default Apache and MySQL ports and Reset MAMP buttons then OK.

  3. Quit MAMP

  4. Delete all files (not folders) from /Applications/MAMP/db/mysql directory.

  5. Reboot MAMP and click Start Servers.

    Note: if MySQL starts fine but Apache doesn't, go back to Preferences and set Apache Port back to what it was before. MAMP should refresh after you click OK and both Apache and MySQL should start.

  6. If http://localhost/MAMP/index.php fails to load, open Developer Tools (Chrome), right-click on refresh button and select Empty Cache and Hard Reload. The phpAdmin page should load. If not try going to Application panel in Developer tools, select Clear Storage from the menu and click Clear Site Data.

I hope those steps provide a quick fix for someone without needed to destroy your database tables.

Prevent any form of page refresh using jQuery/Javascript

Although its not a good idea to disable F5 key you can do it in JQuery as below.

<script type="text/javascript">
function disableF5(e) { if ((e.which || e.keyCode) == 116 || (e.which || e.keyCode) == 82) e.preventDefault(); };

$(document).ready(function(){
     $(document).on("keydown", disableF5);
});
</script>

Hope this will help!

Why is JsonRequestBehavior needed?

You do not need it.

If your action has the HttpPost attribute, then you do not need to bother with setting the JsonRequestBehavior and use the overload without it. There is an overload for each method without the JsonRequestBehavior enum. Here they are:

Without JsonRequestBehavior

protected internal JsonResult Json(object data);
protected internal JsonResult Json(object data, string contentType);
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding);

With JsonRequestBehavior

protected internal JsonResult Json(object data, JsonRequestBehavior behavior);
protected internal JsonResult Json(object data, string contentType, 
                                   JsonRequestBehavior behavior);
protected internal virtual JsonResult Json(object data, string contentType, 
    Encoding contentEncoding, JsonRequestBehavior behavior);

Confirm postback OnClientClick button ASP.NET

I know this is old and there are so many answers, some are really convoluted, can be quick and inline:

<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton" OnClick="BtnUserDelete_Click" OnClientClick="return confirm('Are you sure you want to delete this user?');" meta:resourcekey="BtnUserDeleteResource1" />
                       

How to set time to 24 hour format in Calendar

Replace this:

c1.set(Calendar.HOUR, d1.getHours());

with this:

c1.set(Calendar.HOUR_OF_DAY, d1.getHours());

Calendar.HOUR is strictly for 12 hours.

jquery: animate scrollLeft

First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate

$('.swipeRight').click(function()
{

    $('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});

$('.swipeLeft').click(function()
{
    $('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});

The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.

Doctrine2: Best way to handle many-to-many with extra columns in reference table

This really useful example. It lacks in the documentation doctrine 2.

Very thank you.

For the proxies functions can be done :

class AlbumTrack extends AlbumTrackAbstract {
   ... proxy method.
   function getTitle() {} 
}

class TrackAlbum extends AlbumTrackAbstract {
   ... proxy method.
   function getTitle() {}
}

class AlbumTrackAbstract {
   private $id;
   ....
}

and

/** @OneToMany(targetEntity="TrackAlbum", mappedBy="album") */
protected $tracklist;

/** @OneToMany(targetEntity="AlbumTrack", mappedBy="track") */
protected $albumsFeaturingThisTrack;

iOS start Background Thread

Well that's pretty easy actually with GCD. A typical workflow would be something like this:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
    dispatch_async(queue, ^{
        // Perform async operation
        // Call your method/function here
        // Example:
        // NSString *result = [anObject calculateSomething];
                dispatch_sync(dispatch_get_main_queue(), ^{
                    // Update UI
                    // Example:
                    // self.myLabel.text = result;
                });
    });

For more on GCD you can take a look into Apple's documentation here

Skip first line(field) in loop using CSV file?

csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

Looping through GridView rows and Checking Checkbox Control

you have to iterate gridview Rows

for (int count = 0; count < grd.Rows.Count; count++)
{
    if (((CheckBox)grd.Rows[count].FindControl("yourCheckboxID")).Checked)
    {     
      ((Label)grd.Rows[count].FindControl("labelID")).Text
    }
}

What's the best practice using a settings file in Python?

The sample config you provided is actually valid YAML. In fact, YAML meets all of your demands, is implemented in a large number of languages, and is extremely human friendly. I would highly recommend you use it. The PyYAML project provides a nice python module, that implements YAML.

To use the yaml module is extremely simple:

import yaml
config = yaml.safe_load(open("path/to/config.yml"))

Get only records created today in laravel

Laravel ^5.6 - Query Scopes

For readability purposes i use query scope, makes my code more declarative.

scope query

namespace App\Models;

use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    // ...

    /**
     * Scope a query to only include today's entries.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeCreatedToday($query)
    {
        return $query->where('created_at', '>=', Carbon::today());
    }

    // ...
}

example of usage

MyModel::createdToday()->get()

SQL generated

Sql      : select * from "my_models" where "created_at" >= ?

Bindings : ["2019-10-22T00:00:00.000000Z"]

Protractor : How to wait for page complete after click a button?

With Protractor, you can use the following approach

var EC = protractor.ExpectedConditions;
// Wait for new page url to contain newPageName
browser.wait(EC.urlContains('newPageName'), 10000);

So your code will look something like,

emailEl.sendKeys('jack');
passwordEl.sendKeys('123pwd');

btnLoginEl.click();

var EC = protractor.ExpectedConditions;
// Wait for new page url to contain efg
ptor.wait(EC.urlContains('efg'), 10000);

expect(ptor.getCurrentUrl()).toEqual(url + 'abc#/efg');

Note: This may not mean that new page has finished loading and DOM is ready. The subsequent 'expect()' statement will ensure Protractor waits for DOM to be available for test.

Reference: Protractor ExpectedConditions

How to set javascript variables using MVC4 with Razor

I found a very clean solution that allows separate logic and GUI:

in your razor .cshtml page try this:

<body id="myId" data-my-variable="myValue">

...your page code here

</body>

in your .js file or .ts (if you use typeScript) to read stored value from your view put some like this (jquery library is required):

$("#myId").data("my-variable")

Elegant way to read file into byte[] array in Java

This works for me:

File file = ...;
byte[] data = new byte[(int) file.length()];
try {
    new FileInputStream(file).read(data);
} catch (Exception e) {
    e.printStackTrace();
}

phpinfo() is not working on my CentOS server

My solution was uninstalling and installing the PHP instance (7.0 in my case) again:

sudo apt-get purge php7.0
sudo apt-get install php7.0

After that you will need to restart the Apache service:

sudo service apache2 restart

Finally, verify again in your browser with your localhost or IP address.

Why Maven uses JDK 1.6 but my java -version is 1.7

Please check the compatibility. I struggled with mvn 3.2.1 and jdk 1.6.0_37 for many hours. All variables were set but was not working. Finally I upgraded jdk to 1.8.0_60 and mvn 3.3.3 and that worked. Environment Variables as following:

JAVA_HOME=C:\ProgramFiles\Java\jdk1.8.0_60 
MVN_HOME=C:\ProgramFiles\apache-maven\apache-maven-3.3.3 
M2=%MVN_HOME%\bin extend system level Path- ;%M2%;%JAVA_HOME%\bin;

How to know installed Oracle Client is 32 bit or 64 bit?

Go to %ORACLE_HOME%\inventory\ContentsXML folder and open comps.xml file

Look for <DEP_LIST> on ~second screen.
If following lines have

  • PLAT="NT_AMD64" then this Oracle Home is 64 bit.
  • PLAT="NT_X86" then - 32 bit.

    You may have both 32-bit and 64-bit Oracle Homes installed.

  • Is there a download function in jsFiddle?

    Adding /show does not present a pure source code, it's an embedded working example. To display it without any additional scripts, css and html, use:

    http://fiddle.jshell.net/<fiddle id>/show/light/
    

    An example: http://fiddle.jshell.net/Ua8Cv/show/light/

    "Please try running this command again as Root/Administrator" error when trying to install LESS

    Re Explosion Pills "An installation can run arbitrary scripts and running it with sudo can be extremely dangerous!"

    Seems like using sudo is the wrong way of doing it.

    "Change the owner of the files in your /usr/local folder to the current user:"

    sudo chown -R $USER /usr/local
    

    Then run the install

    node install -g less
    

    Check out:

    Writing to a file in a for loop

    It's preferable to use context managers to close the files automatically

    with open("new.txt", "r"), open('xyz.txt', 'w') as textfile, myfile:
        for line in textfile:
            var1, var2 = line.split(",");
            myfile.writelines(var1)
    

    Calculating powers of integers

    I managed to modify(boundaries, even check, negative nums check) Qx__ answer. Use at your own risk. 0^-1, 0^-2 etc.. returns 0.

    private static int pow(int x, int n) {
            if (n == 0)
                return 1;
            if (n == 1)
                return x;
            if (n < 0) { // always 1^xx = 1 && 2^-1 (=0.5 --> ~ 1 )
                if (x == 1 || (x == 2 && n == -1))
                    return 1;
                else
                    return 0;
            }
            if ((n & 1) == 0) { //is even 
                long num = pow(x * x, n / 2);
                if (num > Integer.MAX_VALUE) //check bounds
                    return Integer.MAX_VALUE; 
                return (int) num;
            } else {
                long num = x * pow(x * x, n / 2);
                if (num > Integer.MAX_VALUE) //check bounds
                    return Integer.MAX_VALUE;
                return (int) num;
            }
        }
    

    How to start an application without waiting in a batch file?

    If your exe takes arguments,

    start MyApp.exe -arg1 -arg2
    

    Swift convert unix time to date and time

    Swift:

    extension Double {
        func getDateStringFromUnixTime(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> String {
            let dateFormatter = DateFormatter()
            dateFormatter.dateStyle = dateStyle
            dateFormatter.timeStyle = timeStyle
            return dateFormatter.string(from: Date(timeIntervalSince1970: self))
        }
    }
    

    Submit HTML form, perform javascript function (alert then redirect)

    <form action="javascript:completeAndRedirect();">
        <input type="text" id="Edit1" 
        style="width:280; height:50; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif; font-size:22px">
    </form>
    

    Changing action to point at your function would solve the problem, in a different way.

    Passing arguments to "make run"

    Not too proud of this, but I didn't want to pass in environment variables so I inverted the way to run a canned command:

    run:
        @echo command-you-want
    

    this will print the command you want to run, so just evaluate it in a subshell:

    $(make run) args to my command
    

    Using Panel or PlaceHolder

    PlaceHolder control

    Use the PlaceHolder control as a container to store server controls that are dynamically added to the Web page. The PlaceHolder control does not produce any visible output and is used only as a container for other controls on the Web page. You can use the Control.Controls collection to add, insert, or remove a control in the PlaceHolder control.

    Panel control

    The Panel control is a container for other controls. It is especially useful when you want to generate controls programmatically, hide/show a group of controls, or localize a group of controls.

    The Direction property is useful for localizing a Panel control's content to display text for languages that are written from right to left, such as Arabic or Hebrew.

    The Panel control provides several properties that allow you to customize the behavior and display of its contents. Use the BackImageUrl property to display a custom image for the Panel control. Use the ScrollBars property to specify scroll bars for the control.

    Small differences when rendering HTML: a PlaceHolder control will render nothing, but Panel control will render as a <div>.

    More information at ASP.NET Forums

    Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

    Maybe you forgot the MySQL JDBC driver.

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.34</version>
    </dependency>
    

    Codeigniter $this->db->order_by(' ','desc') result is not complete

    Put the line $this->db->order_by("course_name","desc"); at top of your query. Like

    $this->db->order_by("course_name","desc");$this->db->select('*');
    $this->db->where('tennant_id',$tennant_id);
    $this->db->from('courses');
    $query=$this->db->get();
    return $query->result();
    

    How do I setup a SSL certificate for an express.js server?

    See the Express docs as well as the Node docs for https.createServer (which is what express recommends to use):

    var privateKey = fs.readFileSync( 'privatekey.pem' );
    var certificate = fs.readFileSync( 'certificate.pem' );
    
    https.createServer({
        key: privateKey,
        cert: certificate
    }, app).listen(port);
    

    Other options for createServer are at: http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener

    Can't change z-index with JQuery

    $(this).parent().css('z-index',3000);
    

    Google Maps: How to create a custom InfoWindow?

    I'm not sure how FWIX.com is doing it specifically, but I'd wager they are using Custom Overlays.

    How to change DataTable columns order

    Re-Ordering data Table based on some condition or check box checked. PFB :-

     var tableResult= $('#exampleTable').DataTable();
    
        var $tr = $(this).closest('tr');
        if ($("#chkBoxId").prop("checked")) 
                        {
                            // re-draw table shorting based on condition
                            tableResult.row($tr).invalidate().order([colindx, 'asc']).draw();
                        }
                        else {
                            tableResult.row($tr).invalidate().order([colindx, "asc"]).draw();
                        }
    

    how I can show the sum of in a datagridview column?

    int sum = 0;
    for (int i = 0; i < dataGridView1.Rows.Count; ++i)
    {
        sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);
    }
    label1.Text = sum.ToString();
    

    PHP ini file_get_contents external url

    This will also give external links an absolute path without having to use php.ini

    <?php
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://www.your_external_website.com");
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $result = curl_exec($ch);
    curl_close($ch);
    $result = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#",'$1http://www.your_external_website.com/$2$3', $result);
    echo $result
    ?>
    

    PuTTY scripting to log onto host

    For me it works this way:

    putty -ssh [email protected] 22 -pw password
    

    putty, protocol, user name @ ip address port and password. To connect in less than a second.

    JavaScript: How to get parent element by selector?

    Here is simple way to access parent id

    document.getElementById("child1").parentNode;
    

    will do the magic for you to access the parent div.

    <html>
    <head>
    </head>
    <body id="body">
    <script>
    function alertAncestorsUntilID() {
    var a = document.getElementById("child").parentNode;
    alert(a.id);
    }
    </script>
    <div id="master">
    Master
    <div id="child">Child</div>
    </div>
    <script>
    alertAncestorsUntilID();
    </script>
    </body>
    </html>
    

    What exactly does an #if 0 ..... #endif block do?

    When the preprocessor sees #if it checks whether the next token has a non-zero value. If it does, it keeps the code around for the compiler. If it doesn't, it gets rid of that code so the compiler never sees it.

    If someone says #if 0 they are effectively commenting out the code so it will never be compiled. You can think of this the same as if they had put /* ... */ around it. It's not quite the same, but it has the same effect.

    If you want to understand what happened in detail, you can often look. Many compilers will allow you to see the files after the preprocessor has run. For example, on Visual C++ the switch /P command will execute the preprocessor and put the results in a .i file.

    How to get first object out from List<Object> using Linq

    You can do

    Component depCountry = lstComp
                           .Select(x => x.ComponentValue("Dep"))
                           .FirstOrDefault();
    

    Alternatively if you are wanting this for the entire dictionary of values, you can even tie it back to the key

    var newDictionary = dic.Select(x => new 
                {
                   Key = x.Key,
                   Value = x.Value.Select( y => 
                          {
                              depCountry = y.ComponentValue("Dep")
                          }).FirstOrDefault()
                 }
                 .Where(x => x.Value != null)
                 .ToDictionary(x => x.Key, x => x.Value());
    

    This will give you a new dictionary. You can access the values

    var myTest = newDictionary[key1].depCountry     
    

    Git Diff with Beyond Compare

    For MAC after doing lot of research it worked for me..! 1. Install the beyond compare and this will be installed in below location

    /Applications/Beyond\ Compare.app/Contents/MacOS/bcomp

    Please follow these steps to make bc as diff/merge tool in git http://www.scootersoftware.com/support.php?zz=kb_mac

    SQL: How to get the count of each distinct value in a column?

    SELECT
      category,
      COUNT(*) AS `num`
    FROM
      posts
    GROUP BY
      category
    

    jQuery append text inside of an existing paragraph tag

    Try this...

    $('p').append('<span id="add_here">new-dynamic-text</span>');
    

    OR if there is an existing span, do this.

    $('p').children('span').text('new-dynamic-text');
    

    DEMO

    the getSource() and getActionCommand()

    I use getActionCommand() to hear buttons. I apply the setActionCommand() to each button so that I can hear whenever an event is execute with event.getActionCommand("The setActionCommand() value of the button").

    I use getSource() for JRadioButtons for example. I write methods that returns each JRadioButton so in my Listener Class I can specify an action each time a new JRadioButton is pressed. So for example:

    public class SeleccionListener implements ActionListener, FocusListener {}
    

    So with this I can hear button events and radioButtons events. The following are examples of how I listen each one:

    public void actionPerformed(ActionEvent event) {
        if (event.getActionCommand().equals(GUISeleccion.BOTON_ACEPTAR)) {
            System.out.println("Aceptar pressed");
        }
    

    In this case GUISeleccion.BOTON_ACEPTAR is a "public static final String" which is used in JButtonAceptar.setActionCommand(BOTON_ACEPTAR).

    public void focusGained(FocusEvent focusEvent) {
        if (focusEvent.getSource().equals(guiSeleccion.getJrbDat())){
            System.out.println("Data radio button");
        }
    

    In this one, I get the source of any JRadioButton that is focused when the user hits it. guiSeleccion.getJrbDat() returns the reference to the JRadioButton that is in the class GUISeleccion (this is a Frame)

    Meaning of end='' in the statement print("\t",end='')?

    See the documentation for the print function: print()

    The content of end is printed after the thing you want to print. By default it contains a newline ("\n") but it can be changed to something else, like an empty string.

    How can I list all tags for a Docker image on a remote registry?

    I have done this thing when I have to implement a task in which if user somehow type the wrong tag then we have to give the list of all the tag present in the repo(Docker repo) present in the register. So I have code in batch Script.

    <html>
    <pre style="background-color:#bcbbbb;">
    @echo off
    
    docker login --username=xxxx --password=xxxx
    docker pull %1:%2
    
    IF NOT %ERRORLEVEL%==0 (
    echo "Specified Version is Not Found "
    echo "Available Version for this image is :"
    for /f %%i in (' curl -s -H "Content-Type:application/json" -X POST -d "{\"username\":\"user\",\"password\":\"password\"}" https://hub.docker.com/v2/users/login ^|jq -r .token ') do set TOKEN=%%i
    curl -sH "Authorization: JWT %TOKEN%" "https://hub.docker.com/v2/repositories/%1/tags/" | jq .results[].name
    )
    </pre>
    </html>
    

    So in this we can give arguments to out batch file like:

    Dockerfile java version7 

    MySQL error: key specification without a key length

    I know it's quite late, but removing the Unique Key Constraint solved the problem. I didn't use the TEXT or LONGTEXT column as PK , but I was trying to make it unique. I got the 1170 error, but when I removed UK, the error was removed too.

    I don't fully understand why.

    Changing the color of an hr element

    You can use CSS to make a line with a different color, example would be like that:

    border-left: 1px solid rgb(216, 216, 216);
    border-right: medium none;
    border-width: medium medium medium 2px;
    border-style: none none none solid;
    border-color: -moz-use-text-color -moz-use-text-color -moz-use-text-color rgb(216, 216, 216);
    

    that code will display vertical grey line.

    How to pad zeroes to a string?

    width = 10
    x = 5
    print "%0*d" % (width, x)
    > 0000000005
    

    See the print documentation for all the exciting details!

    Update for Python 3.x (7.5 years later)

    That last line should now be:

    print("%0*d" % (width, x))
    

    I.e. print() is now a function, not a statement. Note that I still prefer the Old School printf() style because, IMNSHO, it reads better, and because, um, I've been using that notation since January, 1980. Something ... old dogs .. something something ... new tricks.

    VBA: Counting rows in a table (list object)

    You need to go one level deeper in what you are retrieving.

    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects("MyTable")
    MsgBox tbl.Range.Rows.Count
    MsgBox tbl.HeaderRowRange.Rows.Count
    MsgBox tbl.DataBodyRange.Rows.Count
    Set tbl = Nothing
    

    More information at:

    ListObject Interface
    ListObject.Range Property
    ListObject.DataBodyRange Property
    ListObject.HeaderRowRange Property

    Understanding Popen.communicate

    .communicate() writes input (there is no input in this case so it just closes subprocess' stdin to indicate to the subprocess that there is no more input), reads all output, and waits for the subprocess to exit.

    The exception EOFError is raised in the child process by raw_input() (it expected data but got EOF (no data)).

    p.stdout.read() hangs forever because it tries to read all output from the child at the same time as the child waits for input (raw_input()) that causes a deadlock.

    To avoid the deadlock you need to read/write asynchronously (e.g., by using threads or select) or to know exactly when and how much to read/write, for example:

    from subprocess import PIPE, Popen
    
    p = Popen(["python", "-u", "1st.py"], stdin=PIPE, stdout=PIPE, bufsize=1)
    print p.stdout.readline(), # read the first line
    for i in range(10): # repeat several times to show that it works
        print >>p.stdin, i # write input
        p.stdin.flush() # not necessary in this case
        print p.stdout.readline(), # read output
    
    print p.communicate("n\n")[0], # signal the child to exit,
                                   # read the rest of the output, 
                                   # wait for the child to exit
    

    Note: it is a very fragile code if read/write are not in sync; it deadlocks.

    Beware of block-buffering issue (here it is solved by using "-u" flag that turns off buffering for stdin, stdout in the child).

    bufsize=1 makes the pipes line-buffered on the parent side.

    SSIS cannot convert because a potential loss of data

    This might not be the best method, but you can ignore the conversion error if all else fails. Mine was an issue of nulls not converting properly, so I just ignored the error and the dates came in as dates and the nulls came in as nulls, so no data quality issues--not that this would always be the case. To do this, right click on your source, click Edit, then Error Output. Go to the column that's giving you grief and under Error change it to Ignore Failure.

    Does Python support short-circuiting?

    Short-circuiting behavior in operator and, or:

    Let's first define a useful function to determine if something is executed or not. A simple function that accepts an argument, prints a message and returns the input, unchanged.

    >>> def fun(i):
    ...     print "executed"
    ...     return i
    ... 
    

    One can observe the Python's short-circuiting behavior of and, or operators in the following example:

    >>> fun(1)
    executed
    1
    >>> 1 or fun(1)    # due to short-circuiting  "executed" not printed
    1
    >>> 1 and fun(1)   # fun(1) called and "executed" printed 
    executed
    1
    >>> 0 and fun(1)   # due to short-circuiting  "executed" not printed 
    0
    

    Note: The following values are considered by the interpreter to mean false:

            False    None    0    ""    ()    []     {}
    

    Short-circuiting behavior in function: any(), all():

    Python's any() and all() functions also support short-circuiting. As shown in the docs; they evaluate each element of a sequence in-order, until finding a result that allows an early exit in the evaluation. Consider examples below to understand both.

    The function any() checks if any element is True. It stops executing as soon as a True is encountered and returns True.

    >>> any(fun(i) for i in [1, 2, 3, 4])   # bool(1) = True
    executed
    True
    >>> any(fun(i) for i in [0, 2, 3, 4])   
    executed                               # bool(0) = False
    executed                               # bool(2) = True
    True
    >>> any(fun(i) for i in [0, 0, 3, 4])
    executed
    executed
    executed
    True
    

    The function all() checks all elements are True and stops executing as soon as a False is encountered:

    >>> all(fun(i) for i in [0, 0, 3, 4])
    executed
    False
    >>> all(fun(i) for i in [1, 0, 3, 4])
    executed
    executed
    False
    

    Short-circuiting behavior in Chained Comparison:

    Additionally, in Python

    Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

    >>> 5 > 6 > fun(3)    # same as:  5 > 6 and 6 > fun(3)
    False                 # 5 > 6 is False so fun() not called and "executed" NOT printed
    >>> 5 < 6 > fun(3)    # 5 < 6 is True 
    executed              # fun(3) called and "executed" printed
    True
    >>> 4 <= 6 > fun(7)   # 4 <= 6 is True  
    executed              # fun(3) called and "executed" printed
    False
    >>> 5 < fun(6) < 3    # only prints "executed" once
    executed
    False
    >>> 5 < fun(6) and fun(6) < 3 # prints "executed" twice, because the second part executes it again
    executed
    executed
    False
    

    Edit:
    One more interesting point to note :- Logical and, or operators in Python returns an operand's value instead of a Boolean (True or False). For example:

    Operation x and y gives the result if x is false, then x, else y

    Unlike in other languages e.g. &&, || operators in C that return either 0 or 1.

    Examples:

    >>> 3 and 5    # Second operand evaluated and returned 
    5                   
    >>> 3  and ()
    ()
    >>> () and 5   # Second operand NOT evaluated as first operand () is  false
    ()             # so first operand returned 
    

    Similarly or operator return left most value for which bool(value) == True else right most false value (according to short-circuiting behavior), examples:

    >>> 2 or 5    # left most operand bool(2) == True
    2    
    >>> 0 or 5    # bool(0) == False and bool(5) == True
    5
    >>> 0 or ()
    ()
    

    So, how is this useful? One example is given in Practical Python By Magnus Lie Hetland:
    Let’s say a user is supposed to enter his or her name, but may opt to enter nothing, in which case you want to use the default value '<Unknown>'. You could use an if statement, but you could also state things very succinctly:

    In [171]: name = raw_input('Enter Name: ') or '<Unknown>'
    Enter Name: 
    
    In [172]: name
    Out[172]: '<Unknown>'
    

    In other words, if the return value from raw_input is true (not an empty string), it is assigned to name (nothing changes); otherwise, the default '<Unknown>' is assigned to name.

    How to convert Windows end of line in Unix end of line (CR/LF to LF)

    sed cannot match \n because the trailing newline is removed before the line is put into the pattern space but can match \r, so you can convert \r\n (dos) to \n (unix) by removing \r

    sed -i 's/\r//g' file
    

    Warning: this will change the original file

    However, you cannot change from unix EOL to dos or old mac (\r) by this. More readings here:

    How can I replace a newline (\n) using sed?

    How to make modal dialog in WPF?

    Did you try showing your window using the ShowDialog method?

    Don't forget to set the Owner property on the dialog window to the main window. This will avoid weird behavior when Alt+Tabbing, etc.

    Setting up an MS-Access DB for multi-user access

    The first thing to do (if not already done) is to split your database into a front end (with all the forms/reports etc) and a back end(with all the data). The second thing is to setup version control on the front end.

    The way I have done that in a lot of my databases is to have the users run a small “jumper” database to open the main database. This jumper does the following things

    • Checks to see if the user has the database on their C drive

    • If they do not then install and run

    • If they do then check what version they have

    • If the version numbers do not match then copy down the latest version

    • Open the database

    This whole checking process normally takes under half a second. Using this model you can do all your development on a separate database then when you are ready to “release” you just put the new mde up onto the network share and the next time the user opens the jumper the latest version is copied down.

    There are also other things to think about in multiuser database and it might be worth checking for the common mistakes such as binding a form to a whole table etc

    How to call a function after delay in Kotlin?

    I recommended using SingleThread because you do not have to kill it after using. Also, "stop()" method is deprecated in Kotlin language.

    private fun mDoThisJob(){
    
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate({
            //TODO: You can write your periodical job here..!
    
        }, 1, 1, TimeUnit.SECONDS)
    }
    

    Moreover, you can use it for periodical job. It is very useful. If you would like to do job for each second, you can set because parameters of it:

    Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);

    TimeUnit values are: NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS.

    @canerkaseler

    What's the difference between a null pointer and a void pointer?

    I don't think AnT's answer is correct.

    1. NULL is just a pointer constant, otherwise how could we have ptr = NULL.
    2. As NULL is a pointer, what's its type. I think the type is just (void *), otherwise how could we have both int * ptr = NULL and (user-defined type)* ptr = NULL. void type is actually a universal type.
    3. Quoted in "C11(ISO/IEC 9899:201x) §6.3.2.3 Pointers Section 3":

      An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant

    So simply put: NULL pointer is a void pointer constant.

    Any way of using frames in HTML5?

    I have used frames at my continuing education commercial site for over 15 years. Frames allow the navigation frame to load material into the main frame using the target feature while leaving the navigator frame untouched. Furthermore, Perl scripts operate quite well from a frame form returning the output to the same frame. I love frames and will continue using them. CSS is far too complicated for practical use. I have had no problems using frames with HTML5 with IE, Safari, Chrome, or Firefox.

    How can I use Helvetica Neue Condensed Bold in CSS?

    "Helvetica Neue Condensed Bold" get working with firefox:

    .class {
      font-family: "Helvetica Neue";
      font-weight: bold;
      font-stretch: condensed;
    }
    

    But it's fail with Opera.

    Generate class from database table

    Just thought I'd add my own variation of the top answer for anyone who's interested. The main features are:

    • It will automatically generate classes for all the tables in the entire schema. Just specify the schema name.
    • It will add System.Data.Linq.Mapping attributes to the class and each property. Useful for anyone using Linq to SQL.

      declare @TableName sysname
      declare @Result varchar(max)
      declare @schema varchar(20) = 'dbo'
      DECLARE @Cursor CURSOR
      
      SET @Cursor = CURSOR FAST_FORWARD FOR
      SELECT DISTINCT tablename = rc1.TABLE_NAME
      FROM INFORMATION_SCHEMA.Tables rc1
      where rc1.TABLE_SCHEMA = @schema
      
      OPEN @Cursor FETCH NEXT FROM @Cursor INTO @TableName
      
      WHILE (@@FETCH_STATUS = 0)
      BEGIN
      set @Result = '[Table(Name = "' + @schema + '.' + @TableName + '")]
      public class ' + Replace(@TableName, '$', '_') + '
      {'
      
      select @Result = @Result + '
          [Column' + PriKey +']
          public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
      '
      from
      (
          select 
              replace(col.name, ' ', '_') ColumnName,
              col.column_id ColumnId,
              case typ.name 
                  when 'bigint' then 'long'
                  when 'binary' then 'byte[]'
                  when 'bit' then 'bool'
                  when 'char' then 'string'
                  when 'date' then 'DateTime'
                  when 'datetime' then 'DateTime'
                  when 'datetime2' then 'DateTime'
                  when 'datetimeoffset' then 'DateTimeOffset'
                  when 'decimal' then 'decimal'
                  when 'float' then 'double'
                  when 'image' then 'byte[]'
                  when 'int' then 'int'
                  when 'money' then 'decimal'
                  when 'nchar' then 'string'
                  when 'ntext' then 'string'
                  when 'numeric' then 'decimal'
                  when 'nvarchar' then 'string'
                  when 'real' then 'float'
                  when 'smalldatetime' then 'DateTime'
                  when 'smallint' then 'short'
                  when 'smallmoney' then 'decimal'
                  when 'text' then 'string'
                  when 'time' then 'TimeSpan'
                  when 'timestamp' then 'long'
                  when 'tinyint' then 'byte'
                  when 'uniqueidentifier' then 'Guid'
                  when 'varbinary' then 'byte[]'
                  when 'varchar' then 'string'
                  else 'UNKNOWN_' + typ.name
              end ColumnType,
              case 
                  when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier') 
                  then '?' 
                  else '' 
              end NullableSign,
              case
                  when pk.CONSTRAINT_NAME is not null and ic.column_id is not null then '(IsPrimaryKey = true, IsDbGenerated = true)'
                  when pk.CONSTRAINT_NAME is not null then '(IsPrimaryKey = true)'
                  when ic.column_id is not null then '(IsDbGenerated = true)'
                  else ''
              end PriKey
          from sys.columns col
          join sys.types typ on col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
          left outer join sys.identity_columns ic on ic.column_id = col.column_id and col.object_id = ic.object_id
          left outer join (
              SELECT  K.TABLE_NAME ,
                  K.COLUMN_NAME ,
                  K.CONSTRAINT_NAME
              FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
                      JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K ON C.TABLE_NAME = K.TABLE_NAME
                                                                       AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG
                                                                       AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
                                                                       AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME
              where C.CONSTRAINT_TYPE = 'PRIMARY KEY'
          ) pk on pk.COLUMN_NAME = col.name and pk.TABLE_NAME = @TableName
          where col.object_id = object_id(@schema + '.' + @TableName)
      ) t
      order by ColumnId
      
      set @Result = @Result  + '
      }
      
      '
      
      print @Result
      
      FETCH NEXT FROM @Cursor INTO @TableName
      end
      
      CLOSE @Cursor DEALLOCATE @Cursor
      GO
      

    How do I convert an integer to binary in JavaScript?

    Try

    num.toString(2);
    

    The 2 is the radix and can be any base between 2 and 36

    source here

    UPDATE:

    This will only work for positive numbers, Javascript represents negative binary integers in two's-complement notation. I made this little function which should do the trick, I haven't tested it out properly:

    function dec2Bin(dec)
    {
        if(dec >= 0) {
            return dec.toString(2);
        }
        else {
            /* Here you could represent the number in 2s compliment but this is not what 
               JS uses as its not sure how many bits are in your number range. There are 
               some suggestions https://stackoverflow.com/questions/10936600/javascript-decimal-to-binary-64-bit 
            */
            return (~dec).toString(2);
        }
    }
    

    I had some help from here

    How do I change TextView Value inside Java Code?

    First we need to find a Button:

    Button mButton = (Button) findViewById(R.id.my_button);
    

    After that, you must implement View.OnClickListener and there you should find the TextView and execute the method setText:

    mButton.setOnClickListener(new View.OnClickListener {
        public void onClick(View v) {
            final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
            mTextView.setText("Some Text");
        }
    });
    

    Right way to split an std::string into a vector<string>

    Tweaked version from Techie Delight:

    #include <string>
    #include <vector>
    
    std::vector<std::string> split(const std::string& str, char delim) {
        std::vector<std::string> strings;
        size_t start;
        size_t end = 0;
        while ((start = str.find_first_not_of(delim, end)) != std::string::npos) {
            end = str.find(delim, start);
            strings.push_back(str.substr(start, end - start));
        }
        return strings;
    }
    

    Put current changes in a new Git branch

    You can simply check out a new branch, and then commit:

    git checkout -b my_new_branch
    git commit
    

    Checking out the new branch will not discard your changes.

    How to construct a set out of list items in python?

    One general way to construct set in iterative way like this:

    aset = {e for e in alist}
    

    Where can I find the error logs of nginx, using FastCGI and Django?

    Errors are stored in the nginx log file. You can specify it in the root of the nginx configuration file:

    error_log  /var/log/nginx/nginx_error.log  warn;
    

    On Mac OS X with Homebrew, the log file was found by default at the following location:

    /usr/local/var/log/nginx
    

    Pass in an array of Deferreds to $.when()

    As a simple alternative, that does not require $.when.apply or an array, you can use the following pattern to generate a single promise for multiple parallel promises:

    promise = $.when(promise, anotherPromise);
    

    e.g.

    function GetSomeDeferredStuff() {
        // Start with an empty resolved promise (or undefined does the same!)
        var promise;
        var i = 1;
        for (i = 1; i <= 5; i++) {
            var count = i;
    
            promise = $.when(promise,
            $.ajax({
                type: "POST",
                url: '/echo/html/',
                data: {
                    html: "<p>Task #" + count + " complete.",
                    delay: count / 2
                },
                success: function (data) {
                    $("div").append(data);
                }
            }));
        }
        return promise;
    }
    
    $(function () {
        $("a").click(function () {
            var promise = GetSomeDeferredStuff();
            promise.then(function () {
                $("div").append("<p>All done!</p>");
            });
        });
    });
    

    Notes:

    • I figured this one out after seeing someone chain promises sequentially, using promise = promise.then(newpromise)
    • The downside is it creates extra promise objects behind the scenes and any parameters passed at the end are not very useful (as they are nested inside additional objects). For what you want though it is short and simple.
    • The upside is it requires no array or array management.

    how to get the base url in javascript

    Base URL in JavaScript

    Here is simple function for your project to get base URL in JavaScript.

    // base url
    function base_url() {
        var pathparts = location.pathname.split('/');
        if (location.host == 'localhost') {
            var url = location.origin+'/'+pathparts[1].trim('/')+'/'; // http://localhost/myproject/
        }else{
            var url = location.origin; // http://stackoverflow.com
        }
        return url;
    }
    

    Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

    I tried running Android studio 3.0.1 with internet connection. Android studio started downloading something from a link automatically which was showing in Gradle build notification. I can't say this is a sure answer but try this out.. maybe you can get your issue resolved.

    How do I configure PyCharm to run py.test tests?

    With a special Conda python setup which included the pip install for py.test plus usage of the Specs addin (option --spec) (for Rspec like nice test summary language), I had to do ;

    1.Edit the default py.test to include option= --spec , which means use the plugin: https://github.com/pchomik/pytest-spec

    2.Create new test configuration, using py.test. Change its python interpreter to use ~/anaconda/envs/ your choice of interpreters, eg py27 for my namings.

    3.Delete the 'unittests' test configuration.

    4.Now the default test config is py.test with my lovely Rspec style outputs. I love it! Thank you everyone!

    p.s. Jetbrains' doc on run/debug configs is here: https://www.jetbrains.com/help/pycharm/2016.1/run-debug-configuration-py-test.html?search=py.test

    What do all of Scala's symbolic operators mean?

    I divide the operators, for the purpose of teaching, into four categories:

    • Keywords/reserved symbols
    • Automatically imported methods
    • Common methods
    • Syntactic sugars/composition

    It is fortunate, then, that most categories are represented in the question:

    ->    // Automatically imported method
    ||=   // Syntactic sugar
    ++=   // Syntactic sugar/composition or common method
    <=    // Common method
    _._   // Typo, though it's probably based on Keyword/composition
    ::    // Common method
    :+=   // Common method
    

    The exact meaning of most of these methods depend on the class that is defining them. For example, <= on Int means "less than or equal to". The first one, ->, I'll give as example below. :: is probably the method defined on List (though it could be the object of the same name), and :+= is probably the method defined on various Buffer classes.

    So, let's see them.

    Keywords/reserved symbols

    There are some symbols in Scala that are special. Two of them are considered proper keywords, while others are just "reserved". They are:

    // Keywords
    <-  // Used on for-comprehensions, to separate pattern from generator
    =>  // Used for function types, function literals and import renaming
    
    // Reserved
    ( )        // Delimit expressions and parameters
    [ ]        // Delimit type parameters
    { }        // Delimit blocks
    .          // Method call and path separator
    // /* */   // Comments
    #          // Used in type notations
    :          // Type ascription or context bounds
    <: >: <%   // Upper, lower and view bounds
    <? <!      // Start token for various XML elements
    " """      // Strings
    '          // Indicate symbols and characters
    @          // Annotations and variable binding on pattern matching
    `          // Denote constant or enable arbitrary identifiers
    ,          // Parameter separator
    ;          // Statement separator
    _*         // vararg expansion
    _          // Many different meanings
    

    These are all part of the language, and, as such, can be found in any text that properly describe the language, such as Scala Specification(PDF) itself.

    The last one, the underscore, deserve a special description, because it is so widely used, and has so many different meanings. Here's a sample:

    import scala._    // Wild card -- all of Scala is imported
    import scala.{ Predef => _, _ } // Exception, everything except Predef
    def f[M[_]]       // Higher kinded type parameter
    def f(m: M[_])    // Existential type
    _ + _             // Anonymous function placeholder parameter
    m _               // Eta expansion of method into method value
    m(_)              // Partial function application
    _ => 5            // Discarded parameter
    case _ =>         // Wild card pattern -- matches anything
    f(xs: _*)         // Sequence xs is passed as multiple parameters to f(ys: T*)
    case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequence
    

    I probably forgot some other meaning, though.

    Automatically imported methods

    So, if you did not find the symbol you are looking for in the list above, then it must be a method, or part of one. But, often, you'll see some symbol and the documentation for the class will not have that method. When this happens, either you are looking at a composition of one or more methods with something else, or the method has been imported into scope, or is available through an imported implicit conversion.

    These can still be found on ScalaDoc: you just have to know where to look for them. Or, failing that, look at the index (presently broken on 2.9.1, but available on nightly).

    Every Scala code has three automatic imports:

    // Not necessarily in this order
    import _root_.java.lang._      // _root_ denotes an absolute path
    import _root_.scala._
    import _root_.scala.Predef._
    

    The first two only make classes and singleton objects available. The third one contains all implicit conversions and imported methods, since Predef is an object itself.

    Looking inside Predef quickly show some symbols:

    class <:<
    class =:=
    object <%<
    object =:=
    

    Any other symbol will be made available through an implicit conversion. Just look at the methods tagged with implicit that receive, as parameter, an object of type that is receiving the method. For example:

    "a" -> 1  // Look for an implicit from String, AnyRef, Any or type parameter
    

    In the above case, -> is defined in the class ArrowAssoc through the method any2ArrowAssoc that takes an object of type A, where A is an unbounded type parameter to the same method.

    Common methods

    So, many symbols are simply methods on a class. For instance, if you do

    List(1, 2) ++ List(3, 4)
    

    You'll find the method ++ right on the ScalaDoc for List. However, there's one convention that you must be aware when searching for methods. Methods ending in colon (:) bind to the right instead of the left. In other words, while the above method call is equivalent to:

    List(1, 2).++(List(3, 4))
    

    If I had, instead 1 :: List(2, 3), that would be equivalent to:

    List(2, 3).::(1)
    

    So you need to look at the type found on the right when looking for methods ending in colon. Consider, for instance:

    1 +: List(2, 3) :+ 4
    

    The first method (+:) binds to the right, and is found on List. The second method (:+) is just a normal method, and binds to the left -- again, on List.

    Syntactic sugars/composition

    So, here's a few syntactic sugars that may hide a method:

    class Example(arr: Array[Int] = Array.fill(5)(0)) {
      def apply(n: Int) = arr(n)
      def update(n: Int, v: Int) = arr(n) = v
      def a = arr(0); def a_=(v: Int) = arr(0) = v
      def b = arr(1); def b_=(v: Int) = arr(1) = v
      def c = arr(2); def c_=(v: Int) = arr(2) = v
      def d = arr(3); def d_=(v: Int) = arr(3) = v
      def e = arr(4); def e_=(v: Int) = arr(4) = v
      def +(v: Int) = new Example(arr map (_ + v))
      def unapply(n: Int) = if (arr.indices contains n) Some(arr(n)) else None
    }
    
    val Ex = new Example // or var for the last example
    println(Ex(0))  // calls apply(0)
    Ex(0) = 2       // calls update(0, 2)
    Ex.b = 3        // calls b_=(3)
    // This requires Ex to be a "val"
    val Ex(c) = 2   // calls unapply(2) and assigns result to c
    // This requires Ex to be a "var"
    Ex += 1         // substituted for Ex = Ex + 1
    

    The last one is interesting, because any symbolic method can be combined to form an assignment-like method that way.

    And, of course, there's various combinations that can appear in code:

    (_+_) // An expression, or parameter, that is an anonymous function with
          // two parameters, used exactly where the underscores appear, and
          // which calls the "+" method on the first parameter passing the
          // second parameter as argument.
    

    How to get the current time in milliseconds from C in Linux?

    This version need not math library and checked the return value of clock_gettime().

    #include <time.h>
    #include <stdlib.h>
    #include <stdint.h>
    
    /**
     * @return milliseconds
     */
    uint64_t get_now_time() {
      struct timespec spec;
      if (clock_gettime(1, &spec) == -1) { /* 1 is CLOCK_MONOTONIC */
        abort();
      }
    
      return spec.tv_sec * 1000 + spec.tv_nsec / 1e6;
    }
    

    Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

    Do not use primitives in your Entity classes, use instead their respective wrappers. That will fix this problem.

    Out of your Entity classes you can use the != null validation for the rest of your code flow.

    Bootstrap 4 navbar color

    To change navbar background color:

    .navbar-custom {
    
        background-color: yourcolor !important;
    }
    

    android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

    This link may help you. Try checking in your manifest for problems. If you can get it to happen again, post your entire stack trace so that we can see what the error actually is.

    EDIT: I'm sure you've checked this, but what is on line 12 of the XML file you use for the TourActivity layout?

    IOCTL Linux device driver

    The ioctl function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl could be used to get the current font as well as set the font to a new one. A user application uses ioctl to send a code to a printer telling it to return the current font or to set the font to a new one.

    int ioctl(int fd, int request, ...)
    
    1. fd is file descriptor, the one returned by open;
    2. request is request code. e.g GETFONT will get the current font from the printer, SETFONT will set the font on the printer;
    3. the third argument is void *. Depending on the second argument, the third may or may not be present, e.g. if the second argument is SETFONT, the third argument can be the font name such as "Arial";

    int request is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl and then uses the request code in the device driver module to determine which action to perform.

    A request code has 4 main parts

        1. A Magic number - 8 bits
        2. A sequence number - 8 bits
        3. Argument type (typically 14 bits), if any.
        4. Direction of data transfer (2 bits).  
    

    If the request code is SETFONT to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial" to the printer). If the request code is GETFONT, direction is from printer to the user application.

    In order to generate a request code, Linux provides some predefined function-like macros.

    1._IO(MAGIC, SEQ_NO) both are 8 bits, 0 to 255, e.g. let us say we want to pause printer. This does not require a data transfer. So we would generate the request code as below

    #define PRIN_MAGIC 'P'
    #define NUM 0
    #define PAUSE_PRIN __IO(PRIN_MAGIC, NUM) 
    

    and now use ioctl as

    ret_val = ioctl(fd, PAUSE_PRIN);
    

    The corresponding system call in the driver module will receive the code and pause the printer.

    1. __IOW(MAGIC, SEQ_NO, TYPE) MAGIC and SEQ_NO are the same as above, and TYPE gives the type of the next argument, recall the third argument of ioctl is void *. W in __IOW indicates that the data flow is from user application to driver module. As an example, suppose we want to set the printer font to "Arial".
    #define PRIN_MAGIC 'S'
    #define SEQ_NO 1
    #define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)
    

    further,

    char *font = "Arial";
    ret_val = ioctl(fd, SETFONT, font); 
    

    Now font is a pointer, which means it is an address best represented as unsigned long, hence the third part of _IOW mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE) and __IORW(MAGIC, SEQ_NO, TYPE) where the data flow will be from kernel space to user space and both ways respectively.

    Please let me know if this helps!

    insert vertical divider line between two nested divs, not full height

    Use a div for your divider. It will always be centered vertically regardless to whether left and right divs are equal in height. You can reuse it anywhere on your site.

    .divider{
        position:absolute;
        left:50%;
        top:10%;
        bottom:10%;
        border-left:1px solid white;
    }
    

    Check working example at http://jsfiddle.net/gtKBs/

    How do I exclude Weekend days in a SQL Server query?

    SELECT date_created
    FROM your_table
    WHERE DATENAME(dw, date_created) NOT IN ('Saturday', 'Sunday')
    

    Jackson JSON custom serialization for certain fields

    You can create a custom serializer inline in the mixin. Then annotate a field with it. See example below that appends " - something else " to lang field. This is kind of hackish - if your serializer requires something like a repository or anything injected by spring, this is going to be a problem. Probably best to use a custom deserializer/serializer instead of a mixin.

    package com.test;
    
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.annotation.JsonPropertyOrder;
    import com.fasterxml.jackson.core.JsonGenerator;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.JsonSerializer;
    import com.fasterxml.jackson.databind.SerializerProvider;
    import com.fasterxml.jackson.databind.annotation.JsonSerialize;
    import com.test.Argument;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    //Serialize only fields explicitly mentioned by this mixin.
    @JsonAutoDetect(
        fieldVisibility = Visibility.NONE,
        setterVisibility = Visibility.NONE,
        getterVisibility = Visibility.NONE,
        isGetterVisibility = Visibility.NONE,
        creatorVisibility = Visibility.NONE
    )
    @JsonPropertyOrder({"lang", "name", "value"})
    public abstract class V2ArgumentMixin {
    
      @JsonProperty("name")
      private String name;
    
      @JsonSerialize(using = LangCustomSerializer.class, as=String.class)
      @JsonProperty("lang")
      private String lang;
    
      @JsonProperty("value")
      private Object value;
    
    
      
      public static class LangCustomSerializer extends JsonSerializer<String> {
    
        @Override
        public void serialize(String value,
                              JsonGenerator jsonGenerator,
                              SerializerProvider serializerProvider)
            throws IOException, JsonProcessingException {
          jsonGenerator.writeObject(value.toString() + "  - something else");
        }
      }
    }
    

    make iframe height dynamic based on content inside- JQUERY/Javascript

    You can refer related question here - How to make width and height of iframe same as its parent div?

    To set dynamic height -

    1. We need to communicate with cross domain iFrames and parent
    2. Then we can send scroll height/content height of iframe to parent window

    And codes - https://gist.github.com/mohandere/a2e67971858ee2c3999d62e3843889a8

    What is 0x10 in decimal?

    It's a hex number and is 16 decimal.

    What is the difference between <p> and <div>?

    Think of DIV as a grouping element. You put elements in a DIV element so that you can set their alignments

    Whereas "p" is simply to create a new paragraph.

    Convert generic List/Enumerable to DataTable?

    This link on MSDN is worth a visit: How to: Implement CopyToDataTable<T> Where the Generic Type T Is Not a DataRow

    This adds an extension method that lets you do this:

    // Create a sequence. 
    Item[] items = new Item[] 
    { new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"}, 
      new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
      new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
      new Movie{Id = 1, Price = 13.40, Genre = "Action", Director = "Emmanuel Fernandez"}};
    
    // Query for items with price greater than 9.99.
    var query = from i in items
                 where i.Price > 9.99
                 orderby i.Price
                 select i;
    
    // Load the query results into new DataTable.
    DataTable table = query.CopyToDataTable();
    

    Installing and Running MongoDB on OSX

    Make sure you are logged in as root user in your terminal.

    Steps to start mongodb server in your mac

    1. Open Terminal
    2. Run the command sudo su
    3. Enter your administrator password
    4. run the command mongod
    5. MongoDb Server starts

    Hope it helps you. Thanks

    LINQ query to return a Dictionary<string, string>

    Look at the ToLookup and/or ToDictionary extension methods.

    Difference between Static methods and Instance methods

    The behavior of an object depends on the variables and the methods of that class. When we create a class we create an object for it. For static methods, we don't require them as static methods means all the objects will have the same copy so there is no need of an object. e.g:

    Myclass.get();
    

    In instance method each object will have different behaviour so they have to call the method using the object instance. e.g:

    Myclass x = new Myclass();
    x.get();
    

    How to format a QString?

    Use QString::arg() for the same effect.

    Handling click events on a drawable within an EditText

    Here's my simple solution, just place ImageButton over EditText:

    <RelativeLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content">
    
      <EditText android:id="@+id/editTextName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:imeOptions="actionSearch"
        android:inputType="text"/>
    
      <ImageButton android:id="@+id/imageViewSearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_action_search"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"/>
    
    </RelativeLayout>
    

    Single vs double quotes in JSON

    JSON syntax is not Python syntax. JSON requires double quotes for its strings.

    What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

    By any chance have you tried POST vs post? This support article suggests it can cause problems with IIS: http://support.microsoft.com/?id=828726

    Python Loop: List Index Out of Range

    1. In your for loop, you're iterating through the elements of a list a. But in the body of the loop, you're using those items to index that list, when you actually want indexes.
      Imagine if the list a would contain 5 items, a number 100 would be among them and the for loop would reach it. You will essentially attempt to retrieve the 100th element of the list a, which obviously is not there. This will give you an IndexError.

    We can fix this issue by iterating over a range of indexes instead:

    for i in range(len(a))
    

    and access the a's items like that: a[i]. This won't give any errors.

    1. In the loop's body, you're indexing not only a[i], but also a[i+1]. This is also a place for a potential error. If your list contains 5 items and you're iterating over it like I've shown in the point 1, you'll get an IndexError. Why? Because range(5) is essentially 0 1 2 3 4, so when the loop reaches 4, you will attempt to get the a[5] item. Since indexing in Python starts with 0 and your list contains 5 items, the last item would have an index 4, so getting the a[5] would mean getting the sixth element which does not exist.

    To fix that, you should subtract 1 from len(a) in order to get a range sequence 0 1 2 3. Since you're using an index i+1, you'll still get the last element, but this way you will avoid the error.

    1. There are many different ways to accomplish what you're trying to do here. Some of them are quite elegant and more "pythonic", like list comprehensions:

    b = [a[i] + a[i+1] for i in range(len(a) - 1)]

    This does the job in only one line.

    How can I change all input values to uppercase using Jquery?

    $('#id-submit').click(function () {
        $("input").val(function(i,val) {
            return val.toUpperCase();
        });
    });
    

    FIDDLE

    Binding IIS Express to an IP Address

    Below are the complete changes I needed to make to run my x64 bit IIS application using IIS Express, so that it was accessible to a remote host:

    iisexpress /config:"C:\Users\test-user\Documents\IISExpress\config\applicationhost.config" /site:MyWebSite
    Starting IIS Express ...
    Successfully registered URL "http://192.168.2.133:8080/" for site "MyWebSite" application "/"
    Registration completed for site "MyWebSite"
    IIS Express is running.
    Enter 'Q' to stop IIS Express
    

    The configuration file (applicationhost.config) had a section added as follows:

    <sites>
      <site name="MyWebsite" id="2">
        <application path="/" applicationPool="Clr4IntegratedAppPool">
          <virtualDirectory path="/" physicalPath="C:\build\trunk\MyWebsite" />
        </application>
        <bindings>
          <binding protocol="http" bindingInformation=":8080:192.168.2.133" />
        </bindings>
      </site>
    

    The 64 bit version of the .NET framework can be enabled as follows:

    <globalModules>
        <!--
            <add name="ManagedEngine" image="%windir%\Microsoft.NET\Framework\v2.0.50727\webengine.dll" preCondition="integratedMode,runtimeVersionv2.0,bitness32" />
            <add name="ManagedEngineV4.0_32bit" image="%windir%\Microsoft.NET\Framework\v4.0.30319\webengine4.dll" preCondition="integratedMode,runtimeVersionv4.0,bitness32" />
        -->             
        <add name="ManagedEngine64" image="%windir%\Microsoft.NET\Framework64\v4.0.30319\webengine4.dll" preCondition="integratedMode,runtimeVersionv4.0,bitness64" />
    

    How to concatenate two strings to build a complete path

    I was working around with my shell script which need to do some path joining stuff like you do.

    The thing is, both path like

    /data/foo/bar
    
    /data/foo/bar/ 
    

    are valid.

    If I want to append a file to this path like

    /data/foo/bar/myfile
    

    there was no native method (like os.path.join() in python) in shell to handle such situation.

    But I did found a trick

    For example , the base path was store in a shell variable

    BASE=~/mydir
    

    and the last file name you wanna join was

    FILE=myfile
    

    Then you can assign your new path like this

    NEW_PATH=$(realpath ${BASE})/FILE
    

    and then you`ll get

    $ echo $NEW_PATH
    
    /path/to/your/home/mydir/myfile
    

    the reason is quiet simple, the "realpath" command would always trim the terminating slash for you if necessary

    How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

    I noticed following line from error.

    exact fetch returns more than requested number of rows
    

    That means Oracle was expecting one row but It was getting multiple rows. And, only dual table has that characteristic, which returns only one row.

    Later I recall, I have done few changes in dual table and when I executed dual table. Then found multiple rows.

    So, I truncated dual table and inserted only row which X value. And, everything working fine.

    How to set fake GPS location on IOS real device

    I had a similar issue, but with no source code to run on Xcode.

    So if you want to test an application on a real device with a fake location you should use a VPN application.

    There are plenty in the App Store to choose from - free ones without the option to choose a specific country/city and free ones which assign you a random location or asks you to choose from a limited set of default options.

    PHPmailer sending HTML CODE

    do like this-paste your html code inside your separate html file using GET method.

    $mail->IsHTML(true);                                 
        $mail->WordWrap = 70;                                 
        $mail->addAttachment= $_GET['addattachment']; $mail->AltBody   
        =$_GET['AltBody'];  $mail->Subject = $_GET['subject']; $mail->Body = $_GET['body'];
    

    How do I resolve a TesseractNotFoundError?

    Just run these command if you are using linux,

    sudo apt update
    sudo apt install tesseract-ocr
    sudo apt install libtesseract-dev
    

    then run this,

    python -m pip install tesseract tesseract-ocr pytesseract
    

    InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

    Add below code in your client code :

    static {
        Security.insertProviderAt(new BouncyCastleProvider(),1);
     }
    

    with this there is no need to add any entry in java.security file.

    How do I script a "yes" response for installing programs?

    You just need to put -y with the install command.

    For example: yum install <package_to_install> -y

    Scroll / Jump to id without jQuery

    Maybe You should try scrollIntoView.

    document.getElementById('id').scrollIntoView();
    

    This will scroll to your Element.

    where is gacutil.exe?

    1. Open Developer Command prompt.
    2. type

    where gacutil

    javascript onclick increment number

    <body>
        <input type="button" value="Increase" id="inc" onclick="incNumber()"/>
        <input type="button" value="Decrease" id="dec" onclick="decNumber()"/>
    
        <label id="display"></label>
    
        <script type="text/javascript">
    
        var i = 0;
    
        function incNumber() {
            if (i < 10) {
                i++;
            } else if (i = 10) {
                i = 0;
            }
            document.getElementById("display").innerHTML = i;
        }
    
        function decNumber() {
            if (i > 0) {
                --i;
            } else if (i = 0) {
                i = 10;
            }
            document.getElementById("display").innerHTML = i;
        }
        </script>
    </body>
    

    Ruby: kind_of? vs. instance_of? vs. is_a?

    kind_of? and is_a? are synonymous.

    instance_of? is different from the other two in that it only returns true if the object is an instance of that exact class, not a subclass.

    Example:

    • "hello".is_a? Object and "hello".kind_of? Object return true because "hello" is a String and String is a subclass of Object.
    • However "hello".instance_of? Object returns false.

    How do I pre-populate a jQuery Datepicker textbox with today's date?

    Set to today:

    $('#date_pretty').datepicker('setDate', '+0');
    

    Set to yesterday:

    $('#date_pretty').datepicker('setDate', '-1');
    

    And so on with any number of days before or after today's date.

    See jQuery UI › Methods › setDate.

    Create Generic method constraining T to an Enum

    I modified the sample by dimarzionist. This version will only work with Enums and not let structs get through.

    public static T ParseEnum<T>(string enumString)
        where T : struct // enum 
        {
        if (String.IsNullOrEmpty(enumString) || !typeof(T).IsEnum)
           throw new Exception("Type given must be an Enum");
        try
        {
    
           return (T)Enum.Parse(typeof(T), enumString, true);
        }
        catch (Exception ex)
        {
           return default(T);
        }
    }
    

    fork() child and parent processes

    This is the correct way for getting the correct output.... However, childs parent id maybe sometimes printed as 1 because parent process gets terminated and the root process with pid = 1 controls this orphan process.

     pid_t  pid;
     pid = fork();
     if (pid == 0) 
        printf("This is the child process. My pid is %d and my parent's id 
          is %d.\n", getpid(), getppid());
     else 
         printf("This is the parent process. My pid is %d and my parent's 
             id is %d.\n", getpid(), pid);
    

    org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

    You are trying to read xls with explicit implementation poi classes for xlsx.

    G:\Selenium Jar Files\TestData\Data.xls

    Either use HSSFWorkbook and HSSFSheet classes or make your implementation more generic by using shared interfaces, like;

    Change:

    XSSFWorkbook workbook = new XSSFWorkbook(file);
    

    To:

     org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);
    

    And Change:

    XSSFSheet sheet = workbook.getSheetAt(0);
    

    To:

    org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
    

    Change Bootstrap input focus blue glow

    I landed to this thread looking for the way to disable glow altogether. Many answers were overcomplicated for my purpose. For easy solution, I just needed one line of CSS as follows.

    input, textarea, button {outline: none; }
    

    How to execute an Oracle stored procedure via a database link

    for me, this worked

    exec utl_mail.send@myotherdb(
      sender => '[email protected]',recipients => '[email protected], 
      cc => null, subject => 'my subject', message => 'my message'
    ); 
    

    Split array into chunks

    ES6 one-line approach based on Array.prototype reduce and push methods:

    const doChunk = (list, size) => list.reduce((r, v) =>
      (!r.length || r[r.length - 1].length === size ?
        r.push([v]) : r[r.length - 1].push(v)) && r
    , []);
    
    console.log(doChunk([0,1,2,3,4,5,6,7,8,9,10,11,12], 5));
    // [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12]]
    

    Invalid date in safari

    use the format 'mm/dd/yyyy'. For example :- new Date('02/28/2015'). It works well in all browsers.

    How can I run an EXE program from a Windows Service using C#?

    You should check this MSDN article and download the .docx file and read it carefully , it was very helpful for me.

    However this is a class which works fine for my case :

        [StructLayout(LayoutKind.Sequential)]
        internal struct PROCESS_INFORMATION
        {
            public IntPtr hProcess;
            public IntPtr hThread;
            public uint dwProcessId;
            public uint dwThreadId;
        }
        
        [StructLayout(LayoutKind.Sequential)]
        internal struct SECURITY_ATTRIBUTES
        {
            public uint nLength;
            public IntPtr lpSecurityDescriptor;
            public bool bInheritHandle;
        }
    
    
        [StructLayout(LayoutKind.Sequential)]
        public struct STARTUPINFO
        {
            public uint cb;
            public string lpReserved;
            public string lpDesktop;
            public string lpTitle;
            public uint dwX;
            public uint dwY;
            public uint dwXSize;
            public uint dwYSize;
            public uint dwXCountChars;
            public uint dwYCountChars;
            public uint dwFillAttribute;
            public uint dwFlags;
            public short wShowWindow;
            public short cbReserved2;
            public IntPtr lpReserved2;
            public IntPtr hStdInput;
            public IntPtr hStdOutput;
            public IntPtr hStdError;
    
        }
    
        internal enum SECURITY_IMPERSONATION_LEVEL
        {
            SecurityAnonymous,
            SecurityIdentification,
            SecurityImpersonation,
            SecurityDelegation
        }
    
        internal enum TOKEN_TYPE
        {
            TokenPrimary = 1,
            TokenImpersonation
        }
    
        public static class ProcessAsUser
        {
    
            [DllImport("advapi32.dll", SetLastError = true)]
            private static extern bool CreateProcessAsUser(
                IntPtr hToken,
                string lpApplicationName,
                string lpCommandLine,
                ref SECURITY_ATTRIBUTES lpProcessAttributes,
                ref SECURITY_ATTRIBUTES lpThreadAttributes,
                bool bInheritHandles,
                uint dwCreationFlags,
                IntPtr lpEnvironment,
                string lpCurrentDirectory,
                ref STARTUPINFO lpStartupInfo,
                out PROCESS_INFORMATION lpProcessInformation);
    
    
            [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx", SetLastError = true)]
            private static extern bool DuplicateTokenEx(
                IntPtr hExistingToken,
                uint dwDesiredAccess,
                ref SECURITY_ATTRIBUTES lpThreadAttributes,
                Int32 ImpersonationLevel,
                Int32 dwTokenType,
                ref IntPtr phNewToken);
    
    
            [DllImport("advapi32.dll", SetLastError = true)]
            private static extern bool OpenProcessToken(
                IntPtr ProcessHandle,
                UInt32 DesiredAccess,
                ref IntPtr TokenHandle);
    
            [DllImport("userenv.dll", SetLastError = true)]
            private static extern bool CreateEnvironmentBlock(
                    ref IntPtr lpEnvironment,
                    IntPtr hToken,
                    bool bInherit);
    
    
            [DllImport("userenv.dll", SetLastError = true)]
            private static extern bool DestroyEnvironmentBlock(
                    IntPtr lpEnvironment);
    
            [DllImport("kernel32.dll", SetLastError = true)]
            private static extern bool CloseHandle(
                IntPtr hObject);
    
            private const short SW_SHOW = 5;
            private const uint TOKEN_QUERY = 0x0008;
            private const uint TOKEN_DUPLICATE = 0x0002;
            private const uint TOKEN_ASSIGN_PRIMARY = 0x0001;
            private const int GENERIC_ALL_ACCESS = 0x10000000;
            private const int STARTF_USESHOWWINDOW = 0x00000001;
            private const int STARTF_FORCEONFEEDBACK = 0x00000040;
            private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;
    
    
            private static bool LaunchProcessAsUser(string cmdLine, IntPtr token, IntPtr envBlock)
            {
                bool result = false;
    
    
                PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
                SECURITY_ATTRIBUTES saProcess = new SECURITY_ATTRIBUTES();
                SECURITY_ATTRIBUTES saThread = new SECURITY_ATTRIBUTES();
                saProcess.nLength = (uint)Marshal.SizeOf(saProcess);
                saThread.nLength = (uint)Marshal.SizeOf(saThread);
    
                STARTUPINFO si = new STARTUPINFO();
                si.cb = (uint)Marshal.SizeOf(si);
    
    
                //if this member is NULL, the new process inherits the desktop
                //and window station of its parent process. If this member is
                //an empty string, the process does not inherit the desktop and
                //window station of its parent process; instead, the system
                //determines if a new desktop and window station need to be created.
                //If the impersonated user already has a desktop, the system uses the
                //existing desktop.
    
                si.lpDesktop = @"WinSta0\Default"; //Modify as needed
                si.dwFlags = STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK;
                si.wShowWindow = SW_SHOW;
                //Set other si properties as required.
    
                result = CreateProcessAsUser(
                    token,
                    null,
                    cmdLine,
                    ref saProcess,
                    ref saThread,
                    false,
                    CREATE_UNICODE_ENVIRONMENT,
                    envBlock,
                    null,
                    ref si,
                    out pi);
    
    
                if (result == false)
                {
                    int error = Marshal.GetLastWin32Error();
                    string message = String.Format("CreateProcessAsUser Error: {0}", error);
                    FilesUtilities.WriteLog(message,FilesUtilities.ErrorType.Info);
    
                }
    
                return result;
            }
    
    
            private static IntPtr GetPrimaryToken(int processId)
            {
                IntPtr token = IntPtr.Zero;
                IntPtr primaryToken = IntPtr.Zero;
                bool retVal = false;
                Process p = null;
    
                try
                {
                    p = Process.GetProcessById(processId);
                }
    
                catch (ArgumentException)
                {
    
                    string details = String.Format("ProcessID {0} Not Available", processId);
                    FilesUtilities.WriteLog(details, FilesUtilities.ErrorType.Info);
                    throw;
                }
    
    
                //Gets impersonation token
                retVal = OpenProcessToken(p.Handle, TOKEN_DUPLICATE, ref token);
                if (retVal == true)
                {
    
                    SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
                    sa.nLength = (uint)Marshal.SizeOf(sa);
    
                    //Convert the impersonation token into Primary token
                    retVal = DuplicateTokenEx(
                        token,
                        TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY,
                        ref sa,
                        (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
                        (int)TOKEN_TYPE.TokenPrimary,
                        ref primaryToken);
    
                    //Close the Token that was previously opened.
                    CloseHandle(token);
                    if (retVal == false)
                    {
                        string message = String.Format("DuplicateTokenEx Error: {0}", Marshal.GetLastWin32Error());
                        FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);
    
                    }
    
                }
    
                else
                {
    
                    string message = String.Format("OpenProcessToken Error: {0}", Marshal.GetLastWin32Error());
                    FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);
    
                }
    
                //We'll Close this token after it is used.
                return primaryToken;
    
            }
    
            private static IntPtr GetEnvironmentBlock(IntPtr token)
            {
    
                IntPtr envBlock = IntPtr.Zero;
                bool retVal = CreateEnvironmentBlock(ref envBlock, token, false);
                if (retVal == false)
                {
    
                    //Environment Block, things like common paths to My Documents etc.
                    //Will not be created if "false"
                    //It should not adversley affect CreateProcessAsUser.
    
                    string message = String.Format("CreateEnvironmentBlock Error: {0}", Marshal.GetLastWin32Error());
                    FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);
    
                }
                return envBlock;
            }
    
            public static bool Launch(string appCmdLine /*,int processId*/)
            {
    
                bool ret = false;
    
                //Either specify the processID explicitly
                //Or try to get it from a process owned by the user.
                //In this case assuming there is only one explorer.exe
    
                Process[] ps = Process.GetProcessesByName("explorer");
                int processId = -1;//=processId
                if (ps.Length > 0)
                {
                    processId = ps[0].Id;
                }
    
                if (processId > 1)
                {
                    IntPtr token = GetPrimaryToken(processId);
    
                    if (token != IntPtr.Zero)
                    {
    
                        IntPtr envBlock = GetEnvironmentBlock(token);
                        ret = LaunchProcessAsUser(appCmdLine, token, envBlock);
                        if (envBlock != IntPtr.Zero)
                            DestroyEnvironmentBlock(envBlock);
    
                        CloseHandle(token);
                    }
    
                }
                return ret;
            }
    
        }
    

    And to execute , simply call like this :

    string szCmdline = "AbsolutePathToYourExe\\ExeNameWithoutExtension";
    ProcessAsUser.Launch(szCmdline);
    

    Android studio - Failed to find target android-18

    I solved the problem by changing the compileSdkVersion in the Gradle.build file from 18 to 17.

    buildscript {
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:0.5.+'
        }
    }
    apply plugin: 'android'
    
    repositories {
        mavenCentral()
    }
    
    android {
        compileSdkVersion 17
        buildToolsVersion "17.0.0"
    
        defaultConfig {
            minSdkVersion 10
            targetSdkVersion 18
        }
    }
    
    dependencies {
        compile 'com.android.support:support-v4:13.0.+'
    }
    

    Check if enum exists in Java

    Since Java 8, we could use streams instead of for loops. Also, it might be apropriate to return an Optional if the enum does not have an instance with such a name.

    I have come up with the following three alternatives on how to look up an enum:

    private enum Test {
        TEST1, TEST2;
    
        public Test fromNameOrThrowException(String name) {
            return Arrays.stream(values())
                    .filter(e -> e.name().equals(name))
                    .findFirst()
                    .orElseThrow(() -> new IllegalArgumentException("No enum with name " + name));
        }
    
        public Test fromNameOrNull(String name) {
            return Arrays.stream(values()).filter(e -> e.name().equals(name)).findFirst().orElse(null);
        }
    
        public Optional<Test> fromName(String name) {
            return Arrays.stream(values()).filter(e -> e.name().equals(name)).findFirst();
        }
    }
    

    How do I reference a local image in React?

    import image from './img/one.jpg';
    
    class Icons extends React.Component{
        render(){
          return(
            <img className='profile-image' alt='icon' src={image}/>
        );
        }
    }
    export default Icons;
    

    How can I count the occurrences of a list item?

    use %timeit to see which operation is more efficient. np.array counting operations should be faster.

     from collections import Counter
     mylist = [1,7,7,7,3,9,9,9,7,9,10,0] 
     types_counts=Counter(mylist)
     print(types_counts)
    

    Javascript - object key->value

    Use [] notation for string representations of properties:

    console.log(obj[name]);
    

    Otherwise it's looking for the "name" property, rather than the "a" property.

    multiple where condition codeigniter

    $wherecond = "( ( ( username ='" . $username . "' OR status='" . $status . "') AND (id='" . $id . "') ) )"; $this->db->where($wherecond);

    If you want to add AND and OR conditions at a time. this will work.

    how to hide a vertical scroll bar when not needed

    overflow: auto (or overflow-y: auto) is the correct way to go.

    The problem is that your text area is taller than your div. The div ends up cutting off the textbox, so even though it looks like it should start scrolling when the text is taller than 159px it won't start scrolling until the text is taller than 400px which is the height of the textbox.

    Try this: http://jsfiddle.net/G9rfq/1/

    I set overflow:auto on the text box, and made the textbox the same size as the div.

    Also I don't believe it's valid to have a div inside a label, the browser will render it, but it might cause some funky stuff to happen. Also your div isn't closed.

    Create hyperlink to another sheet

    I recorded a macro making a hiperlink. This resulted.

    ActiveCell.FormulaR1C1 = "=HYPERLINK(""[Workbook.xlsx]Sheet1!A1"",""CLICK HERE"")"
    

    Lost connection to MySQL server during query?

    This can also happen if someone or something kills your connection using the KILL command.

    how to dynamically add options to an existing select in vanilla javascript

    Use the document.createElement function and then add it as a child of your select.

    var newOption = document.createElement("option");
    newOption.text = 'the options text';
    newOption.value = 'some value if you want it';
    daySelect.appendChild(newOption);
    

    Real mouse position in canvas

    The Simple 1:1 Scenario

    For situations where the canvas element is 1:1 compared to the bitmap size, you can get the mouse positions by using this snippet:

    function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
          x: evt.clientX - rect.left,
          y: evt.clientY - rect.top
        };
    }
    

    Just call it from your event with the event and canvas as arguments. It returns an object with x and y for the mouse positions.

    As the mouse position you are getting is relative to the client window you'll have to subtract the position of the canvas element to convert it relative to the element itself.

    Example of integration in your code:

    //put this outside the event loop..
    var canvas = document.getElementById("imgCanvas");
    var context = canvas.getContext("2d");
    
    function draw(evt) {
        var pos = getMousePos(canvas, evt);
    
        context.fillStyle = "#000000";
        context.fillRect (pos.x, pos.y, 4, 4);
    }
    

    Note: borders and padding will affect position if applied directly to the canvas element so these needs to be considered via getComputedStyle() - or apply those styles to a parent div instead.

    When Element and Bitmap are of different sizes

    When there is the situation of having the element at a different size than the bitmap itself, for example, the element is scaled using CSS or there is pixel-aspect ratio etc. you will have to address this.

    Example:

    function  getMousePos(canvas, evt) {
      var rect = canvas.getBoundingClientRect(), // abs. size of element
          scaleX = canvas.width / rect.width,    // relationship bitmap vs. element for X
          scaleY = canvas.height / rect.height;  // relationship bitmap vs. element for Y
    
      return {
        x: (evt.clientX - rect.left) * scaleX,   // scale mouse coordinates after they have
        y: (evt.clientY - rect.top) * scaleY     // been adjusted to be relative to element
      }
    }
    

    With transformations applied to context (scale, rotation etc.)

    Then there is the more complicated case where you have applied transformation to the context such as rotation, skew/shear, scale, translate etc. To deal with this you can calculate the inverse matrix of the current matrix.

    Newer browsers let you read the current matrix via the currentTransform property and Firefox (current alpha) even provide a inverted matrix through the mozCurrentTransformInverted. Firefox however, via mozCurrentTransform, will return an Array and not DOMMatrix as it should. Neither Chrome, when enabled via experimental flags, will return a DOMMatrix but a SVGMatrix.

    In most cases however you will have to implement a custom matrix solution of your own (such as my own solution here - free/MIT project) until this get full support.

    When you eventually have obtained the matrix regardless of path you take to obtain one, you'll need to invert it and apply it to your mouse coordinates. The coordinates are then passed to the canvas which will use its matrix to convert it to back wherever it is at the moment.

    This way the point will be in the correct position relative to the mouse. Also here you need to adjust the coordinates (before applying the inverse matrix to them) to be relative to the element.

    An example just showing the matrix steps

    function draw(evt) {
        var pos = getMousePos(canvas, evt);        // get adjusted coordinates as above
        var imatrix = matrix.inverse();            // get inverted matrix somehow
        pos = imatrix.applyToPoint(pos.x, pos.y);  // apply to adjusted coordinate
    
        context.fillStyle = "#000000";
        context.fillRect(pos.x-1, pos.y-1, 2, 2);
    }
    

    An example of using currentTransform when implemented would be:

        var pos = getMousePos(canvas, e);          // get adjusted coordinates as above
        var matrix = ctx.currentTransform;         // W3C (future)
        var imatrix = matrix.invertSelf();         // invert
    
        // apply to point:
        var x = pos.x * imatrix.a + pos.y * imatrix.c + imatrix.e;
        var y = pos.x * imatrix.b + pos.y * imatrix.d + imatrix.f;
    

    Update I made a free solution (MIT) to embed all these steps into a single easy-to-use object that can be found here and also takes care of a few other nitty-gritty things most ignore.

    Test if string is a number in Ruby on Rails

    In rails 4, you need to put require File.expand_path('../../lib', __FILE__) + '/ext/string' in your config/application.rb

    How to query between two dates using Laravel and Eloquent?

    If you need to have in when a datetime field should be like this.

    return $this->getModel()->whereBetween('created_at', [$dateStart." 00:00:00",$dateEnd." 23:59:59"])->get();
    

    Create a folder if it doesn't already exist

    You can try also:

    $dirpath = "path/to/dir";
    $mode = "0764";
    is_dir($dirpath) || mkdir($dirpath, $mode, true);
    

    Command line: search and replace in all filenames matched by grep

    This works using grep without needing to use perl or find.

    grep -rli 'old-word' * | xargs -i@ sed -i 's/old-word/new-word/g' @
    

    How to get value by key from JObject?

    Try this:

    private string GetJArrayValue(JObject yourJArray, string key)
    {
        foreach (KeyValuePair<string, JToken> keyValuePair in yourJArray)
        {
            if (key == keyValuePair.Key)
            {
                return keyValuePair.Value.ToString();
            }
        }
    }
    

    What is the PostgreSQL equivalent for ISNULL()

    Create the following function

    CREATE OR REPLACE FUNCTION isnull(text, text) RETURNS text AS 'SELECT (CASE (SELECT $1 "
        "is null) WHEN true THEN $2 ELSE $1 END) AS RESULT' LANGUAGE 'sql'
    

    And it'll work.

    You may to create different versions with different parameter types.

    How do I refresh a DIV content?

    To reload a section of the page, you could use jquerys load with the current url and specify the fragment you need, which would be the same element that load is called on, in this case #here:

    function updateDiv()
    { 
        $( "#here" ).load(window.location.href + " #here" );
    }
    
    • Don't disregard the space within the load element selector: + " #here"

    This function can be called within an interval, or attached to a click event

    Should Gemfile.lock be included in .gitignore?

    The other answers here are correct: Yes, your Ruby app (not your Ruby gem) should include Gemfile.lock in the repo. To expand on why it should do this, read on:

    I was under the mistaken notion that each env (development, test, staging, prod...) each did a bundle install to build their own Gemfile.lock. My assumption was based on the fact that Gemfile.lock does not contain any grouping data, such as :test, :prod, etc. This assumption was wrong, as I found out in a painful local problem.

    Upon closer investigation, I was confused why my Jenkins build showed fetching a particular gem (ffaker, FWIW) successfully, but when the app loaded and required ffaker, it said file not found. WTF?

    A little more investigation and experimenting showed what the two files do:

    First it uses Gemfile.lock to go fetch all the gems, even those that won't be used in this particular env. Then it uses Gemfile to choose which of those fetched gems to actually use in this env.

    So, even though it fetched the gem in the first step based on Gemfile.lock, it did NOT include in my :test environment, based on the groups in Gemfile.

    The fix (in my case) was to move gem 'ffaker' from the :development group to the main group, so all env's could use it. (Or, add it only to :development, :test, as appropriate)

    Why is `input` in Python 3 throwing NameError: name... is not defined

    I'd say the code you need is:

    test = input("enter the test")
    print(test)
    

    Otherwise it shouldn't run at all, due to a syntax error. The print function requires brackets in python 3. I cannot reproduce your error, though. Are you sure it's those lines causing that error?

    json.dumps vs flask.jsonify

    This is flask.jsonify()

    def jsonify(*args, **kwargs):
        if __debug__:
            _assert_have_json()
        return current_app.response_class(json.dumps(dict(*args, **kwargs),
            indent=None if request.is_xhr else 2), mimetype='application/json')
    

    The json module used is either simplejson or json in that order. current_app is a reference to the Flask() object i.e. your application. response_class() is a reference to the Response() class.

    Simple CSS: Text won't center in a button

    You can bootstrap. Now a days, almost all websites are developed using bootstrap. You can simply add bootstrap link in head of html file. Now simply add class="btn btn-primary" and your button will look like a normal button. Even you can use btn class on a tag as well, it will look like button on UI.

    Resolve Javascript Promise outside function scope

    I liked @JonJaques answer but I wanted to take it a step further.

    If you bind then and catch then the Deferred object, then it fully implements the Promise API and you can treat it as promise and await it and such.

    _x000D_
    _x000D_
    class DeferredPromise {_x000D_
      constructor() {_x000D_
        this._promise = new Promise((resolve, reject) => {_x000D_
          // assign the resolve and reject functions to `this`_x000D_
          // making them usable on the class instance_x000D_
          this.resolve = resolve;_x000D_
          this.reject = reject;_x000D_
        });_x000D_
        // bind `then` and `catch` to implement the same interface as Promise_x000D_
        this.then = this._promise.then.bind(this._promise);_x000D_
        this.catch = this._promise.catch.bind(this._promise);_x000D_
        this[Symbol.toStringTag] = 'Promise';_x000D_
      }_x000D_
    }_x000D_
    _x000D_
    const deferred = new DeferredPromise();_x000D_
    console.log('waiting 2 seconds...');_x000D_
    setTimeout(() => {_x000D_
      deferred.resolve('whoa!');_x000D_
    }, 2000);_x000D_
    _x000D_
    async function someAsyncFunction() {_x000D_
      const value = await deferred;_x000D_
      console.log(value);_x000D_
    }_x000D_
    _x000D_
    someAsyncFunction();
    _x000D_
    _x000D_
    _x000D_

    Multiprocessing: How to use Pool.map on a function defined in a class?

    I also was annoyed by restrictions on what sort of functions pool.map could accept. I wrote the following to circumvent this. It appears to work, even for recursive use of parmap.

    from multiprocessing import Process, Pipe
    from itertools import izip
    
    def spawn(f):
        def fun(pipe, x):
            pipe.send(f(x))
            pipe.close()
        return fun
    
    def parmap(f, X):
        pipe = [Pipe() for x in X]
        proc = [Process(target=spawn(f), args=(c, x)) for x, (p, c) in izip(X, pipe)]
        [p.start() for p in proc]
        [p.join() for p in proc]
        return [p.recv() for (p, c) in pipe]
    
    if __name__ == '__main__':
        print parmap(lambda x: x**x, range(1, 5))
    

    An attempt was made to access a socket in a way forbidden by its access permissions

    I had a similar issue with Docker for Windows and Hyper-V having reserved ports for its own use- in my case, it was port 3001 that couldn't be accessed.

    • The port wasn't be used by another process- running netstat -ano | findstr 3001 in an Administrator Powershell prompt showed nothing.
    • However, netsh interface ipv4 show excludedportrange protocol=tcp showed that the port was in one of the exclusion ranges.

    I was able to follow the solution described in Docker for Windows issue #3171 (Unable to bind ports: Docker-for-Windows & Hyper-V excluding but not using important port ranges):

    1. Disable Hyper-V:

      dism.exe /Online /Disable-Feature:Microsoft-Hyper-V
      
    2. After the required restarts, reserve the port you want so Hyper-V doesn't reserve it back:

      netsh int ipv4 add excludedportrange protocol=tcp startport=3001 numberofports=1
      
    3. Reenable Hyper-V:

      dism.exe /Online /Enable-Feature:Microsoft-Hyper-V /All
      

    After this, I was able to start my docker container.

    How to delete a line from a text file in C#?

    I wrote a method to delete lines from files.

    This program uses using System.IO.

    See my code:

    void File_DeleteLine(int Line, string Path)
    {
        StringBuilder sb = new StringBuilder();
        using (StreamReader sr = new StreamReader(Path))
        {
            int Countup = 0;
            while (!sr.EndOfStream)
            {
                Countup++;
                if (Countup != Line)
                {
                    using (StringWriter sw = new StringWriter(sb))
                    {
                        sw.WriteLine(sr.ReadLine());
                    }
                }
                else
                {
                    sr.ReadLine();
                }
            }
        }
        using (StreamWriter sw = new StreamWriter(Path))
        {
            sw.Write(sb.ToString());
        }
    }
    

    What is the Python equivalent of static variables inside a function?

    Using an attribute of a function as static variable has some potential drawbacks:

    • Every time you want to access the variable, you have to write out the full name of the function.
    • Outside code can access the variable easily and mess with the value.

    Idiomatic python for the second issue would probably be naming the variable with a leading underscore to signal that it is not meant to be accessed, while keeping it accessible after the fact.

    An alternative would be a pattern using lexical closures, which are supported with the nonlocal keyword in python 3.

    def make_counter():
        i = 0
        def counter():
            nonlocal i
            i = i + 1
            return i
        return counter
    counter = make_counter()
    

    Sadly I know no way to encapsulate this solution into a decorator.

    How to use Sublime over SSH

    I am on MacOS, and the most convenient way for me is to using CyberDuck, which is free (also available for Windows). You can connect to your remote SSH file system and edit your file using your local editor. What CyberDuck does is download the file to a temporary place on your local OS and open it with your editor. Once you save the file, CyberDuck automatically upload it to your remote system. It seems transparent as if you are editing your remote file using your local editor. The developers of Cyberduck also make MountainDuck for mounting remote files systems.

    bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

    In version 2.1.5

    changeDate has been renamed to change.dp so changedate was not working for me

    $("#datetimepicker").datetimepicker().on('change.dp', function (e) {
                FillDate(new Date());
        });
    

    also needed to change css class from datepicker to datepicker-input

    <div id='datetimepicker' class='datepicker-input input-group controls'>
       <input id='txtStartDate' class='form-control' placeholder='Select datepicker' data-rule-required='true' data-format='MM-DD-YYYY' type='text' />
       <span class='input-group-addon'>
           <span class='icon-calendar' data-time-icon='icon-time' data-date-icon='icon-calendar'></span>
       </span>
    </div>
    

    Date formate also works in capitals like this data-format='MM-DD-YYYY'

    it might be helpful for someone it gave me really hard time :)

    How to select records from last 24 hours using SQL?

    SELECT * 
    FROM tableName 
    WHERE datecolumn >= dateadd(hour,-24,getdate())
    

    How to check if input is numeric in C++

    Why not just using scanf("%i") and check its return?

    How to install a .ipa file into my iPhone?

    You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

    Testing if a site is vulnerable to Sql Injection

    The easiest way to protect yourself is to use stored procedures instead of inline SQL statements.

    Then use "least privilege" permissions and only allow access to stored procedures and not directly to tables.

    How to develop or migrate apps for iPhone 5 screen resolution?

    Point worth notice - in new Xcode you have to add this image file [email protected] to assets

    Checkboxes in web pages – how to make them bigger?

    Pure modern 2020 CSS only decision, without blurry scaling or non-handy transforming. And with tick! =)

    Works nice in Firefox and Chromium-based browsers.

    So, you can rule your checkboxes purely ADAPTIVE, just by setting parent block's font-height and it will grow with text!

    _x000D_
    _x000D_
    input[type='checkbox'] {_x000D_
      -moz-appearance: none;_x000D_
      -webkit-appearance: none;_x000D_
      appearance: none;_x000D_
      vertical-align: middle;_x000D_
      outline: none;_x000D_
      font-size: inherit;_x000D_
      cursor: pointer;_x000D_
      width: 1.0em;_x000D_
      height: 1.0em;_x000D_
      background: white;_x000D_
      border-radius: 0.25em;_x000D_
      border: 0.125em solid #555;_x000D_
      position: relative;_x000D_
    }_x000D_
    _x000D_
    input[type='checkbox']:checked {_x000D_
      background: #adf;_x000D_
    }_x000D_
    _x000D_
    input[type='checkbox']:checked:after {_x000D_
      content: "?";_x000D_
      position: absolute;_x000D_
      font-size: 90%;_x000D_
      left: 0.0625em;_x000D_
      top: -0.25em;_x000D_
    }
    _x000D_
    <label for="check1"><input type="checkbox" id="check1" checked="checked" /> checkbox one</label>_x000D_
    <label for="check2"><input type="checkbox" id="check2" /> another checkbox</label>
    _x000D_
    _x000D_
    _x000D_

    How do I access previous promise results in a .then() chain?

    When using bluebird, you can use .bind method to share variables in promise chain:

    somethingAsync().bind({})
    .spread(function (aValue, bValue) {
        this.aValue = aValue;
        this.bValue = bValue;
        return somethingElseAsync(aValue, bValue);
    })
    .then(function (cValue) {
        return this.aValue + this.bValue + cValue;
    });
    

    please check this link for further information:

    http://bluebirdjs.com/docs/api/promise.bind.html

    Best way to check for IE less than 9 in JavaScript without library

    Using conditional comments, you can create a script block that will only get executed in IE less than 9.

    <!--[if lt IE 9 ]>
    <script>
    var is_ie_lt9 = true;
    </script>
    <![endif]--> 
    

    Of course, you could precede this block with a universal block that declares var is_ie_lt9=false, which this would override for IE less than 9. (In that case, you'd want to remove the var declaration, as it would be repetitive).

    EDIT: Here's a version that doesn't rely on in-line script blocks (can be run from an external file), but doesn't use user agent sniffing:

    Via @cowboy:

    with(document.createElement("b")){id=4;while(innerHTML="<!--[if gt IE "+ ++id+"]>1<![endif]-->",innerHTML>0);var ie=id>5?+id:0}
    

    Android: how to draw a border to a LinearLayout

    Extend LinearLayout/RelativeLayout and use it straight on the XML

    package com.pkg_name ;
    ...imports...
    public class LinearLayoutOutlined extends LinearLayout {
        Paint paint;    
    
        public LinearLayoutOutlined(Context context) {
            super(context);
            // TODO Auto-generated constructor stub
            setWillNotDraw(false) ;
            paint = new Paint();
        }
        public LinearLayoutOutlined(Context context, AttributeSet attrs) {
            super(context, attrs);
            // TODO Auto-generated constructor stub
            setWillNotDraw(false) ;
            paint = new Paint();
        }
        @Override
        protected void onDraw(Canvas canvas) {
            /*
            Paint fillPaint = paint;
            fillPaint.setARGB(255, 0, 255, 0);
            fillPaint.setStyle(Paint.Style.FILL);
            canvas.drawPaint(fillPaint) ;
            */
    
            Paint strokePaint = paint;
            strokePaint.setARGB(255, 255, 0, 0);
            strokePaint.setStyle(Paint.Style.STROKE);
            strokePaint.setStrokeWidth(2);  
            Rect r = canvas.getClipBounds() ;
            Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
            canvas.drawRect(outline, strokePaint) ;
        }
    
    }
    

    <?xml version="1.0" encoding="utf-8"?>
    
    <com.pkg_name.LinearLayoutOutlined
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:orientation="vertical"
        android:layout_width=...
        android:layout_height=...
       >
       ... your widgets here ...
    
    </com.pkg_name.LinearLayoutOutlined>
    

    Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

    The answer is not efficiency. Non-reentrant mutexes lead to better code.

    Example: A::foo() acquires the lock. It then calls B::bar(). This worked fine when you wrote it. But sometime later someone changes B::bar() to call A::baz(), which also acquires the lock.

    Well, if you don't have recursive mutexes, this deadlocks. If you do have them, it runs, but it may break. A::foo() may have left the object in an inconsistent state before calling bar(), on the assumption that baz() couldn't get run because it also acquires the mutex. But it probably shouldn't run! The person who wrote A::foo() assumed that nobody could call A::baz() at the same time - that's the entire reason that both of those methods acquired the lock.

    The right mental model for using mutexes: The mutex protects an invariant. When the mutex is held, the invariant may change, but before releasing the mutex, the invariant is re-established. Reentrant locks are dangerous because the second time you acquire the lock you can't be sure the invariant is true any more.

    If you are happy with reentrant locks, it is only because you have not had to debug a problem like this before. Java has non-reentrant locks these days in java.util.concurrent.locks, by the way.

    Is it possible to set a timeout for an SQL query on Microsoft SQL server?

    As far as I know, apart from setting the command or connection timeouts in the client, there is no way to change timeouts on a query by query basis in the server.

    You can indeed change the default 600 seconds using sp_configure, but these are server scoped.

    Query for array elements inside JSON type

    Create a table with column as type json

    CREATE TABLE friends ( id serial primary key, data jsonb);
    

    Now let's insert json data

    INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
    INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');
    

    Now let's make some queries to fetch data

    select data->'name' from friends;
    select data->'name' as name, data->'work' as work from friends;
    

    You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])

        name    |            work            
    ------------+----------------------------
     "Arya"     | ["Improvements", "Office"]
     "Tim Cook" | ["Cook", "ceo", "Play"]
    (2 rows)
    

    Now to retrieve only the values just use ->>

    select data->>'name' as name, data->'work'->>0 as work from friends;
    select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';
    

    JavaScript: client-side vs. server-side validation

    JavaScript can be modified at runtime.

    I suggest a pattern of creating a validation structure on the server, and sharing this with the client.

    You'll need separate validation logic on both ends, ex:

    "required" attributes on inputs client-side

    field.length > 0 server-side.

    But using the same validation specification will eliminate some redundancy (and mistakes) of mirroring validation on both ends.

    Search for a particular string in Oracle clob column

    You can use the way like @Florin Ghita has suggested. But remember dbms_lob.substr has a limit of 4000 characters in the function For example :

    dbms_lob.substr(clob_value_column,4000,1)
    

    Otherwise you will find ORA-22835 (buffer too small)

    You can also use the other sql way :

    SELECT * FROM   your_table WHERE  clob_value_column LIKE '%your string%';
    

    Note : There are performance problems associated with both the above ways like causing Full Table Scans, so please consider about Oracle Text Indexes as well:

    https://docs.oracle.com/en/database/oracle/oracle-database/12.2/ccapp/indexing-with-oracle-text.html

    DateTime fields from SQL Server display incorrectly in Excel

    This is a very old post, but I recently encountered the problem and for me the following solved the issue by formatting the SQL as follows,

    SELECT CONVERT (varchar, getdate(), 120) AS Date

    If you copy the result from SQL Server and paste in Excel then Excel holds the proper formatting.

    How to add an action to a UIAlertView button using Swift iOS

    The Swifty way is to use the new UIAlertController and closures:

        // Create the alert controller
        let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
    
        // Create the actions
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
            UIAlertAction in
            NSLog("OK Pressed")
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
            UIAlertAction in
            NSLog("Cancel Pressed")
        }
    
        // Add the actions
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
    
        // Present the controller
        self.presentViewController(alertController, animated: true, completion: nil)
    

    Swift 3:

        // Create the alert controller
        let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
    
        // Create the actions
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
            UIAlertAction in
            NSLog("OK Pressed")
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
            UIAlertAction in
            NSLog("Cancel Pressed")
        }
    
        // Add the actions
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
    
        // Present the controller
        self.present(alertController, animated: true, completion: nil)
    

    Join between tables in two different databases?

    SELECT <...> 
    FROM A.tableA JOIN B.tableB 
    

    Cannot install NodeJs: /usr/bin/env: node: No such file or directory

    If you already have nodejs installed (check with which nodejs) and don't want to install another package, you can, as root:

    update-alternatives --install /usr/bin/node node /usr/bin/nodejs 99
    

    How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

    The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:.

    You can convert between the two like this:

    NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
    NSDictionary *dict = [[mutable copy] autorelease]; 
    

    Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):

    BOOL success = [dict writeToFile:@"/file/path" atomically:YES];
    

    To read a dictionary from a file, there's a corresponding method:

    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];
    

    If you want to read the file as an NSMutableDictionary, simply use:

    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];
    

    Get a JSON object from a HTTP response

    For the sake of a complete solution to this problem (yes, I know that this post died long ago...) :

    If you want a JSONObject, then first get a String from the result:

    String jsonString = EntityUtils.toString(response.getEntity());
    

    Then you can get your JSONObject:

    JSONObject jsonObject = new JSONObject(jsonString);
    

    Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

    I just felt like I'll add my $0.2 to those 2 good answers. I had a case when I had to move the last column all the way to the top in a 3-column situation.

    [A][B][C]

    to

    [C]

    [A]

    [B]

    Boostrap's class .col-xx-push-Xdoes nothing else but pushes a column to the right with left: XX%; so all you have to do to push a column right is to add the number of pseudo columns going left.

    In this case:

    • two columns (col-md-5 and col-md-3) are going left, each with the value of the one that is going right;

    • one(col-md-4) is going right by the sum of the first two going left (5+3=8);


    <div class="row">
        <div class="col-md-4 col-md-push-8 ">
            C
        </div>
        <div class="col-md-5 col-md-pull-4">
            A
        </div>
        <div class="col-md-3 col-md-pull-4">
            B
        </div>
    </div>
    

    enter image description here

    How to set the LDFLAGS in CMakeLists.txt?

    It depends a bit on what you want:

    A) If you want to specify which libraries to link to, you can use find_library to find libs and then use link_directories and target_link_libraries to.

    Of course, it is often worth the effort to write a good find_package script, which nicely adds "imported" libraries with add_library( YourLib IMPORTED ) with correct locations, and platform/build specific pre- and suffixes. You can then simply refer to 'YourLib' and use target_link_libraries.

    B) If you wish to specify particular linker-flags, e.g. '-mthreads' or '-Wl,--export-all-symbols' with MinGW-GCC, you can use CMAKE_EXE_LINKER_FLAGS. There are also two similar but undocumented flags for modules, shared or static libraries:

    CMAKE_MODULE_LINKER_FLAGS
    CMAKE_SHARED_LINKER_FLAGS
    CMAKE_STATIC_LINKER_FLAGS
    

    java.lang.ClassCastException

    ClassA a = <something>;
    ClassB b = (ClassB) a;
    

    The 2nd line will fail if ClassA is not a subclass of ClassB, and will throw a ClassCastException.

    Pass a string parameter in an onclick function

    You can use this code in your button onclick method:

    <button class="btn btn-danger" onclick="cancelEmployee(\''+cancelButtonID+'\')" > Cancel </button>
    

    How to expand a list to function arguments in Python

    It exists, but it's hard to search for. I think most people call it the "splat" operator.

    It's in the documentation as "Unpacking argument lists".

    You'd use it like this: foo(*values). There's also one for dictionaries:

    d = {'a': 1, 'b': 2}
    def foo(a, b):
        pass
    foo(**d)
    

    Get DataKey values in GridView RowCommand

    you can just do this:

    string id = GridName.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
    

    How to fix "The ConnectionString property has not been initialized"

    I stumbled in the same problem while working on a web api Asp Net Core project. I followed the suggestion to change the reference in my code to:

    ConfigurationManager.ConnectionStrings["NameOfTheConnectionString"].ConnectionString
    

    but adding the reference to System.Configuration.dll caused the error "Reference not valid or not supported".

    Configuration manager error

    To fix the problem I had to download the package System.Configuration.ConfigurationManager using NuGet (Tools -> Nuget Package-> Manage Nuget packages for the solution)

    if var == False

    Use not

    var = False
    if not var:
        print 'learnt stuff'
    

    Getting the first index of an object

    I had the same problem yesterday. I solved it like this:

    var obj = {
            foo:{},
            bar:{},
            baz:{}
        },
       first = null,
       key = null;
    for (var key in obj) {
        first = obj[key];
        if(typeof(first) !== 'function') {
            break;
        }
    }
    // first is the first enumerated property, and key it's corresponding key.
    

    Not the most elegant solution, and I am pretty sure that it may yield different results in different browsers (i.e. the specs says that enumeration is not required to enumerate the properties in the same order as they were defined). However, I only had a single property in my object so that was a non-issue. I just needed the first key.

    How can I add new item to the String array?

    String a []=new String[1];
    
      a[0].add("kk" );
      a[1].add("pp");
    

    Try this one...