Programs & Examples On #Tagfile

A "tagfile" is a JSP/Facelets specific term for a reuseable JSP/Facelets code fragment which is registered as a custom tag and is thus accessible under a custom namespace, such as ``.

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

According to: Java Revisited

  1. Resources included by include directive are loaded during jsp translation time, while resources included by include action are loaded during request time.

  2. Any change on included resources will not be visible in case of include directive until jsp file compiles again. While in case of include action, any change in included resource will be visible in the next request.

  3. Include directive is static import, while include action is dynamic import.

  4. Include directive uses file attribute to specify resources to be included while include action uses page attribute for the same purpose.

How can I convert a cv::Mat to a gray scale in OpenCv?

Using the C++ API, the function name has slightly changed and it writes now:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);

The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.

OpenCV 3

Starting with OpenCV 3.0, there is yet another convention. Conversion codes are embedded in the namespace cv:: and are prefixed with COLOR. So, the example becomes then:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);

As far as I have seen, the included file path hasn't changed (this is not a typo).

How to get all checked checkboxes

In IE9+, Chrome or Firefox you can do:

var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');

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

The cleanest and simplest solution is to use your own listener interface so that when the user clicks on the ok button your listener is called with the return value. This method does nothing fancy or complicated and respects android principles.

Define your listener interface as follows:

public interface EditListener
/* Used to get an integer return value from a dialog
 * 
 */
{
 void returnValue(int value); 
}

For my application I created an EditValue class which uses AlertDialog and which I call whenever I want to edit an integer value. Note how the EditListener interface is passed as an argument to this code. When the user clicks on the OK button the value will be returned to your calling code via the EditListener method:

public final class EditValue
/* Used to edit a value using an alert dialog
 * The edited value is returned via the returnValue method of the supplied EditListener             interface
 * Could be modified with different constructors to edit double/float etc
 */
{
 public EditValue(final Activity parent, int value, String title, String message,
                  final EditListener editListener)
 {AlertDialog.Builder alert= new AlertDialog.Builder(parent);
  if(title==null) title= message;
  else if(message==null) message= title;
  if(title!=null) alert.setTitle(title);
  if(message!=null) alert.setMessage(message);

  // Set an EditText view to get user input 
  final EditText input = new EditText(parent);
  input.setText(String.valueOf(value));
  input.setInputType(InputType.TYPE_CLASS_NUMBER);
  alert.setView(input);

  alert.setPositiveButton("OK",new DialogInterface.OnClickListener()
  {public void onClick(DialogInterface dialog, int which)
   {try
    {int newValue= Integer.valueOf(input.getText().toString());
     editListener.returnValue(newValue);
     dialog.dismiss();
    }catch(NumberFormatException err) { }
   }
  });

  alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
  {public void onClick(DialogInterface dialog, int which)
   {dialog.dismiss();
    }
  });

  alert.show();
 }
}

Finally when you use EditValue you need to declare your EditListener and you can now access the return value and do what you want to do:

 new EditValue(main,AnchorManager.anchorageLimit,
               main.res.getString(R.string.config_anchorage_limit),null,
               new EditListener()
 {public void returnValue(int value) {AnchorManager.anchorageLimit= value;}
  }
 );

How do I set the default value for an optional argument in Javascript?

You can also do this with ArgueJS:

function (){
  arguments = __({nodebox: undefined, str: [String: "hai"]})

  // and now on, you can access your arguments by
  //   arguments.nodebox and arguments.str
}

How to remove old Docker containers

https://github.com/HardySimpson/docker-cleanup

Docker cleanup

A tiny all-in-one shell, which removes:

  • Containers that not running more than one day ago
  • Images that don't belong to any remaining container

Intend to run as a crontab job

Feature

  • It will remove all <none>:<none> images
  • If the image has multiple repo:tag references to it, it will remove all repo:tag except with running a container. Actually it is a nature of "docker rmi".
  • Many error message will be show on screen, and you can decide to 2>/dev/null or not
  • Learn something from docker-gc, and fix its problem (it can not remove image that has mutliple repo:tag)

How to change the Spyder editor background to dark?

If you are using MacBook Pro (OS X) follow the following steps:

python > Preference > Syntax coloring

enter image description here

enter image description here

catch specific HTTP error in python

Python 3

from urllib.error import HTTPError

Python 2

from urllib2 import HTTPError

Just catch HTTPError, handle it, and if it's not Error 404, simply use raise to re-raise the exception.

See the Python tutorial.

e.g. complete example for Pyhton 2

import urllib2
from urllib2 import HTTPError
try:
   urllib2.urlopen("some url")
except HTTPError as err:
   if err.code == 404:
       <whatever>
   else:
       raise

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

If youre running wamp update

define("DB_HOST", "localhost");

To your machines ip address (mine is 192.168.0.25);

define("DB_HOST", "192.168.0.25");

You can find it on window by typing ipconfig in your console or ifconfig on mac/linux

Contain form within a bootstrap popover?

A complete solution for anyone that might need it, I've used this with good results so far

JS:

$(".btn-popover-container").each(function() {
    var btn = $(this).children(".popover-btn");
    var titleContainer = $(this).children(".btn-popover-title");
    var contentContainer = $(this).children(".btn-popover-content");

    var title = $(titleContainer).html();
    var content = $(contentContainer).html();

    $(btn).popover({
        html: true,
        title: title,
        content: content,
        placement: 'right'
    });
});

HTML:

<div class="btn-popover-container">
    <button type="button" class="btn btn-link popover-btn">Button Name</button>
    <div class="btn-popover-title">
        Popover Title
    </div>
    <div class="btn-popover-content">
        <form>
          Or Other content..
        </form>
    </div>
</div>

CSS:

.btn-popover-container {
    display: inline-block;
}


.btn-popover-container .btn-popover-title, .btn-popover-container .btn-popover-content {
    display: none;
}

Extract directory path and filename

bash:

fspec="/exp/home1/abc.txt"
fname="${fspec##*/}"

Using Lato fonts in my css (@font-face)

Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).

(I don't see anything obviously wrong with the code you have posted above)

Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?

How to load my app from Eclipse to my Android phone instead of AVD

Some people may have the issue where your phone might not immediately get recognized by the computer as an emulator, especially if you're given the option to choose why your phone is connected to the computer on your phone. These options are:

  • charge only
  • Media device (MTP)
  • Camera file transfer (PTP)
  • Share mobile network
  • Install driver

Of these options, choose MTP and follow the instructions found in the quotes of other answers.

  • Hope this helps!

goto run menu -> run configuration. right click on android application on the right side and click new. fill the corresponding details like project name under the android tab. then under the target tab. select 'launch on all compatible devices and then select active devices from the drop down list'. save the configuration and run it by either clicking run on the 'run' button on the bottom right side of the window or close the window and run again

Why does javascript replace only first instance when using replace?

Unlike the C#/.NET class library (and most other sensible languages), when you pass a String in as the string-to-match argument to the string.replace method, it doesn't do a string replace. It converts the string to a RegExp and does a regex substitution. As Gumbo explains, a regex substitution requires the g?lobal flag, which is not on by default, to replace all matches in one go.

If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:

var id= 'c_'+date.split('/').join('');

Convert A String (like testing123) To Binary In Java

The usual way is to use String#getBytes() to get the underlying bytes and then present those bytes in some other form (hex, binary whatever).

Note that getBytes() uses the default charset, so if you want the string converted to some specific character encoding, you should use getBytes(String encoding) instead, but many times (esp when dealing with ASCII) getBytes() is enough (and has the advantage of not throwing a checked exception).

For specific conversion to binary, here is an example:

  String s = "foo";
  byte[] bytes = s.getBytes();
  StringBuilder binary = new StringBuilder();
  for (byte b : bytes)
  {
     int val = b;
     for (int i = 0; i < 8; i++)
     {
        binary.append((val & 128) == 0 ? 0 : 1);
        val <<= 1;
     }
     binary.append(' ');
  }
  System.out.println("'" + s + "' to binary: " + binary);

Running this example will yield:

'foo' to binary: 01100110 01101111 01101111 

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

The select statement in the cost part of your select is returning more than one value. You need to add more where clauses, or use an aggregation.

PHP Fatal error: Call to undefined function mssql_connect()

I have just tried to install that extension on my dev server.

First, make sure that the extension is correctly enabled. Your phpinfo() output doesn't seem complete.

If it is indeed installed properly, your phpinfo() should have a section that looks like this: enter image description here

If you do not get that section in your phpinfo(). Make sure that you are using the right version. There are both non-thread-safe and thread-safe versions of the extension.

Finally, check your extension_dir setting. By default it's this: extension_dir = "ext", for most of the time it works fine, but if it doesn't try: extension_dir = "C:\PHP\ext".

===========================================================================

EDIT given new info:

You are using the wrong function. mssql_connect() is part of the Mssql extension. You are using microsoft's extension, so use sqlsrv_connect(), for the API for the microsoft driver, look at SQLSRV_Help.chm which should be extracted to your ext directory when you extracted the extension.

How to consume a webApi from asp.net Web API to store result in database?

public class EmployeeApiController : ApiController
{
    private readonly IEmployee _employeeRepositary;

    public EmployeeApiController()
    {
        _employeeRepositary = new EmployeeRepositary();
    }

    public async Task<HttpResponseMessage> Create(EmployeeModel Employee)
    {
        var returnStatus = await _employeeRepositary.Create(Employee);
        return Request.CreateResponse(HttpStatusCode.OK, returnStatus);
    }
} 

Persistance

public async Task<ResponseStatusViewModel> Create(EmployeeModel Employee)
{    
    var responseStatusViewModel = new ResponseStatusViewModel();
    var connection = new SqlConnection(EmployeeConfig.EmployeeConnectionString);
                var command = new SqlCommand("usp_CreateEmployee", connection);
                command.CommandType = CommandType.StoredProcedure;
                var pEmployeeName = new SqlParameter("@EmployeeName", SqlDbType.VarChar, 50);
                pEmployeeName.Value = Employee.EmployeeName;
                command.Parameters.Add(pEmployeeName);


                try
                {
                    await connection.OpenAsync();
                    await command.ExecuteNonQueryAsync();

                    command.Dispose();
                    connection.Dispose();

                }
                catch (Exception ex)
                {

                    throw ex;
                }
                return responseStatusViewModel;
            }

Repository

Task<ResponseStatusViewModel> Create(EmployeeModel Employee);

public class EmployeeConfig
{
    public static string EmployeeConnectionString;
    private const string EmployeeConnectionStringKey = "EmployeeConnectionString";
    public static void InitializeConfig()
    {
        EmployeeConnectionString = GetConnectionStringValue(EmployeeConnectionStringKey);
    }

    private static string GetConnectionStringValue(string connectionStringName)
    {
        return Convert.ToString(ConfigurationManager.ConnectionStrings[connectionStringName]);
    }
}

How do I fetch only one branch of a remote Git repository?

git version: 2.74

This is how I do it:

git remote add [REMOTE-NAME] [REMOTE-URL]
git fetch [REMOTE-NAME] -- [BRANCH]

Bootstrap how to get text to vertical align in a div container

h2.text-left{
  position:relative;
  top:50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
}

Explanation:

The top:50% style essentially pushes the header element down 50% from the top of the parent element. The translateY stylings also act in a similar manner by moving then element down 50% from the top.

Please note that this works well for headers with 1 (maybe 2) lines of text as this simply moves the top of the header element down 50% and then the rest of the content fills in below that, which means that with multiple lines of text it would appear to be slightly below vertically aligned.

A possible fix for multiple lines would be to use a percentage slightly less than 50%.

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

As far as I am aware, the MSVCRxxx.dlls are in %SystemRoot%\System32 (usually C:\Windows\System32).

The xxx refers to the version of the MS Visual C Runtime (hence MSVCR...)

However, the complication seems to be that the xxx version is not the same as the two digits of the year "version".

For example, Visual C Runtime 2013 yields MSVCR120.dll and "...Runtime 2012" yields MSVCR110.dll. And then Microsoft packages these as vcredist_x86.exe or vcredist_x64.exe, seemingly irrespective of the xxx version or the Visual Studio version number (2012, 2013 etc) - confused? You have every right to be!

So, firstly, you need to determine whether you need 32 bit, 64 bit or even both (some PHP distributions apparently do need both), then download the relevant vcredist... for the bits AND for the Visual Studio version. As far as I can tell, the only way to tell which vcredist... you have is to start to install it. Recent versions give an intro screen that quotes the Visual Studio version and the xxx version. I have renamed by vcredists to something like vcredist_x64_2012_V11.exe.

[EDIT] Forgot to add earlier that if you are simply looking to "install" the missing DLL (as opposed to resolve some bigger set of issues), then you probably won't do any harm by simply installing the relevant vcredist for your architecture (32 bit, 64 bit) and "missing" version.

Adding +1 to a variable inside a function

points is not within the function's scope. You can grab a reference to the variable by using nonlocal:

points = 0
def test():
    nonlocal points
    points += 1

If points inside test() should refer to the outermost (module) scope, use global:

points = 0
def test():
    global points
    points += 1

In Python, what is the difference between ".append()" and "+= []"?

The rebinding behaviour mentioned in other answers does matter in certain circumstances:

>>> a = ([],[])
>>> a[0].append(1)
>>> a
([1], [])
>>> a[1] += [1]
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

That's because augmented assignment always rebinds, even if the object was mutated in-place. The rebinding here happens to be a[1] = *mutated list*, which doesn't work for tuples.

Want to download a Git repository, what do I need (windows machine)?

To change working directory in GitMSYS's Git Bash you can just use cd

cd /path/do/directory

Note that:

  • Directory separators use the forward-slash (/) instead of backslash.
  • Drives are specified with a lower case letter and no colon, e.g. "C:\stuff" should be represented with "/c/stuff".
  • Spaces can be escaped with a backslash (\)
  • Command line completion is your friend. Press TAB at anytime to expand stuff, including Git options, branches, tags, and directories.

Also, you can right click in Windows Explorer on a directory and "Git Bash here".

hibernate could not get next sequence value

For anyone using FluentNHibernate (my version is 2.1.2), it's just as repetitive but this works:

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("users");
        Id(x => x.Id).Column("id").GeneratedBy.SequenceIdentity("users_id_seq");

bash echo number of lines of file given in a bash variable without the file name

An Example Using Your Own Data

You can avoid having your filename embedded in the NUMOFLINES variable by using redirection from JAVA_TAGS_FILE, rather than passing the filename as an argument to wc. For example:

NUMOFLINES=$(wc -l < "$JAVA_TAGS_FILE")

Explanation: Use Pipes or Redirection to Avoid Filenames in Output

The wc utility will not print the name of the file in its output if input is taken from a pipe or redirection operator. Consider these various examples:

# wc shows filename when the file is an argument
$ wc -l /etc/passwd
41 /etc/passwd

# filename is ignored when piped in on standard input
$ cat /etc/passwd | wc -l
41

# unusual redirection, but wc still ignores the filename
$ < /etc/passwd wc -l
41

# typical redirection, taking standard input from a file
$ wc -l < /etc/passwd
41

As you can see, the only time wc will print the filename is when its passed as an argument, rather than as data on standard input. In some cases, you may want the filename to be printed, so it's useful to understand when it will be displayed.

How can I set the background color of <option> in a <select> element?

I assume you mean the <select> input element?

Support for that is pretty new, but FF 3.6, Chrome and IE 8 render this all right:

_x000D_
_x000D_
<select name="select">
  <option value="1" style="background-color: blue">Test</option>
  <option value="2" style="background-color: green">Test</option>
</select>
_x000D_
_x000D_
_x000D_

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

Get a list of all the files in a directory (recursive)

This code works for me:

import groovy.io.FileType

def list = []

def dir = new File("path_to_parent_dir")
dir.eachFileRecurse (FileType.FILES) { file ->
  list << file
}

Afterwards the list variable contains all files (java.io.File) of the given directory and its subdirectories:

list.each {
  println it.path
}

How to get form values in Symfony2 controller

In Symfony forms, there are two different types of transformers and three different types of underlying data: enter image description here In any form, the three different types of data are:

  • Model data

    This is the data in the format used in your application (e.g. an Issue object). If you call Form::getData() or Form::setData(), you're dealing with the "model" data.

  • Norm Data

    This is a normalized version of your data and is commonly the same as your "model" data (though not in our example). It's not commonly used directly.

  • View Data

    This is the format that's used to fill in the form fields themselves. It's also the format in which the user will submit the data. When you call Form::submit($data), the $data is in the "view" data format.

The two different types of transformers help convert to and from each of these types of data:

  • Model transformers:

    transform(): "model data" => "norm data"
    reverseTransform(): "norm data" => "model data"

  • View transformers:

    transform(): "norm data" => "view data"
    reverseTransform(): "view data" => "norm data"

Which transformer you need depends on your situation.

To use the view transformer, call addViewTransformer().


If you want to get all form data:

$form->getData();

If you are after a specific form field (for example first_name):

$form->get('first_name')->getData();

Wait till a Function with animations is finished until running another Function

Along with Yoshi's answer, I have found another very simple (callback type) solution for animations.

jQuery has an exposed variable (that for some reason isn't listed anywhere in the jQuery docs) called $.timers, which holds the array of animations currently taking place.

function animationsTest (callback) {
    // Test if ANY/ALL page animations are currently active

    var testAnimationInterval = setInterval(function () {
        if (! $.timers.length) { // any page animations finished
            clearInterval(testAnimationInterval);
            callback();
        }
    }, 25);
};

Basic useage:

functionOne(); // one with animations

animationsTest(functionTwo);

Hope this helps some people out!

Shell script to copy files from one location to another location and rename add the current date to every file

cp --archive home/webapps/project1/folder1/{aaa,bbb,ccc,ddd}.csv home/webapps/project1/folder2
rename 's/\.csv$/'$(date +%m%d%Y).csv'/' home/webapps/project1/folder2/{aaa,bbb,ccc,ddd}.csv

Explanation:

  • --archive ensures that the files are copied with the same ownership and permissions.
  • foo{bar,baz} is expanded into foobar foobaz.
  • rename is a commonly available program to do exactly this kind of substitution.

PS: don't use ls for this.

How do I perform a GROUP BY on an aliased column in MS-SQL Server?

You pass the expression you want to group by rather than the alias

SELECT       LastName + ', ' + FirstName AS 'FullName'
FROM         customers
GROUP BY      LastName + ', ' + FirstName

How can I solve Exception in thread "main" java.lang.NullPointerException error

This is the problem

double a[] = null;

Since a is null, NullPointerException will arise every time you use it until you initialize it. So this:

a[i] = var;

will fail.

A possible solution would be initialize it when declaring it:

double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7

IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.

java.lang.NullPointerException

This exception means there's a variable with null value being used. How to solve? Just make sure the variable is not null before being used.

at twoten.TwoTenB.(TwoTenB.java:29)

This line has two parts:

  • First, shows the class and method where the error was thrown. In this case, it was at <init> method in class TwoTenB declared in package twoten. When you encounter an error message with SomeClassName.<init>, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
  • Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file TwoTenB.java, line number 29. This seems to be a[i] = var;.

From this line, other lines will be similar to tell you where the error arose. So when reading this:

at javapractice.JavaPractice.main(JavaPractice.java:32)

It means that you were trying to instantiate a TwoTenB object reference inside the main method of your class JavaPractice declared in javapractice package.

How to remove leading zeros using C#

Regex rx = new Regex(@"^0+(\d+)$");
rx.Replace("0001234", @"$1"); // => "1234"
rx.Replace("0001234000", @"$1"); // => "1234000"
rx.Replace("000", @"$1"); // => "0" (TrimStart will convert this to "")

// usage
var outString = rx.Replace(inputString, @"$1");

How to link an image and target a new window

If you use script to navigate to the page, use the open method with the target _blank to open a new window / tab:

<img src="..." alt="..." onclick="window.open('anotherpage.html', '_blank');" />

However, if you want search engines to find the page, you should just wrap the image in a regular link instead.

How to use the onClick event for Hyperlink using C# code?

The onclick attribute on your anchor tag is going to call a client-side function. (This is what you would use if you wanted to call a javascript function when the link is clicked.)

What you want is a server-side control, like the LinkButton:

<asp:LinkButton ID="lnkTutorial" runat="server" Text="Tutorial" OnClick="displayTutorial_Click"/>

This has an OnClick attribute that will call the method in your code behind.

Looking further into your code, it looks like you're just trying to open a different tutorial based on access level of the user. You don't need an event handler for this at all. A far better approach would be to just set the end point of your LinkButton control in the code behind.

protected void Page_Load(object sender, EventArgs e)
{
    userinfo = (UserInfo)Session["UserInfo"];

    if (userinfo.user == "Admin")
    {
        lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
    }
    else
    {
        lnkTutorial.PostBackUrl = "help/UserTutorial.html";
    }
}

Really, it would be best to check that you actually have a user first.

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["UserInfo"] != null && ((UserInfo)Session["UserInfo"]).user == "Admin")
    {
        lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
    }
    else
    {
        lnkTutorial.PostBackUrl = "help/UserTutorial.html";
    }
}

What does += mean in Python?

a += b is essentially the same as a = a + b, except that:

  • + always returns a newly allocated object, but += should (but doesn't have to) modify the object in-place if it's mutable (e.g. list or dict, but int and str are immutable).

  • In a = a + b, a is evaluated twice.

  • Python: Simple Statements

    • A simple statement is comprised within a single logical line.

If this is the first time you encounter the += operator, you may wonder why it matters that it may modify the object in-place instead of building a new one. Here is an example:

# two variables referring to the same list
>>> list1 = []
>>> list2 = list1

# += modifies the object pointed to by list1 and list2
>>> list1 += [0]
>>> list1, list2
([0], [0])

# + creates a new, independent object
>>> list1 = []
>>> list2 = list1
>>> list1 = list1 + [0]
>>> list1, list2
([0], [])

How to uninstall an older PHP version from centOS7

Subscribing to the IUS Community Project Repository

cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh

Run the script:

sudo bash setup-ius.sh

Upgrading mod_php with Apache

This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.

Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.

sudo yum remove php-cli mod_php php-common

Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.

sudo yum install mod_php70u php70u-cli php70u-mysqlnd

Finally, restart Apache to load the new version of mod_php:

sudo apachectl restart

You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:

systemctl status httpd

How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

In addition to @chanafdo answer, you can use route name

when working with laravel blade

<a href="{{route('login')}}">login here</a> with parameter in route name

when go to url like URI: profile/{id} <a href="{{route('profile', ['id' => 1])}}">login here</a>

without blade

<a href="<?php echo route('login')?>">login here</a>

with parameter in route name

when go to url like URI: profile/{id} <a href="<?php echo route('profile', ['id' => 1])?>">login here</a>

As of laravel 5.2 you can use @php @endphp to create as <?php ?> in laravel blade. Using blade your personal opinion but I suggest to use it. Learn it. It has many wonderful features as template inheritance, Components & Slots,subviews etc...

How can I change column types in Spark SQL's DataFrame?

To convert the year from string to int, you can add the following option to the csv reader: "inferSchema" -> "true", see DataBricks documentation

How to make Twitter Bootstrap tooltips have multiple lines?

In Angular UI Bootstrap 0.13.X, tooltip-html-unsafe has been deprecated. You should now use tooltip-html and $sce.trustAsHtml() to accomplish a tooltip with html.

https://github.com/angular-ui/bootstrap/commit/e31fcf0fcb06580064d1e6375dbedb69f1c95f25

<a href="#" tooltip-html="htmlTooltip">Check me out!</a>

$scope.htmlTooltip = $sce.trustAsHtml('I\'ve been made <b>bold</b>!');

Working with $scope.$emit and $scope.$on

<!DOCTYPE html>
<html>

<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('MyApp',[]);
app.controller('parentCtrl',function($scope){
  $scope.$on('MyEvent',function(event,data){    
    $scope.myData = data;
  });
 });

app.controller('childCtrl',function($scope){
  $scope.fireEvent = function(){ 
  $scope.$emit('MyEvent','Any Data');
  }  
 });
</script>
</head>
<body ng-app="MyApp">
<div ng-controller="parentCtrl" ng-model="myName">

{{myData}}

 <div ng-controller="childCtrl">
   <button ng-click="fireEvent()">Fire Event</button>
 </div>

</div>
</body>
</html>

Update int column in table with unique incrementing values

Try something like this:

with toupdate as (
    select p.*,
           (coalesce(max(interfaceid) over (), 0) +
            row_number() over (order by (select NULL))
           ) as newInterfaceId
    from prices
   )
update p
    set interfaceId = newInterfaceId
    where interfaceId is NULL

This doesn't quite make them consecutive, but it does assign new higher ids. To make them consecutive, try this:

with toupdate as (
    select p.*,
           (coalesce(max(interfaceid) over (), 0) +
            row_number() over (partition by interfaceId order by (select NULL))
           ) as newInterfaceId
    from prices
   )
update p
    set interfaceId = newInterfaceId
    where interfaceId is NULL

Find the item with maximum occurrences in a list

I am surprised no-one has mentioned the simplest solution,max() with the key list.count:

max(lst,key=lst.count)

Example:

>>> lst = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
>>> max(lst,key=lst.count)
4

This works in Python 3 or 2, but note that it only returns the most frequent item and not also the frequency. Also, in the case of a draw (i.e. joint most frequent item) only a single item is returned.

Although the time complexity of using max() is worse than using Counter.most_common(1) as PM 2Ring comments, the approach benefits from a rapid C implementation and I find this approach is fastest for short lists but slower for larger ones (Python 3.6 timings shown in IPython 5.3):

In [1]: from collections import Counter
   ...: 
   ...: def f1(lst):
   ...:     return max(lst, key = lst.count)
   ...: 
   ...: def f2(lst):
   ...:     return Counter(lst).most_common(1)
   ...: 
   ...: lst0 = [1,2,3,4,3]
   ...: lst1 = lst0[:] * 100
   ...: 

In [2]: %timeit -n 10 f1(lst0)
10 loops, best of 3: 3.32 us per loop

In [3]: %timeit -n 10 f2(lst0)
10 loops, best of 3: 26 us per loop

In [4]: %timeit -n 10 f1(lst1)
10 loops, best of 3: 4.04 ms per loop

In [5]: %timeit -n 10 f2(lst1)
10 loops, best of 3: 75.6 us per loop

Fork() function in C

int a = fork(); 

Creates a duplicate process "clone?", which shares the execution stack. The difference between the parent and the child is the return value of the function.

The child getting 0 returned, and the parent getting the new pid.

Each time the addresses and the values of the stack variables are copied. The execution continues at the point it already got to in the code.

At each fork, only one value is modified - the return value from fork.

Python - abs vs fabs

abs() : Returns the absolute value as per the argument i.e. if argument is int then it returns int, if argument is float it returns float. Also it works on complex variable also i.e. abs(a+bj) also works and returns absolute value i.e.math.sqrt(((a)**2)+((b)**2)

math.fabs() : It only works on the integer or float values. Always returns the absolute float value no matter what is the argument type(except for the complex numbers).

Is there any way to have a fieldset width only be as wide as the controls in them?

try this

<fieldset>
   <legend style="max-width: max-content;" >Blah</legend>
</fieldset>

PHP memcached Fatal error: Class 'Memcache' not found

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

sudo apt-get install php5-memcache

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

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

How to read numbers separated by space using scanf

int main()
{
char string[200];
int g,a,i,G[20],A[20],met;

gets(string);
g=convert_input(G,string);

for(i=0;i<=g;i++)
    printf("\n%d>>%d",i,G[i]);
return 0;
}

int convert_input(int K[],char string[200])
{
int j=0,i=0,temp=0;
while(string[i]!='\0')
{
    temp=0;
    while(string[i]!=' ' && string[i]!='\0')
        temp=temp*10 + (string[i++]-'0') ;
    if(string[i]==' ')
        i++;
    K[j++]=temp;
}
return j-1;
}

Using NSLog for debugging

type : BOOL DATA (YES/NO) OR(1/0)

BOOL dtBool = 0; 

OR

BOOL dtBool = NO;
NSLog(dtBool ? @"Yes" : @"No");

OUTPUT : NO

type : Long

long aLong = 2015;
NSLog(@"Display Long: %ld”, aLong);

OUTPUT : Display Long: 2015

long long veryLong = 20152015;
NSLog(@"Display very Long: %lld", veryLong);

OUTPUT : Display very Long: 20152015

type : String

NSString *aString = @"A string";
NSLog(@"Display string: %@", aString);

OUTPUT : Display String: a String

type : Float

float aFloat = 5.34245;
NSLog(@"Display Float: %F", aFloat);

OUTPUT : isplay Float: 5.342450

type : Integer

int aInteger = 3;    
NSLog(@"Display Integer: %i", aInteger);

OUTPUT : Display Integer: 3

NSLog(@"\nDisplay String: %@ \n\n Display Float: %f \n\n Display Integer: %i", aString, aFloat, aInteger);

OUTPUT : String: a String

Display Float: 5.342450

Display Integer: 3

http://luterr.blogspot.sg/2015/04/example-code-nslog-console-commands-to.html

Radio button validation in javascript

You could do something like this

var option=document.getElementsByName('Gender');

if (!(option[0].checked || option[1].checked)) {
    alert("Please Select Your Gender");
    return false;
}

How to get ID of clicked element with jQuery

Your IDs are #1, and cycle just wants a number passed to it. You need to remove the # before calling cycle.

$('a.pagerlink').click(function() { 
    var id = $(this).attr('id');
    $container.cycle(id.replace('#', '')); 
    return false; 
});

Also, IDs shouldn't contain the # character, it's invalid (numeric IDs are also invalid). I suggest changing the ID to something like pager_1.

<a href="#" id="pager_1" class="pagerlink" >link</a>

$('a.pagerlink').click(function() { 
    var id = $(this).attr('id');
    $container.cycle(id.replace('pager_', '')); 
    return false; 
});

What's the valid way to include an image with no src?

As written in comments, this method is wrong.

I didn't find this answer before, but acording to W3 Specs valid empty src tag would be an anchor link #.

Example: src="#", src="#empty"

Page validates successfully and no extra request are made.

Run bash script from Windows PowerShell

If you add the extension .SH to the environment variable PATHEXT, you will be able to run shell scripts from PowerShell by only using the script name with arguments:

PS> .\script.sh args

If you store your scripts in a directory that is included in your PATH environment variable, you can run it from anywhere, and omit the extension and path:

PS> script args

Note: sh.exe or another *nix shell must be associated with the .sh extension.

How to convert a string into double and vice versa?

I ended up using this handy macro:

#define STRING(value)               [@(value) stringValue]

Disabled href tag

Letting a parent have pointer-events: none will disable the child a-tag like this (requires that the div covers the a and hasn't 0 width/height):

<div class="disabled">
   <a href="/"></a>
</div>

where:

.disabled {
    pointer-events: none;
}

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

For anyone who lands here and all the other solutions did not work give this a try. I am using typescript + react and my problem was that I was associating the files in vscode as javascriptreact not typescriptreact so check your settings for the following entries.

   "files.associations": {
    "*.tsx": "typescriptreact",
    "*.ts": "typescriptreact"
  },

PHP If Statement with Multiple Conditions

I don't know if $var is a string and you want to find only those expressions but here it goes either way.

Try to use preg_match http://php.net/manual/en/function.preg-match.php

if(preg_match('abc', $val) || preg_match('def', $val) || ...)
   echo "true"

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

I had the same problem with exactly the same error message. In the end the error was, that I still called the maps v2 javascript. I had to replace:

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=####################" type="text/javascript"></script>

with

<script src="http://maps.googleapis.com/maps/api/js?key=####################&sensor=false" type="text/javascript"></script>

after this, it worked fine. took me a while ;-)

Passing references to pointers in C++

I know that it's posible to pass references of pointers, I did it last week, but I can't remember what the syntax was, as your code looks correct to my brain right now. However another option is to use pointers of pointers:

Myfunc(String** s)

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

I know I'm 4 years late but my answer is for anyone who may not have figured it out. I'm using a Samsung Galaxy S6, what worked for me was:

  1. Disable USB debugging

  2. Disable Developer mode

  3. Unplug the device from the USB cable

  4. Re-enable Developer mode

  5. Re-enable USB debugging

  6. Reconnect the USB cable to your device

It is important you do it in this order as it didn't work until it was done in this order.

Open popup and refresh parent page on close popup

If your app runs on an HTML5 enabled browser. You can use postMessage. The example given there is quite similar to yours.

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

This error is definite mismatch between the data that is advertised in the HTTP Headers and the data transferred over the wire.

It could come from the following:

  1. Server: If a server has a bug with certain modules that changes the content but don't update the content-length in the header or just doesn't work properly. It was the case for the Node HTTP Proxy at some point (see here)

  2. Proxy: Any proxy between you and your server could be modifying the request and not update the content-length header.

As far as I know, I haven't see those problem in IIS but mostly with custom written code.

Let me know if that helps.

How to input a path with a white space?

Use one of these threee variants:

SOME_PATH="/mnt/someProject/some path"
SOME_PATH='/mnt/someProject/some path'
SOME_PATH=/mnt/someProject/some\ path

How do you reindex an array in PHP but with indexes starting from 1?

You may want to consider why you want to use a 1-based array at all. Zero-based arrays (when using non-associative arrays) are pretty standard, and if you're wanting to output to a UI, most would handle the solution by just increasing the integer upon output to the UI.

Think about consistency—both in your application and in the code you work with—when thinking about 1-based indexers for arrays.

What does principal end of an association means in 1:1 relationship in Entity framework

This is with reference to @Ladislav Mrnka's answer on using fluent api for configuring one-to-one relationship.

Had a situation where having FK of dependent must be it's PK was not feasible.

E.g., Foo already has one-to-many relationship with Bar.

public class Foo {
   public Guid FooId;
   public virtual ICollection<> Bars; 
}
public class Bar {
   //PK
   public Guid BarId;
   //FK to Foo
   public Guid FooId;
   public virtual Foo Foo;
}

Now, we had to add another one-to-one relationship between Foo and Bar.

public class Foo {
   public Guid FooId;
   public Guid PrimaryBarId;// needs to be removed(from entity),as we specify it in fluent api
   public virtual Bar PrimaryBar;
   public virtual ICollection<> Bars;
}
public class Bar {
   public Guid BarId;
   public Guid FooId;
   public virtual Foo PrimaryBarOfFoo;
   public virtual Foo Foo;
}

Here is how to specify one-to-one relationship using fluent api:

modelBuilder.Entity<Bar>()
            .HasOptional(p => p.PrimaryBarOfFoo)
            .WithOptionalPrincipal(o => o.PrimaryBar)
            .Map(x => x.MapKey("PrimaryBarId"));

Note that while adding PrimaryBarId needs to be removed, as we specifying it through fluent api.

Also note that method name [WithOptionalPrincipal()][1] is kind of ironic. In this case, Principal is Bar. WithOptionalDependent() description on msdn makes it more clear.

How to create a DateTime equal to 15 minutes ago?

 datetime.datetime.now() - datetime.timedelta(minutes=15)

How can I close a window with Javascript on Mozilla Firefox 3?

self.close() does not work, are you sure you closing a window and not a script generated popup ?

you guys might want to look at this : https://bugzilla.mozilla.org/show_bug.cgi?id=183697

How to delete Tkinter widgets from a window?

Today I learn some simple and good click event handling using tkinter gui library in python3, which I would like to share inside this thread.

from tkinter import *

cnt = 0


def MsgClick(event):
    children = root.winfo_children()
    for child in children:
        # print("type of widget is : " + str(type(child)))
        if str(type(child)) == "<class 'tkinter.Message'>":
            # print("Here Message widget will destroy")
            child.destroy()
            return

def MsgMotion(event):
  print("Mouse position: (%s %s)" % (event.x, event.y))
  return


def ButtonClick(event):
    global cnt, msg
    cnt += 1
    msg = Message(root, text="you just clicked the button..." + str(cnt) + "...time...")
    msg.config(bg='lightgreen', font=('times', 24, 'italic'))
    msg.bind("<Button-1>", MsgClick)
    msg.bind("<Motion>", MsgMotion)
    msg.pack()
    #print(type(msg)) tkinter.Message


def ButtonDoubleClick(event):
    import sys; sys.exit()


root = Tk()

root.title("My First GUI App in Python")
root.minsize(width=300, height=300)
root.maxsize(width=400, height=350)
button = Button(
    root, text="Click Me!", width=40, height=3
)
button.pack()
button.bind("<Button-1>", ButtonClick)
button.bind("<Double-1>", ButtonDoubleClick)

root.mainloop()

Hope it will help someone...

Fragment onCreateView and onActivityCreated called twice

The two upvoted answers here show solutions for an Activity with navigation mode NAVIGATION_MODE_TABS, but I had the same issue with a NAVIGATION_MODE_LIST. It caused my Fragments to inexplicably lose their state when the screen orientation changed, which was really annoying. Thankfully, due to their helpful code I managed to figure it out.

Basically, when using a list navigation, ``onNavigationItemSelected()is automatically called when your activity is created/re-created, whether you like it or not. To prevent your Fragment'sonCreateView()from being called twice, this initial automatic call toonNavigationItemSelected()should check whether the Fragment is already in existence inside your Activity. If it is, return immediately, because there is nothing to do; if it isn't, then simply construct the Fragment and add it to the Activity like you normally would. Performing this check prevents your Fragment from needlessly being created again, which is what causesonCreateView()` to be called twice!

See my onNavigationItemSelected() implementation below.

public class MyActivity extends FragmentActivity implements ActionBar.OnNavigationListener
{
    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";

    private boolean mIsUserInitiatedNavItemSelection;

    // ... constructor code, etc.

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);

        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM))
        {
            getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState)
    {
        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar().getSelectedNavigationIndex());

        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onNavigationItemSelected(int position, long id)
    {    
        Fragment fragment;
        switch (position)
        {
            // ... choose and construct fragment here
        }

        // is this the automatic (non-user initiated) call to onNavigationItemSelected()
        // that occurs when the activity is created/re-created?
        if (!mIsUserInitiatedNavItemSelection)
        {
            // all subsequent calls to onNavigationItemSelected() won't be automatic
            mIsUserInitiatedNavItemSelection = true;

            // has the same fragment already replaced the container and assumed its id?
            Fragment existingFragment = getSupportFragmentManager().findFragmentById(R.id.container);
            if (existingFragment != null && existingFragment.getClass().equals(fragment.getClass()))
            {
                return true; //nothing to do, because the fragment is already there 
            }
        }

        getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
        return true;
    }
}

I borrowed inspiration for this solution from here.

What is a callback function?

A callback function is one that should be called when a certain condition is met. Instead of being called immediately, the callback function is called at a certain point in the future.

Typically it is used when a task is being started that will finish asynchronously (ie will finish some time after the calling function has returned).

For example, a function to request a webpage might require its caller to provide a callback function that will be called when the webpage has finished downloading.

Bootstrap collapse animation not smooth

For others like me who had a different but similar issue where the animation was not occurring at all:

From what I could find it may be something in my browser setting which preferred less motion for accessibility purposes. I could not find any setting in my browser, but I was able to get the animation working by downloading a local copy of bootstrap and commenting out this section of the CSS file:

@media (prefers-reduced-motion: reduce) {
  .collapsing {
    -webkit-transition: none;
    transition: none;
  }
}

Timer Interval 1000 != 1 second?

Any other places you use TimerEventProcessor or Counter?

Anyway, you can not rely on the Event being exactly delivered one per second. The time may vary, and the system will not make sure the average time is correct.

So instead of _Counter, you should use:

 // when starting the timer:
 DateTime _started = DateTime.UtcNow;

 // in TimerEventProcessor:
 seconds = (DateTime.UtcNow-started).TotalSeconds;
 Label.Text = seconds.ToString();

Note: this does not solve the Problem of TimerEventProcessor being called to often, or _Counter incremented to often. it merely masks it, but it is also the right way to do it.

PHP: Split string into array, like explode with no delimiter

Try this:

$str = '123456789';
$char_array = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);

Can I update a JSF component from a JSF backing bean method?

The RequestContext is deprecated from Primefaces 6.2. From this version use the following:

if (componentID != null && PrimeFaces.current().isAjaxRequest()) {
    PrimeFaces.current().ajax().update(componentID);
}

And to execute javascript from the backbean use this way:

PrimeFaces.current().executeScript(jsCommand);

Reference:

ImportError: No module named pythoncom

You are missing the pythoncom package. It comes with ActivePython but you can get it separately on GitHub (previously on SourceForge) as part of pywin32.

You can also simply use:

pip install pywin32

Convert month name to month number in SQL Server

There is no built in function for this.

You could use a CASE statement:

CASE WHEN MonthName= 'January' THEN 1
     WHEN MonthName = 'February' THEN 2
     ...
     WHEN MonthName = 'December' TNEN 12
END AS MonthNumber 

or create a lookup table to join against

CREATE TABLE Months (
    MonthName VARCHAR(20),
    MonthNumber INT
);

INSERT INTO Months
    (MonthName, MonthNumber)
    SELECT 'January', 1
    UNION ALL
    SELECT 'February', 2
    UNION ALL
    ...
    SELECT 'December', 12;

SELECT t.MonthName, m.MonthNumber
    FROM YourTable t
        INNER JOIN Months m
            ON t.MonthName = m.MonthName;

Select where count of one field is greater than one

You can also do this with a self-join:

SELECT t1.* FROM db.table t1
JOIN db.table t2 ON t1.someField = t2.someField AND t1.pk != t2.pk

SELECT * FROM multiple tables. MySQL

What you do here is called a JOIN (although you do it implicitly because you select from multiple tables). This means, if you didn't put any conditions in your WHERE clause, you had all combinations of those tables. Only with your condition you restrict your join to those rows where the drink id matches.

But there are still X multiple rows in the result for every drink, if there are X photos with this particular drinks_id. Your statement doesn't restrict which photo(s) you want to have!

If you only want one row per drink, you have to tell SQL what you want to do if there are multiple rows with a particular drinks_id. For this you need grouping and an aggregate function. You tell SQL which entries you want to group together (for example all equal drinks_ids) and in the SELECT, you have to tell which of the distinct entries for each grouped result row should be taken. For numbers, this can be average, minimum, maximum (to name some).

In your case, I can't see the sense to query the photos for drinks if you only want one row. You probably thought you could have an array of photos in your result for each drink, but SQL can't do this. If you only want any photo and you don't care which you'll get, just group by the drinks_id (in order to get only one row per drink):

SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id

name     price   photo
fanta    5       ./images/fanta-1.jpg
dew      4       ./images/dew-1.jpg

In MySQL, we also have GROUP_CONCAT, if you want the file names to be concatenated to one single string:

SELECT name, price, GROUP_CONCAT(photo, ',')
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id

name     price   photo
fanta    5       ./images/fanta-1.jpg,./images/fanta-2.jpg,./images/fanta-3.jpg
dew      4       ./images/dew-1.jpg,./images/dew-2.jpg

However, this can get dangerous if you have , within the field values, since most likely you want to split this again on the client side. It is also not a standard SQL aggregate function.

How to get date, month, year in jQuery UI datepicker?

Use the javascript Date object.

$(document).ready(function()  {
    $('#calendar').datepicker({
      dateFormat: 'yy-m-d',
      inline: true,
      onSelect: function(dateText, inst) { 
            var date = new Date(dateText);
            // change date.GetDay() to date.GetDate()
            alert(date.getDate() + date.getMonth() + date.getFullYear());
     } 
    });
});

What are the differences between Deferred, Promise and Future in JavaScript?

  • A promise represents a value that is not yet known
  • A deferred represents work that is not yet finished

A promise is a placeholder for a result which is initially unknown while a deferred represents the computation that results in the value.

Reference

When do we need curly braces around shell variables?

In this particular example, it makes no difference. However, the {} in ${} are useful if you want to expand the variable foo in the string

"${foo}bar"

since "$foobar" would instead expand the variable identified by foobar.

Curly braces are also unconditionally required when:

  • expanding array elements, as in ${array[42]}
  • using parameter expansion operations, as in ${filename%.*} (remove extension)
  • expanding positional parameters beyond 9: "$8 $9 ${10} ${11}"

Doing this everywhere, instead of just in potentially ambiguous cases, can be considered good programming practice. This is both for consistency and to avoid surprises like $foo_$bar.jpg, where it's not visually obvious that the underscore becomes part of the variable name.

How do I raise the same Exception with a custom message in Python?

if you want to custom the error type, a simple thing you can do is to define an error class based on ValueError.

How to check if a table is locked in sql server

Better yet, consider sp_getapplock which is designed for this. Or use SET LOCK_TIMEOUT

Otherwise, you'd have to do something with sys.dm_tran_locks which I'd use only for DBA stuff: not for user defined concurrency.

Installing a pip package from within a Jupyter Notebook not working

%pip install fedex    #fedex = package name

in 2019.

In older versions of conda:

import sys
!{sys.executable} -m pip install fedex     #fedex = package name

*note - you do need to import sys

Ajax success event not working

in my case the error was this was in the server side and for that reason it was returning a html

wp_nonce_field(basename(__FILE__), "mu-meta-box-nonce");

Convert Decimal to Varchar

Hope this will help you

Cast(columnName as Numeric(10,2)) 
        or

Cast(@s as decimal(10,2))

I am not getting why you want to cast to varchar?.If you cast to varchar again convert back to decimail for two decimal points

How to compile multiple java source files in command line

OR you could just use javac file1.java and then also use javac file2.java afterwards.

How do I move a redis database from one server to another?

redis-dump finally worked for me. Its documentation provides an example how to dump a Redis database and insert the data into another one.

How to use <md-icon> in Angular Material?

The simplest way today would be to simply request the Material Icons font from Google Fonts, for example in your HTML header tag:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

or in your stylesheet:

@import url(https://fonts.googleapis.com/icon?family=Material+Icons);

and then use as font icon with ligatures as explained in the md-icon directive. For example:

<md-icon aria-label="Menu" class="material-icons">menu</md-icon>

The complete list of icons/ligatures is at https://www.google.com/design/icons/

PHP - Debugging Curl

Output debug info to STDERR:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/get?foo=bar',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify debug option
     */
    CURLOPT_VERBOSE => true,
]);

curl_exec($curlHandler);

curl_close($curlHandler);

Output debug info to file:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/get?foo=bar',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify debug option.
     */
    CURLOPT_VERBOSE => true,

    /**
     * Specify log file.
     * Make sure that the folder is writable.
     */
    CURLOPT_STDERR => fopen('./curl.log', 'w+'),
]);

curl_exec($curlHandler);

curl_close($curlHandler);

See https://github.com/andriichuk/php-curl-cookbook#debug-request

How to escape braces (curly brackets) in a format string in .NET

You can use double open brackets and double closing brackets which will only show one bracket on your page.

Angular EXCEPTION: No provider for Http

I faced this issue in my code. I only put this code in my app.module.ts.

import { HttpModule } from '@angular/http';

@NgModule({
  imports:      [ BrowserModule, HttpModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Conda: Installing / upgrading directly from github

conda doesn't support this directly because it installs from binaries, whereas git install would be from source. conda build does support recipes that are built from git. On the other hand, if all you want to do is keep up-to-date with the latest and greatest of a package, using pip inside of Anaconda is just fine, or alternately, use setup.py develop against a git clone.

ValueError: could not convert string to float: id

Your data may not be what you expect -- it seems you're expecting, but not getting, floats.

A simple solution to figuring out where this occurs would be to add a try/except to the for-loop:

for i in range(0,N):
    w=f[i].split()
    l1=w[1:8]
    l2=w[8:15]
    try:
      list1=[float(x) for x in l1]
      list2=[float(x) for x in l2]
    except ValueError, e:
      # report the error in some way that is helpful -- maybe print out i
    result=stats.ttest_ind(list1,list2)
    print result[1]

HTTP POST using JSON in Java

Java 8 with apache httpClient 4

CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("www.site.com");


String json = "details={\"name\":\"myname\",\"age\":\"20\"} ";

        try {
            StringEntity entity = new StringEntity(json);
            httpPost.setEntity(entity);

            // set your POST request headers to accept json contents
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            try {
                // your closeablehttp response
                CloseableHttpResponse response = client.execute(httpPost);

                // print your status code from the response
                System.out.println(response.getStatusLine().getStatusCode());

                // take the response body as a json formatted string 
                String responseJSON = EntityUtils.toString(response.getEntity());

                // convert/parse the json formatted string to a json object
                JSONObject jobj = new JSONObject(responseJSON);

                //print your response body that formatted into json
                System.out.println(jobj);

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {

                e.printStackTrace();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

How to print table using Javascript?

Here is your code in a jsfiddle example. I have tested it and it looks fine.

http://jsfiddle.net/dimshik/9DbEP/4/

I used a simple table, maybe you are missing some CSS on your new page that was created with JavaScript.

<table border="1" cellpadding="3" id="printTable">
    <tbody><tr>
        <th>First Name</th>
        <th>Last Name</th>      
        <th>Points</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>      
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>        
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>        
        <td>80</td>
    </tr>
    <tr>
        <td>Adam</td>
        <td>Johnson</td>        
        <td>67</td>
    </tr>
</tbody></table>

Is it possible to change the content HTML5 alert messages?

Yes:

<input required title="Enter something OR ELSE." /> 

The title attribute will be used to notify the user of a problem.

Get the previous month's first and last day dates in c#

This is a take on Mike W's answer:

internal static DateTime GetPreviousMonth(bool returnLastDayOfMonth)
{
    DateTime firstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );
    DateTime lastDayOfLastMonth = firstDayOfThisMonth.AddDays (-1);
    if (returnLastDayOfMonth) return lastDayOfLastMonth;
    return firstDayOfThisMonth.AddMonths(-1);
}

You can call it like so:

dateTimePickerFrom.Value = GetPreviousMonth(false);
dateTimePickerTo.Value = GetPreviousMonth(true);

Reverse order of foreach list items

<?php
    $j=1; 


      array_reverse($skills_nav);   


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

Android LinearLayout : Add border with shadow around a LinearLayout

This is so simple:

Create a drawable file with a gradient like this:

for shadow below a view below_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">   
<gradient
    android:startColor="#20000000"
    android:endColor="@android:color/transparent"
    android:angle="270" >
</gradient>
</shape>

for shadow above a view above_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">   
<gradient
    android:startColor="#20000000"
    android:endColor="@android:color/transparent"
    android:angle="90" >
</gradient>
</shape>

and so on for right and left shadow just change the angle of the gradient :)

Make footer stick to bottom of page using Twitter Bootstrap

Most of the above mentioned solution didn't worked for me. However, below given solution works just fine:

<div class="fixed-bottom">...</div>      

Source

How to get the current time in Python

.isoformat() is in the documentation, but not yet here (this is mighty similar to @Ray Vega's answer):

>>> import datetime
>>> datetime.datetime.now().isoformat()
'2013-06-24T20:35:55.982000'

How do I create a MongoDB dump of my database?

Backup/Restore Mongodb with timing.

Backup:

sudo mongodump --db db_name --out /path_of_your_backup/`date +"%m-%d-%y"`

--db argument for databse name

--out argument for path of output

Restore:

sudo mongorestore --db db_name --drop /path_of_your_backup/01-01-19/db_name/

--drop argument for drop databse before restore

Timing:

You can use crontab for timing backup:

sudo crontab -e

It opens with editor(e.g. nano)

3 3 * * * mongodump --out /path_of_your_backup/`date +"%m-%d-%y"`

backup every day at 03:03 AM

Depending on your MongoDB database sizes you may soon run out of disk space with too many backups. That's why it's also recommended to clean the old backups regularly or to compress them. For example, to delete all the backups older than 7 days you can use the following bash command:

3 1 * * * find /path_of_your_backup/ -mtime +7 -exec rm -rf {} \;

delete all the backups older than 7 days

Good Luck.

ref: https://www.digitalocean.com/community/tutorials/how-to-back-up-restore-and-migrate-a-mongodb-database-on-ubuntu-14-04

update package.json version automatically

With Husky:

{
  "name": "demo-project",
  "version": "0.0.3",
  "husky": {
    "hooks": {
      "pre-commit": "npm --no-git-tag-version version patch && git add ."
    }
  }
}

Is it possible to change javascript variable values while debugging in Google Chrome?

I don't know why chrome team don't allow this silly feature ... but the only way I could change variable values with success is to modify the script directly in the chrome editor under "Sources" Tab (this changes the behavior of your script until you refresh the page), but that changes will lost when refresh, so be carefull.

Python: most idiomatic way to convert None to empty string?

I use max function:

max(None, '')  #Returns blank
max("Hello",'') #Returns Hello

Works like a charm ;) Just put your string in the first parameter of the function.

Is it a bad practice to use break in a for loop?

On MISRA 98 rules, that is used on my company in C dev, break statement shall not be used...

Edit : Break is allowed in MISRA '04

Add column with constant value to pandas dataframe

The reason this puts NaN into a column is because df.index and the Index of your right-hand-side object are different. @zach shows the proper way to assign a new column of zeros. In general, pandas tries to do as much alignment of indices as possible. One downside is that when indices are not aligned you get NaN wherever they aren't aligned. Play around with the reindex and align methods to gain some intuition for alignment works with objects that have partially, totally, and not-aligned-all aligned indices. For example here's how DataFrame.align() works with partially aligned indices:

In [7]: from pandas import DataFrame

In [8]: from numpy.random import randint

In [9]: df = DataFrame({'a': randint(3, size=10)})

In [10]:

In [10]: df
Out[10]:
   a
0  0
1  2
2  0
3  1
4  0
5  0
6  0
7  0
8  0
9  0

In [11]: s = df.a[:5]

In [12]: dfa, sa = df.align(s, axis=0)

In [13]: dfa
Out[13]:
   a
0  0
1  2
2  0
3  1
4  0
5  0
6  0
7  0
8  0
9  0

In [14]: sa
Out[14]:
0     0
1     2
2     0
3     1
4     0
5   NaN
6   NaN
7   NaN
8   NaN
9   NaN
Name: a, dtype: float64

How to use apply a custom drawable to RadioButton?

In programmatically, add the background image

minSdkVersion 16

RadioGroup rg = new RadioGroup(this);
RadioButton radioButton = new RadioButton(this);
radioButton.setBackground(R.drawable.account_background);
rg.addView(radioButton);

Error: Local workspace file ('angular.json') could not be found

For me what worked was creating a new Angular project and just copied the angular.json file in the project that had a problem due to the fact that the angular.json file was missing.

How to programmatically set the ForeColor of a label to its default?

DefaultForeColor is enough for this statement. This property gets the default foreground color of the control.

lblExample.ForeColor = DefaultForeColor;

Assign static IP to Docker container

Not a direct answer but it could help.

I run most of my dockerized services tied to own static ips using the next approach:

  1. I create ip aliases for all services on docker host
  2. Then I run each service redirecting ports from this ip into container so each service have own static ip which could be used by external users and other containers.

Sample:

docker run --name dns --restart=always -d -p 172.16.177.20:53:53/udp dns
docker run --name registry --restart=always -d -p 172.16.177.12:80:5000 registry
docker run --name cache --restart=always -d -p 172.16.177.13:80:3142 -v /data/cache:/var/cache/apt-cacher-ng cache
docker run --name mirror --restart=always -d -p 172.16.177.19:80:80 -v /data/mirror:/usr/share/nginx/html:ro mirror
...

Is it possible in Java to catch two exceptions in the same catch block?

Java <= 6.x just allows you to catch one exception for each catch block:

try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}

Documentation:

Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class.

For Java 7 you can have multiple Exception caught on one catch block:

catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

Documentation:

In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.

Reference: http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

Run a .bat file using python code

Replace \ with / in the path

import os
os.system("D:/xxx1/xxx2XMLnew/otr.bat ")

Align div right in Bootstrap 3

Add offset8 to your class, for example:

<div class="offset8">aligns to the right</div>

X-Frame-Options Allow-From multiple domains

One possible workaround would be using a "frame-breaker" script as described here

You just need to alter the "if" statement to check for your allowed domains.

   if (self === top) {
       var antiClickjack = document.getElementById("antiClickjack");
       antiClickjack.parentNode.removeChild(antiClickjack);
   } else {
       //your domain check goes here
       if(top.location.host != "allowed.domain1.com" && top.location.host == "allowed.domain2.com")
         top.location = self.location;
   }

This workaround would be safe, I think. because with javascript not enabled you will have no security concern about a malicious website framing your page.

How to change line width in ggplot?

Line width in ggplot2 can be changed with argument size= in geom_line().

#sample data
df<-data.frame(x=rnorm(100),y=rnorm(100))
ggplot(df,aes(x=x,y=y))+geom_line(size=2)

enter image description here

How to recover just deleted rows in mysql?

If you use MyISAM tables, then you can recover any data you deleted, just

open file: mysql/data/[your_db]/[your_table].MYD

with any text editor

python: Appending a dictionary to a list - I see a pointer like behavior

You are correct in that your list contains a reference to the original dictionary.

a.append(b.copy()) should do the trick.

Bear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b), which makes a deep copy.

" app-release.apk" how to change this default generated apk name

My solution may also be of help to someone.

Tested and Works on IntelliJ 2017.3.2 with Gradle 4.4

Scenario:

I have 2 flavours in my application, and so I wanted each release to be named appropriately according to each flavor.

The code below will be placed into your module gradle build file found in:

{app-root}/app/build.gradle

Gradle code to be added to android{ } block:

android {
    // ...

    defaultConfig {
        versionCode 10
        versionName "1.2.3_build5"
    }

    buildTypes {
        // ...

        release {
            // ...

            applicationVariants.all { 
                variant.outputs.each { output ->
                    output.outputFile = new File(output.outputFile.parent, output.outputFile.name.replace(output.outputFile.name, variant.flavorName + "-" + defaultConfig.versionName + "_v" + defaultConfig.versionCode + ".apk"))
                }
            }

        }
    }

    productFlavors {
        myspicyflavor {
            applicationIdSuffix ".MySpicyFlavor"
            signingConfig signingConfigs.debug
        }

        mystandardflavor {
            applicationIdSuffix ".MyStandardFlavor"
            signingConfig signingConfigs.config
        }
    }
}

The above provides the following APKs found in {app-root}/app/:

myspicyflavor-release-1.2.3_build5_v10.apk
mystandardflavor-release-1.2.3_build5_v10.apk

Hope it can be of use to someone.

For more info, see other answers mentioned in the question

jQuery UI Alert Dialog as a replacement for alert()

There is an issue that if you close the dialog it will execute the onCloseCallback function. This is a better design.

function jAlert2(outputMsg, titleMsg, onCloseCallback) {
    if (!titleMsg)
        titleMsg = 'Alert';

    if (!outputMsg)
        outputMsg = 'No Message to Display.';

    $("<div></div>").html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": onCloseCallback,
            "Cancel": function() {
          $( this ).dialog( "destroy" );
            }

        },
    });

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

Probably you don't have space in your hard drive. Check it by typing in the promt df -h

Please note that mongo might fail even with 3gb available in the corresponding partition. For details, you might want to check the log: cat /var/log/mongodb/mongod.log

Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?

You need to re-add that certificate to your machine or chose another certificate.

To choose another certificate or to recreate one, head over to the Project's properties page, click on Signing tab and either

  • Click on Select from store
  • Click on Select from file
  • Click on Create test certificate

Once either of these is done, you should be able to build it again.

How can I completely uninstall nodejs, npm and node in Ubuntu

It bothered me too much while updating node version from 8.1.0 to 10.14.0

Here is what worked for me:

  1. Open terminal (Ctrl+Alt+T).

  2. Type which node, which will give a path something like /usr/local/bin/node

  3. Run the command sudo rm /usr/local/bin/node to remove the binary (adjust the path according to what you found in step 2). Now node -v shows you have no node version

  4. Download a script and run it to set up the environment:

    curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
    
  5. Install using sudo apt-get install nodejs

    Note: If you are getting error like

    node /usr/bin/env: node: No such file or directory
    

    just run

    ln -s /usr/bin/nodejs /usr/bin/node
    

    Source

  6. Now node -v will give v10.14.0

Worked for me.

jquery variable syntax

$self has little to do with $, which is an alias for jQuery in this case. Some people prefer to put a dollar sign together with the variable to make a distinction between regular vars and jQuery objects.

example:

var self = 'some string';
var $self = 'another string';

These are declared as two different variables. It's like putting underscore before private variables.

A somewhat popular pattern is:

var foo = 'some string';
var $foo = $('.foo');

That way, you know $foo is a cached jQuery object later on in the code.

How to add reference to a method parameter in javadoc?

The correct way of referring to a method parameter is like this:

enter image description here

Javascript validation: Block special characters

Try this one, this function allows alphanumeric and spaces:

function alpha(e) {
    var k;
    document.all ? k = e.keyCode : k = e.which;
    return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}

in your html:

<input type="text" name="name"  onkeypress="return alpha(event)"/>

How to iterate over a JSONObject?

This is is another working solution to the problem:

public void test (){

    Map<String, String> keyValueStore = new HasMap<>();
    Stack<String> keyPath = new Stack();
    JSONObject json = new JSONObject("thisYourJsonObject");
    keyValueStore = getAllXpathAndValueFromJsonObject(json, keyValueStore, keyPath);
    for(Map.Entry<String, String> map : keyValueStore.entrySet()) {
        System.out.println(map.getKey() + ":" + map.getValue());
    }   
}

public Map<String, String> getAllXpathAndValueFromJsonObject(JSONObject json, Map<String, String> keyValueStore, Stack<String> keyPath) {
    Set<String> jsonKeys = json.keySet();
    for (Object keyO : jsonKeys) {
        String key = (String) keyO;
        keyPath.push(key);
        Object object = json.get(key);

        if (object instanceof JSONObject) {
            getAllXpathAndValueFromJsonObject((JSONObject) object, keyValueStore, keyPath);
        }

        if (object instanceof JSONArray) {
            doJsonArray((JSONArray) object, keyPath, keyValueStore, json, key);
        }

        if (object instanceof String || object instanceof Boolean || object.equals(null)) {
            String keyStr = "";

            for (String keySub : keyPath) {
                keyStr += keySub + ".";
            }

            keyStr = keyStr.substring(0, keyStr.length() - 1);

            keyPath.pop();

            keyValueStore.put(keyStr, json.get(key).toString());
        }
    }

    if (keyPath.size() > 0) {
        keyPath.pop();
    }

    return keyValueStore;
}

public void doJsonArray(JSONArray object, Stack<String> keyPath, Map<String, String> keyValueStore, JSONObject json,
        String key) {
    JSONArray arr = (JSONArray) object;
    for (int i = 0; i < arr.length(); i++) {
        keyPath.push(Integer.toString(i));
        Object obj = arr.get(i);
        if (obj instanceof JSONObject) {
            getAllXpathAndValueFromJsonObject((JSONObject) obj, keyValueStore, keyPath);
        }

        if (obj instanceof JSONArray) {
            doJsonArray((JSONArray) obj, keyPath, keyValueStore, json, key);
        }

        if (obj instanceof String || obj instanceof Boolean || obj.equals(null)) {
            String keyStr = "";

            for (String keySub : keyPath) {
                keyStr += keySub + ".";
            }

            keyStr = keyStr.substring(0, keyStr.length() - 1);

            keyPath.pop();

            keyValueStore.put(keyStr , json.get(key).toString());
        }
    }
    if (keyPath.size() > 0) {
        keyPath.pop();
    }
}

keyCode values for numeric keypad?

******************* Don't use KEYCODE !!!! ******************

The problem with keyCode is to avoid the combined keys with the numbers on top of keyboard, we must add a check on the key "Shift" and "Alt" to avoid special characters such as e @ & " { } ...

A simplest solution is to convert e.key to a number and check if the conversion gives NaN!

let key = Number(e.key)
if (isNaN(key) || e.key === null || e.key === ' ') {
  console.log("is not numeric")
}
else {
  console.log("is numeric")
}

Be careful if e.key is null or a space, it gives 0 !

Number(5)         // => 5
Number('5')       // => 5
Number(null)      // => 0 
Number(' ')       // => 0
Number('chars')   // => NaN
Number(undefined) // => NaN

Setting environment variables on OS X

While the answers here aren't "wrong", I'll add another: never make environment variable changes in OS X that affect "all processes", or even, outside the shell, for all processes run interactively by a given user.

In my experience, global changes to environment variables like PATH for all processes are even more likely to break things on OS X than on Windows. Reason being, lots of OS X applications and other software (including, perhaps especially, components of the OS itself) rely on UNIX command-line tools under the hood, and assume the behavior of the versions of these tools provided with the system, and don't necessarily use absolute paths when doing so (similar comments apply to dynamically-loaded libraries and DYLD_* environment variables). Consider, for instance, that the highest-rated answers to various Stack Overflow questions about replacing OS X-supplied versions of interpreters like Python and Ruby generally say "don't do this."

OS X is really no different than other UNIX-like operating systems (e.g., Linux, FreeBSD, and Solaris) in this respect; the most likely reason Apple doesn't provide an easy way to do this is because it breaks things. To the extent Windows isn't as prone to these problems, it's due to two things: (1) Windows software doesn't tend to rely on command-line tools to the extent that UNIX software does, and (2) Microsoft has had such an extensive history of both "DLL hell" and security problems caused by changes that affect all processes that they've changed the behavior of dynamic loading in newer Windows versions to limit the impact of "global" configuration options like PATH.

"Lame" or not, you'll have a far more stable system if you restrict such changes to smaller scopes.

Is there a way to add a gif to a Markdown file?

If you can provide your image in SVG format and if it is an icon and not a photo so it can be animated with SMIL animations, then it would be definitely the superior alternative to gif images (or even other formats).

SVG images, like other image files, could be used with either standard markup or HTML <img> element:

![image description](the_path_to/image.svg)
<img src="the_path_to/image.svg" width="128"/>

nvm keeps "forgetting" node in new terminal session

Also in case you had node installed before nvm check in your ~/.bash_profile to not have something like :

export PATH=/bin:/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:$PATH

If you do have it, comment/remove it and nvm should start handling the default node version.

How do I insert a JPEG image into a python Tkinter window?

import tkinter as tk
from tkinter import ttk
from PIL import Image,  ImageTk
win = tk. Tk()
image1 = Image. open("Aoran. jpg")
image2 =  ImageTk. PhotoImage(image1)
image_label = ttk. Label(win , image =.image2)
image_label.place(x = 0 , y = 0)
win.mainloop()

How to call any method asynchronously in c#

If you use action.BeginInvoke(), you have to call EndInvoke somewhere - else the framework has to hold the result of the async call on the heap, resulting in a memory leak.

If you don't want to jump to C# 5 with the async/await keywords, you can just use the Task Parallels library in .Net 4. It's much, much nicer than using BeginInvoke/EndInvoke, and gives a clean way to fire-and-forget for async jobs:

using System.Threading.Tasks;
...
void Foo(){}
...
new Task(Foo).Start();

If you have methods to call that take parameters, you can use a lambda to simplify the call without having to create delegates:

void Foo2(int x, string y)
{
    return;
}
...
new Task(() => { Foo2(42, "life, the universe, and everything");}).Start();

I'm pretty sure (but admittedly not positive) that the C# 5 async/await syntax is just syntactic sugar around the Task library.

java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

Why this might have happened:

  1. The server couldn't send a response: Ensure that the backend is working properly at IP and port mentioned.
  2. SSL connections are being blocked: Fix this by importing SSL certificates

Less likely:

  1. Cookies not being sent
  2. Request timeout: Change request timeout

Read from database and fill DataTable

Private Function LoaderData(ByVal strSql As String) As DataTable
    Dim cnn As SqlConnection
    Dim dad As SqlDataAdapter

    Dim dtb As New DataTable
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        dad = New SqlDataAdapter(strSql, cnn)
        dad.Fill(dtb)
        cnn.Close()
        dad.Dispose()
    Catch ex As Exception
        cnn.Close()
        MsgBox(ex.Message)
    End Try
    Return dtb
End Function

Resource from src/main/resources not found after building with maven

Resources from src/main/resources will be put onto the root of the classpath, so you'll need to get the resource as:

new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/config.txt")));

You can verify by looking at the JAR/WAR file produced by maven as you'll find config.txt in the root of your archive.

Jquery to get SelectedText from dropdown

$("#SelectedCountryId_option_selected")[0].textContent

this worked for me, here instead of [0], pass the selected index of your drop down list.

$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST'

It's really a 6 of one, a half-dozen of the other situation.

The only possible argument against your approach is $_SERVER['REQUEST_METHOD'] == 'POST' may not be populated on certain web-servers/configuration, whereas the $_POST array will always exist in PHP4/PHP5 (and if it doesn't exist, you have bigger problems (-:)

How to calculate percentage with a SQL statement

Instead of using a separate CTE to get the total, you can use a window function without the "partition by" clause.

If you are using:

count(*)

to get the count for a group, you can use:

sum(count(*)) over ()

to get the total count.

For example:

select Grade, 100. * count(*) / sum(count(*)) over ()
from table
group by Grade;

It tends to be faster in my experience, but I think it might internally use a temp table in some cases (I've seen "Worktable" when running with "set statistics io on").

EDIT: I'm not sure if my example query is what you are looking for, I was just illustrating how the windowing functions work.

How do I redirect in expressjs while passing some context?

Here s what I suggest without using any other dependency , just node and express, use app.locals, here s an example :

    app.get("/", function(req, res) {
        var context = req.app.locals.specialContext;
        req.app.locals.specialContext = null;
        res.render("home.jade", context); 
        // or if you are using ejs
        res.render("home", {context: context}); 
    });

    function middleware(req, res, next) {
        req.app.locals.specialContext = * your context goes here *
        res.redirect("/");
    }

Excel doesn't update value unless I hit Enter

I Encounter this problem before. I suspect that is some of ur cells are link towards other sheet, which the other sheets is returning #NAME? which ends up the current sheets is not working on calculation.

Try solve ur other sheets that is linked

How To: Execute command line in C#, get STD OUT results

You can launch any command line program using the Process class, and set the StandardOutput property of the Process instance with a stream reader you create (either based on a string or a memory location). After the process completes, you can then do whatever diff you need to on that stream.

Understanding the results of Execute Explain Plan in Oracle SQL Developer

Here is a reference for using EXPLAIN PLAN with Oracle: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm), with specific information about the columns found here: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm#i18300

Your mention of 'FULL' indicates to me that the query is doing a full-table scan to find your data. This is okay, in certain situations, otherwise an indicator of poor indexing / query writing.

Generally, with explain plans, you want to ensure your query is utilizing keys, thus Oracle can find the data you're looking for with accessing the least number of rows possible. Ultimately, you can sometime only get so far with the architecture of your tables. If the costs remain too high, you may have to think about adjusting the layout of your schema to be more performance based.

How to automate browsing using python?

Selenium2 includes webdriver, which has python bindings and allows one to use the headless htmlUnit driver, or switch to firefox or chrome for graphical debugging.

Multiple cases in switch statement

This syntax is from the Visual Basic Select...Case Statement:

Dim number As Integer = 8
Select Case number
    Case 1 To 5
        Debug.WriteLine("Between 1 and 5, inclusive")
        ' The following is the only Case clause that evaluates to True.
    Case 6, 7, 8
        Debug.WriteLine("Between 6 and 8, inclusive")
    Case Is < 1
        Debug.WriteLine("Equal to 9 or 10")
    Case Else
        Debug.WriteLine("Not between 1 and 10, inclusive")
End Select

You cannot use this syntax in C#. Instead, you must use the syntax from your first example.

Body of Http.DELETE request in Angular2

Below is a relevant code example for Angular 4/5 with the new HttpClient.

import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';

public removeItem(item) {
    let options = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
      }),
      body: item,
    };

    return this._http
      .delete('/api/menu-items', options)
      .map((response: Response) => response)
      .toPromise()
      .catch(this.handleError);
  }

What's the difference between OpenID and OAuth?

The explanation of the difference between OpenID, OAuth, OpenID Connect:

OpenID is a protocol for authentication while OAuth is for authorization. Authentication is about making sure that the guy you are talking to is indeed who he claims to be. Authorization is about deciding what that guy should be allowed to do.

In OpenID, authentication is delegated: server A wants to authenticate user U, but U's credentials (e.g. U's name and password) are sent to another server, B, that A trusts (at least, trusts for authenticating users). Indeed, server B makes sure that U is indeed U, and then tells to A: "ok, that's the genuine U".

In OAuth, authorization is delegated: entity A obtains from entity B an "access right" which A can show to server S to be granted access; B can thus deliver temporary, specific access keys to A without giving them too much power. You can imagine an OAuth server as the key master in a big hotel; he gives to employees keys which open the doors of the rooms that they are supposed to enter, but each key is limited (it does not give access to all rooms); furthermore, the keys self-destruct after a few hours.

To some extent, authorization can be abused into some pseudo-authentication, on the basis that if entity A obtains from B an access key through OAuth, and shows it to server S, then server S may infer that B authenticated A before granting the access key. So some people use OAuth where they should be using OpenID. This schema may or may not be enlightening; but I think this pseudo-authentication is more confusing than anything. OpenID Connect does just that: it abuses OAuth into an authentication protocol. In the hotel analogy: if I encounter a purported employee and that person shows me that he has a key which opens my room, then I suppose that this is a true employee, on the basis that the key master would not have given him a key which opens my room if he was not.

(source)

How is OpenID Connect different than OpenID 2.0?

OpenID Connect performs many of the same tasks as OpenID 2.0, but does so in a way that is API-friendly, and usable by native and mobile applications. OpenID Connect defines optional mechanisms for robust signing and encryption. Whereas integration of OAuth 1.0a and OpenID 2.0 required an extension, in OpenID Connect, OAuth 2.0 capabilities are integrated with the protocol itself.

(source)

OpenID connect will give you an access token plus an id token. The id token is a JWT and contains information about the authenticated user. It is signed by the identity provider and can be read and verified without accessing the identity provider.

In addition, OpenID connect standardizes quite a couple things that oauth2 leaves up to choice. for instance scopes, endpoint discovery, and dynamic registration of clients.

This makes it easier to write code that lets the user choose between multiple identity providers.

(source)

Google's OAuth 2.0

Google's OAuth 2.0 APIs can be used for both authentication and authorization. This document describes our OAuth 2.0 implementation for authentication, which conforms to the OpenID Connect specification, and is OpenID Certified. The documentation found in Using OAuth 2.0 to Access Google APIs also applies to this service. If you want to explore this protocol interactively, we recommend the Google OAuth 2.0 Playground.

(source)

Named tuple and default values for optional keyword arguments

Wrap it in a function.

NodeT = namedtuple('Node', 'val left right')

def Node(val, left=None, right=None):
  return NodeT(val, left, right)

Convert string to symbol-able in ruby

from: http://ruby-doc.org/core/classes/String.html#M000809

str.intern => symbol
str.to_sym => symbol

Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. See Symbol#id2name.

"Koala".intern         #=> :Koala
s = 'cat'.to_sym       #=> :cat
s == :cat              #=> true
s = '@cat'.to_sym      #=> :@cat
s == :@cat             #=> true

This can also be used to create symbols that cannot be represented using the :xxx notation.

'cat and dog'.to_sym   #=> :"cat and dog"

But for your example ...

"Book Author Title".gsub(/\s+/, "_").downcase.to_sym

should go ;)

How do I replace all the spaces with %20 in C#?

As commented on the approved story, the HttpServerUtility.UrlEncode method replaces spaces with + instead of %20. Use one of these two methods instead: Uri.EscapeUriString() or Uri.EscapeDataString()

Sample code:

HttpUtility.UrlEncode("https://mywebsite.com/api/get me this file.jpg")
//Output: "https%3a%2f%2fmywebsite.com%2fapi%2fget+me+this+file.jpg"

Uri.EscapeUriString("https://mywebsite.com/api/get me this file.jpg");
//Output: "https://mywebsite.com/api/get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get me this file.jpg");
//Output: "https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%20me%20this%20file.jpg"

//When your url has a query string:
Uri.EscapeUriString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");
//Output: "https://mywebsite.com/api/get?id=123&name=get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");    
//Output: "https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%3Fid%3D123%26name%3Dget%20me%20this%20file.jpg"

HTML for the Pause symbol in audio and video control

The ISO 7000 / IEC 60417 Symbol for Pause; Interruption is #5111B. See Media_Controls

How can I add private key to the distribution certificate?

For Developer certificate, you need to create a developer .mobileprovision profile and install add it to your XCode. In case you want to distribute the app using an adhoc distribution profile you will require AdHoc Distribution certificate and private key installed in your keychain.

If you have not created the cert, here are steps to create it. Incase it has already been created by someone in your team, ask him to share the cert and private key. If that someone is no longer in your team then you can revoke the cert from developer account and create new.

How to time Java program execution speed

Using AOP/AspectJ and @Loggable annotation from jcabi-aspects you can do it easy and compact:

@Loggable(Loggable.DEBUG)
public String getSomeResult() {
  // return some value
}

Every call to this method will be sent to SLF4J logging facility with DEBUG logging level. And every log message will include execution time.

Making text bold using attributed string in swift

Improving upon Prajeet Shrestha answer : -

You can make a generic extension for NSMutableAttributedString which involves less code. In this case I have chosen to use system font but you could adapt it so you can input the font name as a parameter.

    extension NSMutableAttributedString {

        func systemFontWith(text: String, size: CGFloat, weight: CGFloat) -> NSMutableAttributedString {
            let attributes: [String: AnyObject] = [NSFontAttributeName: UIFont.systemFont(ofSize: size, weight: weight)]
            let string = NSMutableAttributedString(string: text, attributes: attributes)
            self.append(string)
            return self
        }
    }

delete map[key] in go?

Copied from Go 1 release notes

In the old language, to delete the entry with key k from the map represented by m, one wrote the statement,

m[k] = value, false

This syntax was a peculiar special case, the only two-to-one assignment. It required passing a value (usually ignored) that is evaluated but discarded, plus a boolean that was nearly always the constant false. It did the job but was odd and a point of contention.

In Go 1, that syntax has gone; instead there is a new built-in function, delete. The call

delete(m, k)

will delete the map entry retrieved by the expression m[k]. There is no return value. Deleting a non-existent entry is a no-op.

Updating: Running go fix will convert expressions of the form m[k] = value, false into delete(m, k) when it is clear that the ignored value can be safely discarded from the program and false refers to the predefined boolean constant. The fix tool will flag other uses of the syntax for inspection by the programmer.

Understanding the grid classes ( col-sm-# and col-lg-# ) in Bootstrap 3

[UPDATE BELOW]

I took another look at the docs and it appears I overlooked a section which talks specifically about this.

The answers to my questions:

  1. Yes, they are meant to apply only to specific ranges, rather than everything above a certain width.

  2. Yes, the classes are meant to be combined.

  3. It appears that this is appropriate in certain cases but not others because the col-# classes are basically equivalent to col-xsm-# or, widths above 0px (all widths).

Other than reading the docs too quickly, I think I was confused because I came into Bootstrap 3 with a "Bootstrap 2 mentality". Specifically, I was using the (optional) responsive styles (bootstrap-responsive.css) in v2 and v3 is quite different (for the better IMO).

UPDATE for stable release:

This question was originally written when RC1 was out. They made some major changes in RC2 so for anyone reading this now, not everything mentioned above still applies.

As of when I'm currently writing this, the col-*-# classes DO seem to apply upwards. So for example, if you want an element to be 12 columns (full width) for phones, but two 6 columns (half page) for tablets and up, you would do something like this:

<div class="col-xs-12 col-sm-6"> ... //NO NEED FOR col-md-6 or col-lg-6

(They also added an additional xs break point after this question was written.)

Java: Date from unix timestamp

Date's constructor expects the timeStamp value to be in milliseconds. Multiply your timestamp's value with 1000, then pass it to the constructor.

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

How to return multiple values in one column (T-SQL)?

DECLARE @Str varchar(500)

SELECT @Str=COALESCE(@Str,'') + CAST(ID as varchar(10)) + ','
FROM dbo.fcUser

SELECT @Str

Android: Flush DNS

Perform a hard reboot of your phone. The easiest way to do this is to remove the phone's battery. Wait for at least 30 seconds, then replace the battery. The phone will reboot, and upon completing its restart will have an empty DNS cache.

Read more: How to Flush the DNS on an Android Phone | eHow.com http://www.ehow.com/how_10021288_flush-dns-android-phone.html#ixzz1gRJnmiJb

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

{"a":"\u00e1"} and {"a":"á"} are different ways to write the same JSON document; The JSON decoder will decode the unicode escape.

In php 5.4+, php's json_encode does have the JSON_UNESCAPED_UNICODE option for plain output. On older php versions, you can roll out your own JSON encoder that does not encode non-ASCII characters, or use Pear's JSON encoder and remove line 349 to 433.

ASP.NET Core - Swashbuckle not creating swagger.json file

If you have any issues in your controller to map to an unique URL you get this error.

The best way to find the cause of issue is exclude all controllers from project. Then try running the app by enabling one controller or one or more methods in a controller at a time to find the controllers/ controller method(S) which have an issue. Or you could get smart and do a binary search logic to find the disable enable multiple controller/methods to find the faulty ones.

Some of the causes is

  1. Having public methods in controller without HTTP method attributes

  2. Having multiple methods with same Http attributes which could map to same api call if you are not using "[action]" based mapping

  3. If you are using versioning make sure you have the method in all the controller versions (if using inheritance even though you use from base)

How to handle the `onKeyPress` event in ReactJS?

Late to the party, but I was trying to get this done in TypeScript and came up with this:

<div onKeyPress={(e: KeyboardEvent<HTMLDivElement>) => console.log(e.key)}

This prints the exact key pressed to the screen. So if you want to respond to all "a" presses when the div is in focus, you'd compare e.key to "a" - literally if(e.key === "a").

How to check the version before installing a package using apt-get?

OK, I found it.

apt-cache policy <package name> will show the version details.

It also shows which version is currently installed and which versions are available to install.

For example, apt-cache policy hylafax+

Curly braces in string in PHP

As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner. Remember to use double quotes (" ") as their content is parsed by PHP, because in single quotes (' ') you'll get the literal name of variable provided:

<?php

 $a = '12345';

// This works:
 echo "qwe{$a}rty"; // qwe12345rty, using braces
 echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used

// Does not work:
 echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
 echo "qwe$arty"; // qwe, because $a became $arty, which is undefined

?>

How to set value to form control in Reactive Forms in Angular

Try this.

editqueForm =  this.fb.group({
   user: [this.question.user],
   questioning: [this.question.questioning, Validators.required],
   questionType: [this.question.questionType, Validators.required],
   options: new FormArray([])
})

setValue() and patchValue()

if you want to set the value of one control, this will not work, therefor you have to set the value of both controls:

formgroup.setValue({name: ‘abc’, age: ‘25’});

It is necessary to mention all the controls inside the method. If this is not done, it will throw an error.

On the other hand patchvalue() is a lot easier on that part, let’s say you only want to assign the name as a new value:

formgroup.patchValue({name:’abc’});

Last Key in Python Dictionary

It seems like you want to do that:

dict.keys()[-1]

dict.keys() returns a list of your dictionary's keys. Once you got the list, the -1 index allows you getting the last element of a list.

Since a dictionary is unordered*, it's doesn't make sense to get the last key of your dictionary.

Perhaps you want to sort them before. It would look like that:

sorted(dict.keys())[-1]

Note:

In Python 3, the code is

list(dict)[-1]

*Update:

This is no longer the case. Dictionary keys are officially ordered as of Python 3.7 (and unofficially in 3.6).

How do I get the unix timestamp in C as an int?

An important point is to consider if you perform tasks based on difference between 2 timestamps because you will get odd behavior if you generate it with gettimeofday(), and even clock_gettime(CLOCK_REALTIME,..) at the moment where you will set the time of your system.

To prevent such problem, use clock_gettime(CLOCK_MONOTONIC_RAW, &tms) instead.

How to darken a background using CSS?

Use an :after psuedo-element:

.overlay {
    position: relative;
    transition: all 1s;
}

.overlay:after {
    content: '\A';
    position: absolute;
    width: 100%; 
    height:100%;
    top:0; 
    left:0;
    background:rgba(0,0,0,0.5);
    opacity: 1;
    transition: all 0.5s;
    -webkit-transition: all 0.5s;
    -moz-transition: all 0.5s;
}
.overlay:hover:after {
    opacity: 0;
}

Check out my pen >

http://codepen.io/craigocurtis/pen/KzXYad

AndroidStudio gradle proxy

For the new android studio 1.2 you find the gradle vm args under:

File
- Settings
  - Build, Execution, Deployment
    - Build Tools
      - Gradle

How to disable EditText in Android

try this Kotlin code,

editField.isEnabled = !editField.isEnabled

How to remove indentation from an unordered list item?

I have the same problem with a footer I'm trying to divide up. I found that this worked for me by trying few of above suggestions combined:

footer div ul {
    list-style-position: inside;
    padding-left: 0;
}

This seems to keep it to the left under my h1 and the bullet points inside the div rather than outside to the left.

XPath to fetch SQL XML value

Update

My recomendation would be to shred the XML into relations and do searches and joins on the resulted relation, in a set oriented fashion, rather than the procedural fashion of searching specific nodes in the XML. Here is a simple XML query that shreds out the nodes and attributes of interest:

select x.value(N'../../../../@stepId', N'int') as StepID
  , x.value(N'../../@id', N'int') as ComponentID
  , x.value(N'@nom',N'nvarchar(100)') as Nom
  , x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box/components/component/variables/variable') t(x)

However, if you must use an XPath that retrieves exactly the value of interest:

select x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box[@stepId=sql:variable("@stepID")]/
    components/component[@id = sql:variable("@componentID")]/
       variables/variable[@nom="Enabled"]') t(x)

If the stepID and component ID are columns, not variables, the you should use sql:column() instead of sql:variable in the XPath filters. See Binding Relational Data Inside XML Data.

And finaly if all you need is to check for existance you can use the exist() XML method:

select @x.exist(
  N'/xml/box[@stepId=sql:variable("@stepID")]/
    components/component[@id = sql:variable("@componentID")]/
      variables/variable[@nom="Enabled" and @valeur="Yes"]') 

If statement with String comparison fails

In your example you are comparing the string objects, not their content.

Your comparison should be :

if (s.equals("/quit"))

Or if s string nullity doesn't mind / or you really don't like NPEs:

if ("/quit".equals(s))

Days between two dates?

Do you mean full calendar days, or groups of 24 hours?

For simply 24 hours, assuming you're using Python's datetime, then the timedelta object already has a days property:

days = (a - b).days

For calendar days, you'll need to round a down to the nearest day, and b up to the nearest day, getting rid of the partial day on either side:

roundedA = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
roundedB = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
days = (roundedA - roundedB).days

What is std::move(), and when should it be used?

You can use move when you need to "transfer" the content of an object somewhere else, without doing a copy (i.e. the content is not duplicated, that's why it could be used on some non-copyable objects, like a unique_ptr). It's also possible for an object to take the content of a temporary object without doing a copy (and save a lot of time), with std::move.

This link really helped me out :

http://thbecker.net/articles/rvalue_references/section_01.html

I'm sorry if my answer is coming too late, but I was also looking for a good link for the std::move, and I found the links above a little bit "austere".

This puts the emphasis on r-value reference, in which context you should use them, and I think it's more detailed, that's why I wanted to share this link here.

How to format Joda-Time DateTime to only mm/dd/yyyy?

This works

String x = "22/06/2012";
String y = "25/10/2014";

String datestart = x;
String datestop = y;

//DateTimeFormatter format = DateTimeFormat.forPattern("dd/mm/yyyy");
SimpleDateFormat  format = new SimpleDateFormat("dd/mm/yyyy");

Date d1 = null;
Date d2 = null;

try {
    d1 =  format.parse(datestart);
    d2 = format.parse(datestop);

    DateTime dt1 = new DateTime(d1);
    DateTime dt2 = new DateTime(d2);

    //Period
    period = new Period (dt1,dt2);

    //calculate days
    int days = Days.daysBetween(dt1, dt2).getDays();


} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

How to see the changes in a Git commit?

First get the commit ID using,

git log #to list all

Or

git log -p -1 #last one commit id

Copy commit id.

Now we use two methods to list changes from a specific commit,

Method 1:

git diff commit_id^! #commit id something like this 1c6a6000asad012

Method 2:

git show commit_id
For example: git show 1c6a600a

What are C++ functors and their uses?

Functor can also be used to simulate defining a local function within a function. Refer to the question and another.

But a local functor can not access outside auto variables. The lambda (C++11) function is a better solution.

How to combine two or more querysets in a Django view?

DATE_FIELD_MAPPING = {
    Model1: 'date',
    Model2: 'pubdate',
}

def my_key_func(obj):
    return getattr(obj, DATE_FIELD_MAPPING[type(obj)])

And then sorted(chain(Model1.objects.all(), Model2.objects.all()), key=my_key_func)

Quoted from https://groups.google.com/forum/#!topic/django-users/6wUNuJa4jVw. See Alex Gaynor

How to enable MySQL Query Log?

To enable the query log in MAC Machine:

Open the following file:

vi /private/etc/my.cnf

Set the query log url under 'mysqld' section as follows:

[mysqld]

general_log_file=/Users/kumanan/Documents/mysql_query.log

Few machine’s are not logging query properly, So that case you can enable it from MySQL console

mysql> SET global general_log = 1;

Stop Visual Studio from mixing line endings in files

see http://editorconfig.org and https://docs.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2017

  1. If it does not exist, add a new file called .editorconfig for your project

  2. manipulate editor config to use your preferred behaviour.

I prefer spaces over tabs, and CRLF for all code files.
Here's my .editorconfig

# http://editorconfig.org
root = true

[*]
indent_style = space
indent_size = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

[*.tmpl.html]
indent_size = 4

[*.scss]
indent_size = 2 

What's the best/easiest GUI Library for Ruby?

Wxruby is a great framework, simple and clean. Try it or use glade with ruby (the simpliest option)

How does PHP 'foreach' actually work?

foreach supports iteration over three different kinds of values:

In the following, I will try to explain precisely how iteration works in different cases. By far the simplest case is Traversable objects, as for these foreach is essentially only syntax sugar for code along these lines:

foreach ($it as $k => $v) { /* ... */ }

/* translates to: */

if ($it instanceof IteratorAggregate) {
    $it = $it->getIterator();
}
for ($it->rewind(); $it->valid(); $it->next()) {
    $v = $it->current();
    $k = $it->key();
    /* ... */
}

For internal classes, actual method calls are avoided by using an internal API that essentially just mirrors the Iterator interface on the C level.

Iteration of arrays and plain objects is significantly more complicated. First of all, it should be noted that in PHP "arrays" are really ordered dictionaries and they will be traversed according to this order (which matches the insertion order as long as you didn't use something like sort). This is opposed to iterating by the natural order of the keys (how lists in other languages often work) or having no defined order at all (how dictionaries in other languages often work).

The same also applies to objects, as the object properties can be seen as another (ordered) dictionary mapping property names to their values, plus some visibility handling. In the majority of cases, the object properties are not actually stored in this rather inefficient way. However, if you start iterating over an object, the packed representation that is normally used will be converted to a real dictionary. At that point, iteration of plain objects becomes very similar to iteration of arrays (which is why I'm not discussing plain-object iteration much in here).

So far, so good. Iterating over a dictionary can't be too hard, right? The problems begin when you realize that an array/object can change during iteration. There are multiple ways this can happen:

  • If you iterate by reference using foreach ($arr as &$v) then $arr is turned into a reference and you can change it during iteration.
  • In PHP 5 the same applies even if you iterate by value, but the array was a reference beforehand: $ref =& $arr; foreach ($ref as $v)
  • Objects have by-handle passing semantics, which for most practical purposes means that they behave like references. So objects can always be changed during iteration.

The problem with allowing modifications during iteration is the case where the element you are currently on is removed. Say you use a pointer to keep track of which array element you are currently at. If this element is now freed, you are left with a dangling pointer (usually resulting in a segfault).

There are different ways of solving this issue. PHP 5 and PHP 7 differ significantly in this regard and I'll describe both behaviors in the following. The summary is that PHP 5's approach was rather dumb and lead to all kinds of weird edge-case issues, while PHP 7's more involved approach results in more predictable and consistent behavior.

As a last preliminary, it should be noted that PHP uses reference counting and copy-on-write to manage memory. This means that if you "copy" a value, you actually just reuse the old value and increment its reference count (refcount). Only once you perform some kind of modification a real copy (called a "duplication") will be done. See You're being lied to for a more extensive introduction on this topic.

PHP 5

Internal array pointer and HashPointer

Arrays in PHP 5 have one dedicated "internal array pointer" (IAP), which properly supports modifications: Whenever an element is removed, there will be a check whether the IAP points to this element. If it does, it is advanced to the next element instead.

While foreach does make use of the IAP, there is an additional complication: There is only one IAP, but one array can be part of multiple foreach loops:

// Using by-ref iteration here to make sure that it's really
// the same array in both loops and not a copy
foreach ($arr as &$v1) {
    foreach ($arr as &$v) {
        // ...
    }
}

To support two simultaneous loops with only one internal array pointer, foreach performs the following shenanigans: Before the loop body is executed, foreach will back up a pointer to the current element and its hash into a per-foreach HashPointer. After the loop body runs, the IAP will be set back to this element if it still exists. If however the element has been removed, we'll just use wherever the IAP is currently at. This scheme mostly-kinda-sort of works, but there's a lot of weird behavior you can get out of it, some of which I'll demonstrate below.

Array duplication

The IAP is a visible feature of an array (exposed through the current family of functions), as such changes to the IAP count as modifications under copy-on-write semantics. This, unfortunately, means that foreach is in many cases forced to duplicate the array it is iterating over. The precise conditions are:

  1. The array is not a reference (is_ref=0). If it's a reference, then changes to it are supposed to propagate, so it should not be duplicated.
  2. The array has refcount>1. If refcount is 1, then the array is not shared and we're free to modify it directly.

If the array is not duplicated (is_ref=0, refcount=1), then only its refcount will be incremented (*). Additionally, if foreach by reference is used, then the (potentially duplicated) array will be turned into a reference.

Consider this code as an example where duplication occurs:

function iterate($arr) {
    foreach ($arr as $v) {}
}

$outerArr = [0, 1, 2, 3, 4];
iterate($outerArr);

Here, $arr will be duplicated to prevent IAP changes on $arr from leaking to $outerArr. In terms of the conditions above, the array is not a reference (is_ref=0) and is used in two places (refcount=2). This requirement is unfortunate and an artifact of the suboptimal implementation (there is no concern of modification during iteration here, so we don't really need to use the IAP in the first place).

(*) Incrementing the refcount here sounds innocuous, but violates copy-on-write (COW) semantics: This means that we are going to modify the IAP of a refcount=2 array, while COW dictates that modifications can only be performed on refcount=1 values. This violation results in user-visible behavior change (while a COW is normally transparent) because the IAP change on the iterated array will be observable -- but only until the first non-IAP modification on the array. Instead, the three "valid" options would have been a) to always duplicate, b) do not increment the refcount and thus allowing the iterated array to be arbitrarily modified in the loop or c) don't use the IAP at all (the PHP 7 solution).

Position advancement order

There is one last implementation detail that you have to be aware of to properly understand the code samples below. The "normal" way of looping through some data structure would look something like this in pseudocode:

reset(arr);
while (get_current_data(arr, &data) == SUCCESS) {
    code();
    move_forward(arr);
}

However foreach, being a rather special snowflake, chooses to do things slightly differently:

reset(arr);
while (get_current_data(arr, &data) == SUCCESS) {
    move_forward(arr);
    code();
}

Namely, the array pointer is already moved forward before the loop body runs. This means that while the loop body is working on element $i, the IAP is already at element $i+1. This is the reason why code samples showing modification during iteration will always unset the next element, rather than the current one.

Examples: Your test cases

The three aspects described above should provide you with a mostly complete impression of the idiosyncrasies of the foreach implementation and we can move on to discuss some examples.

The behavior of your test cases is simple to explain at this point:

  • In test cases 1 and 2 $array starts off with refcount=1, so it will not be duplicated by foreach: Only the refcount is incremented. When the loop body subsequently modifies the array (which has refcount=2 at that point), the duplication will occur at that point. Foreach will continue working on an unmodified copy of $array.

  • In test case 3, once again the array is not duplicated, thus foreach will be modifying the IAP of the $array variable. At the end of the iteration, the IAP is NULL (meaning iteration has done), which each indicates by returning false.

  • In test cases 4 and 5 both each and reset are by-reference functions. The $array has a refcount=2 when it is passed to them, so it has to be duplicated. As such foreach will be working on a separate array again.

Examples: Effects of current in foreach

A good way to show the various duplication behaviors is to observe the behavior of the current() function inside a foreach loop. Consider this example:

foreach ($array as $val) {
    var_dump(current($array));
}
/* Output: 2 2 2 2 2 */

Here you should know that current() is a by-ref function (actually: prefer-ref), even though it does not modify the array. It has to be in order to play nice with all the other functions like next which are all by-ref. By-reference passing implies that the array has to be separated and thus $array and the foreach-array will be different. The reason you get 2 instead of 1 is also mentioned above: foreach advances the array pointer before running the user code, not after. So even though the code is at the first element, foreach already advanced the pointer to the second.

Now lets try a small modification:

$ref = &$array;
foreach ($array as $val) {
    var_dump(current($array));
}
/* Output: 2 3 4 5 false */

Here we have the is_ref=1 case, so the array is not copied (just like above). But now that it is a reference, the array no longer has to be duplicated when passing to the by-ref current() function. Thus current() and foreach work on the same array. You still see the off-by-one behavior though, due to the way foreach advances the pointer.

You get the same behavior when doing by-ref iteration:

foreach ($array as &$val) {
    var_dump(current($array));
}
/* Output: 2 3 4 5 false */

Here the important part is that foreach will make $array an is_ref=1 when it is iterated by reference, so basically you have the same situation as above.

Another small variation, this time we'll assign the array to another variable:

$foo = $array;
foreach ($array as $val) {
    var_dump(current($array));
}
/* Output: 1 1 1 1 1 */

Here the refcount of the $array is 2 when the loop is started, so for once we actually have to do the duplication upfront. Thus $array and the array used by foreach will be completely separate from the outset. That's why you get the position of the IAP wherever it was before the loop (in this case it was at the first position).

Examples: Modification during iteration

Trying to account for modifications during iteration is where all our foreach troubles originated, so it serves to consider some examples for this case.

Consider these nested loops over the same array (where by-ref iteration is used to make sure it really is the same one):

foreach ($array as &$v1) {
    foreach ($array as &$v2) {
        if ($v1 == 1 && $v2 == 1) {
            unset($array[1]);
        }
        echo "($v1, $v2)\n";
    }
}

// Output: (1, 1) (1, 3) (1, 4) (1, 5)

The expected part here is that (1, 2) is missing from the output because element 1 was removed. What's probably unexpected is that the outer loop stops after the first element. Why is that?

The reason behind this is the nested-loop hack described above: Before the loop body runs, the current IAP position and hash is backed up into a HashPointer. After the loop body it will be restored, but only if the element still exists, otherwise the current IAP position (whatever it may be) is used instead. In the example above this is exactly the case: The current element of the outer loop has been removed, so it will use the IAP, which has already been marked as finished by the inner loop!

Another consequence of the HashPointer backup+restore mechanism is that changes to the IAP through reset() etc. usually do not impact foreach. For example, the following code executes as if the reset() were not present at all:

$array = [1, 2, 3, 4, 5];
foreach ($array as &$value) {
    var_dump($value);
    reset($array);
}
// output: 1, 2, 3, 4, 5

The reason is that, while reset() temporarily modifies the IAP, it will be restored to the current foreach element after the loop body. To force reset() to make an effect on the loop, you have to additionally remove the current element, so that the backup/restore mechanism fails:

$array = [1, 2, 3, 4, 5];
$ref =& $array;
foreach ($array as $value) {
    var_dump($value);
    unset($array[1]);
    reset($array);
}
// output: 1, 1, 3, 4, 5

But, those examples are still sane. The real fun starts if you remember that the HashPointer restore uses a pointer to the element and its hash to determine whether it still exists. But: Hashes have collisions, and pointers can be reused! This means that, with a careful choice of array keys, we can make foreach believe that an element that has been removed still exists, so it will jump directly to it. An example:

$array = ['EzEz' => 1, 'EzFY' => 2, 'FYEz' => 3];
$ref =& $array;
foreach ($array as $value) {
    unset($array['EzFY']);
    $array['FYFY'] = 4;
    reset($array);
    var_dump($value);
}
// output: 1, 4

Here we should normally expect the output 1, 1, 3, 4 according to the previous rules. How what happens is that 'FYFY' has the same hash as the removed element 'EzFY', and the allocator happens to reuse the same memory location to store the element. So foreach ends up directly jumping to the newly inserted element, thus short-cutting the loop.

Substituting the iterated entity during the loop

One last odd case that I'd like to mention, it is that PHP allows you to substitute the iterated entity during the loop. So you can start iterating on one array and then replace it with another array halfway through. Or start iterating on an array and then replace it with an object:

$arr = [1, 2, 3, 4, 5];
$obj = (object) [6, 7, 8, 9, 10];

$ref =& $arr;
foreach ($ref as $val) {
    echo "$val\n";
    if ($val == 3) {
        $ref = $obj;
    }
}
/* Output: 1 2 3 6 7 8 9 10 */

As you can see in this case PHP will just start iterating the other entity from the start once the substitution has happened.

PHP 7

Hashtable iterators

If you still remember, the main problem with array iteration was how to handle removal of elements mid-iteration. PHP 5 used a single internal array pointer (IAP) for this purpose, which was somewhat suboptimal, as one array pointer had to be stretched to support multiple simultaneous foreach loops and interaction with reset() etc. on top of that.

PHP 7 uses a different approach, namely, it supports creating an arbitrary amount of external, safe hashtable iterators. These iterators have to be registered in the array, from which point on they have the same semantics as the IAP: If an array element is removed, all hashtable iterators pointing to that element will be advanced to the next element.

This means that foreach will no longer use the IAP at all. The foreach loop will be absolutely no effect on the results of current() etc. and its own behavior will never be influenced by functions like reset() etc.

Array duplication

Another important change between PHP 5 and PHP 7 relates to array duplication. Now that the IAP is no longer used, by-value array iteration will only do a refcount increment (instead of duplication the array) in all cases. If the array is modified during the foreach loop, at that point a duplication will occur (according to copy-on-write) and foreach will keep working on the old array.

In most cases, this change is transparent and has no other effect than better performance. However, there is one occasion where it results in different behavior, namely the case where the array was a reference beforehand:

$array = [1, 2, 3, 4, 5];
$ref = &$array;
foreach ($array as $val) {
    var_dump($val);
    $array[2] = 0;
}
/* Old output: 1, 2, 0, 4, 5 */
/* New output: 1, 2, 3, 4, 5 */

Previously by-value iteration of reference-arrays was special cases. In this case, no duplication occurred, so all modifications of the array during iteration would be reflected by the loop. In PHP 7 this special case is gone: A by-value iteration of an array will always keep working on the original elements, disregarding any modifications during the loop.

This, of course, does not apply to by-reference iteration. If you iterate by-reference all modifications will be reflected by the loop. Interestingly, the same is true for by-value iteration of plain objects:

$obj = new stdClass;
$obj->foo = 1;
$obj->bar = 2;
foreach ($obj as $val) {
    var_dump($val);
    $obj->bar = 42;
}
/* Old and new output: 1, 42 */

This reflects the by-handle semantics of objects (i.e. they behave reference-like even in by-value contexts).

Examples

Let's consider a few examples, starting with your test cases:

  • Test cases 1 and 2 retain the same output: By-value array iteration always keep working on the original elements. (In this case, even refcounting and duplication behavior is exactly the same between PHP 5 and PHP 7).

  • Test case 3 changes: Foreach no longer uses the IAP, so each() is not affected by the loop. It will have the same output before and after.

  • Test cases 4 and 5 stay the same: each() and reset() will duplicate the array before changing the IAP, while foreach still uses the original array. (Not that the IAP change would have mattered, even if the array was shared.)

The second set of examples was related to the behavior of current() under different reference/refcounting configurations. This no longer makes sense, as current() is completely unaffected by the loop, so its return value always stays the same.

However, we get some interesting changes when considering modifications during iteration. I hope you will find the new behavior saner. The first example:

$array = [1, 2, 3, 4, 5];
foreach ($array as &$v1) {
    foreach ($array as &$v2) {
        if ($v1 == 1 && $v2 == 1) {
            unset($array[1]);
        }
        echo "($v1, $v2)\n";
    }
}

// Old output: (1, 1) (1, 3) (1, 4) (1, 5)
// New output: (1, 1) (1, 3) (1, 4) (1, 5)
//             (3, 1) (3, 3) (3, 4) (3, 5)
//             (4, 1) (4, 3) (4, 4) (4, 5)
//             (5, 1) (5, 3) (5, 4) (5, 5) 

As you can see, the outer loop no longer aborts after the first iteration. The reason is that both loops now have entirely separate hashtable iterators, and there is no longer any cross-contamination of both loops through a shared IAP.

Another weird edge case that is fixed now, is the odd effect you get when you remove and add elements that happen to have the same hash:

$array = ['EzEz' => 1, 'EzFY' => 2, 'FYEz' => 3];
foreach ($array as &$value) {
    unset($array['EzFY']);
    $array['FYFY'] = 4;
    var_dump($value);
}
// Old output: 1, 4
// New output: 1, 3, 4

Previously the HashPointer restore mechanism jumped right to the new element because it "looked" like it's the same as the removed element (due to colliding hash and pointer). As we no longer rely on the element hash for anything, this is no longer an issue.

JQuery How to extract value from href tag?

I see two options here

var link = $('a').attr('href');
var equalPosition = link.indexOf('='); //Get the position of '='
var number = link.substring(equalPosition + 1); //Split the string and get the number.

I dont know if you're gonna use it for paging and have the text in the <a>-tag as you have it, but if you should you can also do

var number = $('a').text();

Convert to/from DateTime and Time in Ruby

While making such conversions one should take into consideration the behavior of timezones while converting from one object to the other. I found some good notes and examples in this stackoverflow post.

How do I concatenate strings in Swift?

You can now use stringByAppendingString in Swift.

var string = "Swift"
var resultString = string.stringByAppendingString(" is new Programming Language")

equivalent to push() or pop() for arrays?

You can use Arrays.copyOf() with a little reflection to make a nice helper function.

public class ArrayHelper {
    public static <T> T[] push(T[] arr, T item) {
        T[] tmp = Arrays.copyOf(arr, arr.length + 1);
        tmp[tmp.length - 1] = item;
        return tmp;
    }

    public static <T> T[] pop(T[] arr) {
        T[] tmp = Arrays.copyOf(arr, arr.length - 1);
        return tmp;
    }
}

Usage:

String[] items = new String[]{"a", "b", "c"};

items = ArrayHelper.push(items, "d");
items = ArrayHelper.push(items, "e");

items = ArrayHelper.pop(items);

Results

Original: a,b,c

Array after push calls: a,b,c,d,e

Array after pop call: a,b,c,d

The object 'DF__*' is dependent on column '*' - Changing int to double

When we try to drop a column which is depended upon then we see this kind of error:

The object 'DF__*' is dependent on column ''.

drop the constraint which is dependent on that column with:

ALTER TABLE TableName DROP CONSTRAINT dependent_constraint;

Example:

Msg 5074, Level 16, State 1, Line 1

The object 'DF__Employees__Colf__1273C1CD' is dependent on column 'Colf'.

Msg 4922, Level 16, State 9, Line 1

ALTER TABLE DROP COLUMN Colf failed because one or more objects access this column.

Drop Constraint(DF__Employees__Colf__1273C1CD):

ALTER TABLE Employees DROP CONSTRAINT DF__Employees__Colf__1273C1CD;

Then you can Drop Column:

Alter Table TableName Drop column ColumnName

Reference - What does this regex mean?

The Stack Overflow Regular Expressions FAQ

See also a lot of general hints and useful links at the tag details page.


Online tutorials

Quantifiers

Character Classes

Escape Sequences

Anchors

(Also see "Flavor-Specific Information ? Java ? The functions in Matcher")

Groups

Lookarounds

Modifiers

Other:

Common Tasks

Advanced Regex-Fu

Flavor-Specific Information

(Except for those marked with *, this section contains non-Stack Overflow links.)

General information

(Links marked with * are non-Stack Overflow links.)

Examples of regex that can cause regex engine to fail

Tools: Testers and Explainers

(This section contains non-Stack Overflow links.)

Easy way to convert a unicode list to a list containing python strings?

[str(x) for x in EmployeeList] would do a conversion, but it would fail if the unicode string characters do not lie in the ascii range.

>>> EmployeeList = [u'1001', u'Karick', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
['1001', 'Karick', '14-12-2020', '1$']


>>> EmployeeList = [u'1001', u'????', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

display: inline-block extra margin

You can get a vertical space even though you have NO WHITESPACE whatsoever between your inline-block elements.

For me, this was caused by line-height. The simple fix was:

div.container {
    line-height: 0;
}
div.container > * {
    line-height: normal;
}