Programs & Examples On #Build agent

How to call a MySQL stored procedure from within PHP code?

You can call a stored procedure using the following syntax:

$result = mysql_query('CALL getNodeChildren(2)');

Registering for Push Notifications in Xcode 8/Swift 3.0?

Simply do the following in didFinishWithLaunching::

if #available(iOS 10.0, *) {

    let center = UNUserNotificationCenter.current()

    center.delegate = self
    center.requestAuthorization(options: []) { _, _ in
        application.registerForRemoteNotifications()
    }
}

Remember about import statement:

import UserNotifications

Python: Get relative path from comparing two absolute paths

os.path.commonprefix() and os.path.relpath() are your friends:

>>> print os.path.commonprefix(['/usr/var/log', '/usr/var/security'])
'/usr/var'
>>> print os.path.commonprefix(['/tmp', '/usr/var'])  # No common prefix: the root is the common prefix
'/'

You can thus test whether the common prefix is one of the paths, i.e. if one of the paths is a common ancestor:

paths = […, …, …]
common_prefix = os.path.commonprefix(list_of_paths)
if common_prefix in paths:
    …

You can then find the relative paths:

relative_paths = [os.path.relpath(path, common_prefix) for path in paths]

You can even handle more than two paths, with this method, and test whether all the paths are all below one of them.

PS: depending on how your paths look like, you might want to perform some normalization first (this is useful in situations where one does not know whether they always end with '/' or not, or if some of the paths are relative). Relevant functions include os.path.abspath() and os.path.normpath().

PPS: as Peter Briggs mentioned in the comments, the simple approach described above can fail:

>>> os.path.commonprefix(['/usr/var', '/usr/var2/log'])
'/usr/var'

even though /usr/var is not a common prefix of the paths. Forcing all paths to end with '/' before calling commonprefix() solves this (specific) problem.

PPPS: as bluenote10 mentioned, adding a slash does not solve the general problem. Here is his followup question: How to circumvent the fallacy of Python's os.path.commonprefix?

PPPPS: starting with Python 3.4, we have pathlib, a module that provides a saner path manipulation environment. I guess that the common prefix of a set of paths can be obtained by getting all the prefixes of each path (with PurePath.parents()), taking the intersection of all these parent sets, and selecting the longest common prefix.

PPPPPS: Python 3.5 introduced a proper solution to this question: os.path.commonpath(), which returns a valid path.

Get program execution time in the shell

#!/bin/bash
START=$(date +%s)
# do something
# start your script work here
ls -R /etc > /tmp/x
rm -f /tmp/x
# your logic ends here
END=$(date +%s)
DIFF=$(( $END - $START ))
echo "It took $DIFF seconds"

How to easily initialize a list of Tuples?

Super Duper Old I know but I would add my piece on using Linq and continuation lambdas on methods with using C# 7. I try to use named tuples as replacements for DTOs and anonymous projections when reused in a class. Yes for mocking and testing you still need classes but doing things inline and passing around in a class is nice to have this newer option IMHO. You can instantiate them from

  1. Direct Instantiation
var items = new List<(int Id, string Name)> { (1, "Me"), (2, "You")};
  1. Off of an existing collection, and now you can return well typed tuples similar to how anonymous projections used to be done.
public class Hold
{
    public int Id { get; set; }
    public string Name { get; set; }
}

//In some method or main console app:
var holds = new List<Hold> { new Hold { Id = 1, Name = "Me" }, new Hold { Id = 2, Name = "You" } };
var anonymousProjections = holds.Select(x => new { SomeNewId = x.Id, SomeNewName = x.Name });
var namedTuples = holds.Select(x => (TupleId: x.Id, TupleName: x.Name));
  1. Reuse the tuples later with grouping methods or use a method to construct them inline in other logic:
//Assuming holder class above making 'holds' object
public (int Id, string Name) ReturnNamedTuple(int id, string name) => (id, name);
public static List<(int Id, string Name)> ReturnNamedTuplesFromHolder(List<Hold> holds) => holds.Select(x => (x.Id, x.Name)).ToList();
public static void DoSomethingWithNamedTuplesInput(List<(int id, string name)> inputs) => inputs.ForEach(x => Console.WriteLine($"Doing work with {x.id} for {x.name}"));

var namedTuples2 = holds.Select(x => ReturnNamedTuple(x.Id, x.Name));
var namedTuples3 = ReturnNamedTuplesFromHolder(holds);
DoSomethingWithNamedTuplesInput(namedTuples.ToList());

Adding rows dynamically with jQuery

As an addition to answers above: you probably might need to change ids in names/ids of input elements (pls note, you should not have digits in fields name):

<input name="someStuff.entry[2].fieldOne" id="someStuff_fdf_fieldOne_2" ..>

I have done this having some global variable by default set to 0:

var globalNewIndex = 0;

and in the add function after you've cloned and resetted the values in the new row:

                var newIndex = globalNewIndex+1;
                var changeIds = function(i, val) {
                    return val.replace(globalNewIndex,newIndex);
                }
                $('#mytable tbody>tr:last input').attr('name', changeIds ).attr('id', changeIds );
                globalNewIndex++;

Where does Internet Explorer store saved passwords?

Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.

Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.

You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.

To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.

A typical C++ code will be:

hVaultLib = LoadLibrary(L"vaultcli.dll");

if (hVaultLib != NULL) 
{
    pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
    pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
    pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
    pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
    pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");

    bStatus = (pVaultEnumerateVaults != NULL)
        && (pVaultFree != NULL)
        && (pVaultGetItemW7 != NULL)
        && (pVaultGetItemW8 != NULL)
        && (pVaultOpenVault != NULL)
        && (pVaultCloseVault != NULL)
        && (pVaultEnumerateItems != NULL);
}

Then you enumerate all stored credentials by calling

VaultEnumerateVaults

Then you go over the results.

Allow a div to cover the whole page instead of the area within the container

#dimScreen{
 position:fixed;
 top:0px;
 left:0px;
 width:100%;
 height:100%;
}

Force unmount of NFS-mounted directory

Your NFS server disappeared.

Ideally your best bet is if the NFS server comes back.

If not, the "umount -f" should have done the trick. It doesn't ALWAYS work, but it often will.

If you happen to know what processes are USING the NFS filesystem, you could try killing those processes and then maybe an unmount would work.

Finally, I'd guess you need to reboot.

Also, DON'T soft-mount your NFS drives. You use hard-mounts to guarantee that they worked. That's necessary if you're doing writes.

How to select rows with NaN in particular column?

@qbzenker provided the most idiomatic method IMO

Here are a few alternatives:

In [28]: df.query('Col2 != Col2') # Using the fact that: np.nan != np.nan
Out[28]:
   Col1  Col2  Col3
1     0   NaN   0.0

In [29]: df[np.isnan(df.Col2)]
Out[29]:
   Col1  Col2  Col3
1     0   NaN   0.0

Jquery check if element is visible in viewport

According to the documentation for that plugin, .visible() returns a boolean indicating if the element is visible. So you'd use it like this:

if ($('#element').visible(true)) {
    // The element is visible, do something
} else {
    // The element is NOT visible, do something else
}

Python if not == vs if !=

In the first one Python has to execute one more operations than necessary(instead of just checking not equal to it has to check if it is not true that it is equal, thus one more operation). It would be impossible to tell the difference from one execution, but if run many times, the second would be more efficient. Overall I would use the second one, but mathematically they are the same

Remove HTML tags from string including &nbsp in C#

I've been using this function for a while. Removes pretty much any messy html you can throw at it and leaves the text intact.

        private static readonly Regex _tags_ = new Regex(@"<[^>]+?>", RegexOptions.Multiline | RegexOptions.Compiled);

        //add characters that are should not be removed to this regex
        private static readonly Regex _notOkCharacter_ = new Regex(@"[^\w;&#@.:/\\?=|%!() -]", RegexOptions.Compiled);

        public static String UnHtml(String html)
        {
            html = HttpUtility.UrlDecode(html);
            html = HttpUtility.HtmlDecode(html);

            html = RemoveTag(html, "<!--", "-->");
            html = RemoveTag(html, "<script", "</script>");
            html = RemoveTag(html, "<style", "</style>");

            //replace matches of these regexes with space
            html = _tags_.Replace(html, " ");
            html = _notOkCharacter_.Replace(html, " ");
            html = SingleSpacedTrim(html);

            return html;
        }

        private static String RemoveTag(String html, String startTag, String endTag)
        {
            Boolean bAgain;
            do
            {
                bAgain = false;
                Int32 startTagPos = html.IndexOf(startTag, 0, StringComparison.CurrentCultureIgnoreCase);
                if (startTagPos < 0)
                    continue;
                Int32 endTagPos = html.IndexOf(endTag, startTagPos + 1, StringComparison.CurrentCultureIgnoreCase);
                if (endTagPos <= startTagPos)
                    continue;
                html = html.Remove(startTagPos, endTagPos - startTagPos + endTag.Length);
                bAgain = true;
            } while (bAgain);
            return html;
        }

        private static String SingleSpacedTrim(String inString)
        {
            StringBuilder sb = new StringBuilder();
            Boolean inBlanks = false;
            foreach (Char c in inString)
            {
                switch (c)
                {
                    case '\r':
                    case '\n':
                    case '\t':
                    case ' ':
                        if (!inBlanks)
                        {
                            inBlanks = true;
                            sb.Append(' ');
                        }   
                        continue;
                    default:
                        inBlanks = false;
                        sb.Append(c);
                        break;
                }
            }
            return sb.ToString().Trim();
        }

Find the number of columns in a table

Can get using following sql statement:

select count(*) Noofcolumns from SYSCOLUMNS where id=(select id from SYSOBJECTS where name='table_name')

How to add a reference programmatically

Here is how to get the Guid's programmatically! You can then use these guids/filepaths with an above answer to add the reference!

Reference: http://www.vbaexpress.com/kb/getarticle.php?kb_id=278

Sub ListReferencePaths()
'Lists path and GUID (Globally Unique Identifier) for each referenced library.
'Select a reference in Tools > References, then run this code to get GUID etc.
    Dim rw As Long, ref
    With ThisWorkbook.Sheets(1)
        .Cells.Clear
        rw = 1
        .Range("A" & rw & ":D" & rw) = Array("Reference","Version","GUID","Path")
        For Each ref In ThisWorkbook.VBProject.References
            rw = rw + 1
            .Range("A" & rw & ":D" & rw) = Array(ref.Description, _
                   "v." & ref.Major & "." & ref.Minor, ref.GUID, ref.FullPath)
        Next ref
        .Range("A:D").Columns.AutoFit
    End With
End Sub

Here is the same code but printing to the terminal if you don't want to dedicate a worksheet to the output.

Sub ListReferencePaths() 
 'Macro purpose:  To determine full path and Globally Unique Identifier (GUID)
 'to each referenced library.  Select the reference in the Tools\References
 'window, then run this code to get the information on the reference's library

On Error Resume Next 
Dim i As Long 

Debug.Print "Reference name" & " | " & "Full path to reference" & " | " & "Reference GUID" 

For i = 1 To ThisWorkbook.VBProject.References.Count 
  With ThisWorkbook.VBProject.References(i) 
    Debug.Print .Name & " | " & .FullPath  & " | " & .GUID 
  End With 
Next i 
On Error GoTo 0 
End Sub 

How to find all trigger associated with a table with SQL Server?

find triggers on table:

select so.name, text
from sysobjects so, syscomments sc
where type = 'TR'
and so.id = sc.id
and text like '%TableName%'

and you can find store procedure which has reference of table:

SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%yourtablename%'

C-like structures in Python

Whenever I need an "instant data object that also behaves like a dictionary" (I don't think of C structs!), I think of this cute hack:

class Map(dict):
    def __init__(self, **kwargs):
        super(Map, self).__init__(**kwargs)
        self.__dict__ = self

Now you can just say:

struct = Map(field1='foo', field2='bar', field3=42)

self.assertEquals('bar', struct.field2)
self.assertEquals(42, struct['field3'])

Perfectly handy for those times when you need a "data bag that's NOT a class", and for when namedtuples are incomprehensible...

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

DateTime.MinValue and DateTime.MaxValue

DateTime.MinValue = 1/1/0001 12:00:00 AM

DateTime.MaxValue = 23:59:59.9999999, December 31, 9999, 

                exactly one 100-nanosecond tick 

                before 00:00:00, January 1, 10000 

How do you get current active/default Environment profile programmatically in Spring?

And if you neither want to use @Autowire nor injecting @Value you can simply do (with fallback included):

System.getProperty("spring.profiles.active", "unknown");

This will return any active profile (or fallback to 'unknown').

How do you disable browser Autocomplete on web form field / input tag?

You may use in input.

For example;

<input type=text name="test" autocomplete="off" />

How can I upload files asynchronously?

Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, http://jquery.malsup.com/form/.

Example

var $bar   = $('.ProgressBar');
$('.Form').ajaxForm({
  dataType: 'json',

  beforeSend: function(xhr) {
    var percentVal = '0%';
    $bar.width(percentVal);
  },

  uploadProgress: function(event, position, total, percentComplete) {
    var percentVal = percentComplete + '%';
    $bar.width(percentVal)
  },

  success: function(response) {
    // Response
  }
});

I hope it would be helpful

Long press on UITableView

First add the long press gesture recognizer to the table view:

UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] 
  initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 2.0; //seconds
lpgr.delegate = self;
[self.myTableView addGestureRecognizer:lpgr];
[lpgr release];

Then in the gesture handler:

-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
    CGPoint p = [gestureRecognizer locationInView:self.myTableView];

    NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:p];
    if (indexPath == nil) {
        NSLog(@"long press on table view but not on a row");
    } else if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        NSLog(@"long press on table view at row %ld", indexPath.row);
    } else {
        NSLog(@"gestureRecognizer.state = %ld", gestureRecognizer.state);
    }
}

You have to be careful with this so that it doesn't interfere with the user's normal tapping of the cell and also note that handleLongPress may fire multiple times (this will be due to the gesture recognizer state changes).

How do I download a package from apt-get without installing it?

Don't forget the option "-o", which lets you download anywhere you want, although you have to create "archives", "lock" and "partial" first (the command prints what's needed).

apt-get install -d -o=dir::cache=/tmp whateveryouwant

The application has stopped unexpectedly: How to Debug?

  1. From the Home screen, press the Menu key.
  2. List item
  3. Touch Settings.
  4. Touch Applications.
  5. Touch Manage Applications.
  6. Touch All.
  7. Select the application that is having issues.
  8. Touch Clear data and Clear cache if they are available. This resets the app as if it was new, and may delete personal data stored in the app.

How to get box-shadow on left & right sides only

Classical approach: Negative spread

CSS box-shadow uses 4 parameters: h-shadow, v-shadow, blur, spread:

box-shadow: 10px 0 8px -8px black;

The v-shadow (verical shadow) is set to 0.

The blur parameter adds the gradient effect, but adds also a little shadow on vertical borders (the one we want to get rid of).

Negative spread reduces the shadow on all borders: you can play with it trying to remove that little vertical shadow without affecting too much the one obn the sides (it's easier for small shadows, 5 to 10px.)

Here a fiddle example.


Second approach: Absolute div on the side

Add an empty div in your element, and style it with absolute positioning so it doesen't affect the element content.

Here the fiddle with an example of left-shadow.

<div id="container">
  <div class="shadow"></div>
</div>

.shadow{
    position:absolute;
    height: 100%;
    width: 4px;
    left:0px;
    top:0px;
    box-shadow: -4px 0 3px black;
}

Third: Masking shadow

If you have a fixed background, you can hide the side-shadow effect with two masking shadows having the same color of the background and blur = 0, example:

box-shadow: 
    0 -6px white,          // Top Masking Shadow
    0 6px white,           // Bottom Masking Shadow
    7px 0 4px -3px black,  // Left-shadow
    -7px 0 4px -3px black; // Right-shadow

I've added again a negative spread (-3px) to the black shadow, so it doesn't stretch beyond the corners.

Here the fiddle.

SQL, Postgres OIDs, What are they and why are they useful?

OIDs being phased out

The core team responsible for Postgres is gradually phasing out OIDs.

Postgres 12 removes special behavior of OID columns

The use of OID as an optional system column on your tables is now removed from Postgres 12. You can no longer use:

  • CREATE TABLE … WITH OIDS command
  • default_with_oids (boolean) compatibility setting

The data type OID remains in Postgres 12. You can explicitly create a column of the type OID.

After migrating to Postgres 12, any optionally-defined system column oid will no longer be invisible by default. Performing a SELECT * will now include this column. Note that this extra “surprise” column may break naïvely written SQL code.

Convert array values from string to int?

This is almost 3 times faster than explode(), array_map() and intval():

$integerIDs = json_decode('[' . $string . ']', true);

How can I replace every occurrence of a String in a file with PowerShell?

This is what I use, but it is slow on large text files.

get-content $pathToFile | % { $_ -replace $stringToReplace, $replaceWith } | set-content $pathToFile

If you are going to be replacing strings in large text files and speed is a concern, look into using System.IO.StreamReader and System.IO.StreamWriter.

try
{
   $reader = [System.IO.StreamReader] $pathToFile
   $data = $reader.ReadToEnd()
   $reader.close()
}
finally
{
   if ($reader -ne $null)
   {
       $reader.dispose()
   }
}

$data = $data -replace $stringToReplace, $replaceWith

try
{
   $writer = [System.IO.StreamWriter] $pathToFile
   $writer.write($data)
   $writer.close()
}
finally
{
   if ($writer -ne $null)
   {
       $writer.dispose()
   }
}

(The code above has not been tested.)

There is probably a more elegant way to use StreamReader and StreamWriter for replacing text in a document, but that should give you a good starting point.

using stored procedure in entity framework

You can call a stored procedure using SqlQuery (See here)

// Prepare the query
var query = context.Functions.SqlQuery(
    "EXEC [dbo].[GetFunctionByID] @p1", 
    new SqlParameter("p1", 200));

// add NoTracking() if required

// Fetch the results
var result = query.ToList();

How do I change the root directory of an Apache server?

In case you are using Ubuntu 16.04 (Xenial Xerus), please update the 000-default.conf file in the directory /etc/apache2/sites-available.

Here ?

ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/YourFolder

Interview question: Check if one string is a rotation of other string

A pure Java answer (sans null checks)

private boolean isRotation(String s1,String s2){
    if(s1.length() != s2.length()) return false;
    for(int i=0; i < s1.length()-1; i++){
        s1 = new StringBuilder(s1.substring(1)).append(s1.charAt(0)).toString();
        //--or-- s1 = s1.substring(1) + s1.charAt(0)
        if(s1.equals(s2)) return true;
    }
    return false;
}

HTML button opening link in new tab

Try this

window.open(urlValue, "_system", "location=yes");

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

I found to many long and confusing answer and after reading few of the answers My conclusion is

if (!ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_EXTERNAL_STORAGE))
                Toast.makeText(this, "permanently denied", Toast.LENGTH_SHORT).show();

How to add and get Header values in WebApi

For .net Core in GET method, you can do like this:

 StringValues value1;
 string DeviceId = string.Empty;

  if (Request.Headers.TryGetValue("param1", out value1))
      {
                DeviceId = value1.FirstOrDefault();
      }

How to remove the arrows from input[type="number"] in Opera

There is no way.

This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.

If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.

For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}"> could be adequate. It is of course implementation-dependent how it will be handled.

How do I create a message box with "Yes", "No" choices and a DialogResult?

Use:

MessageBoxResult m = MessageBox.Show("The file will be saved here.", "File Save", MessageBoxButton.OKCancel);
if(m == m.Yes)
{
    // Do something
}
else if (m == m.No)
{
    // Do something else
}

MessageBoxResult is used on Windows Phone instead of DialogResult...

Differences between time complexity and space complexity?

The way in which the amount of storage space required by an algorithm varies with the size of the problem it is solving. Space complexity is normally expressed as an order of magnitude, e.g. O(N^2) means that if the size of the problem (N) doubles then four times as much working storage will be needed.

PHP Get Site URL Protocol - http vs https

$protocal = 'http';
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || $_SERVER['HTTPS'] == 'on') {$protocal = 'https';}


echo $protocal;

Could not find main class HelloWorld

You are not setting a classpath that includes your compiled class! java can't find any classes if you don't tell it where to look.

java -cp [compiler outpur dir] HelloWorld

Incidentally you do not need to set CLASSPATH the way you have done.

Printf long long int in C with GCC?

You can try settings of code::block, there is a complier..., then you select in C mode.

enter image description here

What's the difference between 'r+' and 'a+' when open file in python?

One difference is for r+ if the files does not exist, it'll not be created and open fails. But in case of a+ the file will be created if it does not exist.

How to comment multiple lines with space or indent

One way to do it would be:

  1. Select the text, Press CTRL + K, C to comment (CTRL+E+C )
  2. Move the cursor to the first line after the delimiter // and before the Code text.
  3. Press Alt + Shift and use arrow keys to make selection. (Remember to make line selection(using down, up arrow keys), not the text selection - See Box Selection and Multi line editing)
  4. Once the selection is done, press space bar to enter a single space.

Notice the vertical blue line in the below image( that will appear once the selection is made, then you can insert any number of characters in between them)

enter image description here

I couldn't find a direct way to do that. The interesting thing is that it is mentioned in the C# Coding Conventions (C# Programming Guide) under Commenting Conventions.

Insert one space between the comment delimiter (//) and the comment text

But the default implementation of commenting in visual studio doesn't insert any space

What is the iOS 5.0 user agent string?

iPhone:

Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

iPad:

Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

Changing Locale within the app itself

If you want to effect on the menu options for changing the locale immediately.You have to do like this.

//onCreate method calls only once when menu is called first time.
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //1.Here you can add your  locale settings . 
    //2.Your menu declaration.
}
//This method is called when your menu is opend to again....
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    menu.clear();
    onCreateOptionsMenu(menu);
    return super.onMenuOpened(featureId, menu);
}

Calling C/C++ from Python?

The quickest way to do this is using SWIG.

Example from SWIG tutorial:

/* File : example.c */
int fact(int n) {
    if (n <= 1) return 1;
    else return n*fact(n-1);
}

Interface file:

/* example.i */
%module example
%{
/* Put header files here or function declarations like below */
extern int fact(int n);
%}

extern int fact(int n);

Building a Python module on Unix:

swig -python example.i
gcc -fPIC -c example.c example_wrap.c -I/usr/local/include/python2.7
gcc -shared example.o example_wrap.o -o _example.so

Usage:

>>> import example
>>> example.fact(5)
120

Note that you have to have python-dev. Also in some systems python header files will be in /usr/include/python2.7 based on the way you have installed it.

From the tutorial:

SWIG is a fairly complete C++ compiler with support for nearly every language feature. This includes preprocessing, pointers, classes, inheritance, and even C++ templates. SWIG can also be used to package structures and classes into proxy classes in the target language — exposing the underlying functionality in a very natural manner.

How to find the foreach index?

These two loops are equivalent (bar the safety railings of course):

for ($i=0; $i<count($things); $i++) { ... }

foreach ($things as $i=>$thing) { ... }

eg

for ($i=0; $i<count($things); $i++) {
    echo "Thing ".$i." is ".$things[$i];
}

foreach ($things as $i=>$thing) {
    echo "Thing ".$i." is ".$thing;
}

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

Yes, LINQ to Objects supports this with Enumerable.Concat:

var together = first.Concat(second);

NB: Should first or second be null you would receive a ArgumentNullException. To avoid this & treat nulls as you would an empty set, use the null coalescing operator like so:

var together = (first ?? Enumerable.Empty<string>()).Concat(second ?? Enumerable.Empty<string>()); //amending `<string>` to the appropriate type

Include CSS and Javascript in my django template

Read this https://docs.djangoproject.com/en/dev/howto/static-files/:

For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.

And try:

~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp

Then add 'myapp' to INSTALLED_APPS (myprj/settings.py).

~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html

Edit myprj/urls.py:

from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView

class HelloView(TemplateView):
    template_name = "hello.html"

urlpatterns = patterns('',
    url(r'^$', HelloView.as_view(), name='hello'),
)

And run it:

~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver

It works!

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

/*Maximum value that can be entered is 2,147,483,647
 * Program to convert entered number into string
 * */
import java.util.Scanner;

public class NumberToWords 
{

public static void main(String[] args) 
{
    double num;//for taking input number
    Scanner obj=new Scanner(System.in);
    do
    {
        System.out.println("\n\nEnter the Number (Maximum value that can be entered is 2,147,483,647)");
        num=obj.nextDouble();
        if(num<=2147483647)//checking if entered number exceeds maximum integer value
        {
            int number=(int)num;//type casting double number to integer number
            splitNumber(number);//calling splitNumber-it will split complete number in pairs of 3 digits
        }
        else
            System.out.println("Enter smaller value");//asking user to enter a smaller value compared to 2,147,483,647
    }while(num>2147483647);
}
//function to split complete number into pair of 3 digits each
public static void splitNumber(int number)
{   //splitNumber array-contains the numbers in pair of 3 digits
    int splitNumber[]=new int[4],temp=number,i=0,index;
    //splitting number into pair of 3
    if(temp==0)
        System.out.println("zero");
    while(temp!=0)
    {
        splitNumber[i++]=temp%1000;
        temp/=1000;
    }
    //passing each pair of 3 digits to another function
    for(int j=i-1;j>-1;j--)
    {   //toWords function will split pair of 3 digits to separate digits
        if(splitNumber[j]!=0)
            {toWords(splitNumber[j]);
        if(j==3)//if the number contained more than 9 digits
            System.out.print("billion,");
        else if(j==2)//if the number contained more than 6 digits & less than 10 digits
            System.out.print("million,");
        else if(j==1)
            System.out.print("thousand,");//if the number contained more than 3 digits & less than 7 digits
            }
            }       
}
//function that splits number into individual digits
public static void toWords(int number)
    //splitSmallNumber array contains individual digits of number passed to this function
{   int splitSmallNumber[]=new int[3],i=0,j;
    int temp=number;//making temporary copy of the number
    //logic to split number into its constituent digits

    while(temp!=0)
    {
        splitSmallNumber[i++]=temp%10;
        temp/=10;
    }
    //printing words for each digit
    for(j=i-1;j>-1;j--)
      //{   if the digit is greater than zero
        if(splitSmallNumber[j]>=0)
            //if the digit is at 3rd place or if digit is at (1st place with digit at 2nd place not equal to zero)
        {   if(j==2||(j==0 && (splitSmallNumber[1]!=1)))
            {
                switch(splitSmallNumber[j])
                {

                    case 1:System.out.print("one ");break;
                    case 2:System.out.print("two ");break;
                    case 3:System.out.print("three ");break;
                    case 4:System.out.print("four ");break;
                    case 5:System.out.print("five ");break;
                    case 6:System.out.print("six ");break;
                    case 7:System.out.print("seven ");break;
                    case 8:System.out.print("eight ");break;
                    case 9:System.out.print("nine ");break;

            }

        }
        //if digit is at 2nd place
        if(j==1)
        {       //if digit at 2nd place is 0 or 1
                if(((splitSmallNumber[j]==0)||(splitSmallNumber[j]==1))&& splitSmallNumber[2]!=0 )
                System.out.print("hundred ");
            switch(splitSmallNumber[1])
            {   case 1://if digit at 2nd place is 1 example-213
                        switch(splitSmallNumber[0])
                        {
                        case 1:System.out.print("eleven ");break;
                        case 2:System.out.print("twelve ");break;
                        case 3:System.out.print("thirteen ");break;
                        case 4:System.out.print("fourteen ");break;
                        case 5:System.out.print("fifteen ");break;
                        case 6:System.out.print("sixteen ");break;
                        case 7:System.out.print("seventeen ");break;
                        case 8:System.out.print("eighteen ");break;
                        case 9:System.out.print("nineteen ");break;
                        case 0:System.out.print("ten ");break;
                        }break;
                        //if digit at 2nd place is not 1
                    case 2:System.out.print("twenty ");break;
                    case 3:System.out.print("thirty ");break;
                    case 4:System.out.print("forty ");break;
                    case 5:System.out.print("fifty ");break;
                    case 6:System.out.print("sixty ");break;
                    case 7:System.out.print("seventy ");break;
                    case 8:System.out.print("eighty ");break;
                    case 9:System.out.print("ninety ");break;
                    //case 0:   System.out.println("hundred ");break;

            }                           
        }           
    }
  }

}

How can I kill a process by name instead of PID?

Kill all processes having snippet in startup path. You can kill all apps started from some directory by for putting /directory/ as a snippet. This is quite usefull when you start several components for the same application from the same app directory.

ps ax | grep <snippet> | grep -v grep | awk '{print $1}' | xargs kill

* I would preffer pgrep if available

sql server Get the FULL month name from a date

SELECT DATENAME(MONTH, GETDATE()) 
         + RIGHT(CONVERT(VARCHAR(12), GETDATE(), 107), 9) AS [Month DD, YYYY]

OR Date without Comma Between date and year, you can use the following

SELECT DATENAME(MONTH, GETDATE()) + ' ' + CAST(DAY(GETDATE()) AS VARCHAR(2))
           + ' ' + CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS [Month DD YYYY]

How do I get the number of days between two dates in JavaScript?

if you wanna have an DateArray with dates try this:

<script>
        function getDates(startDate, stopDate) {
        var dateArray = new Array();
        var currentDate = moment(startDate);
        dateArray.push( moment(currentDate).format('L'));

        var stopDate = moment(stopDate);
        while (dateArray[dateArray.length -1] != stopDate._i) {
            dateArray.push( moment(currentDate).format('L'));
            currentDate = moment(currentDate).add(1, 'days');
        }
        return dateArray;
      }
</script>

DebugSnippet

Reading Excel files from C#

SpreadsheetGear for .NET is an Excel compatible spreadsheet component for .NET. You can see what our customers say about performance on the right hand side of our product page. You can try it yourself with the free, fully-functional evaluation.

How can I convert JSON to CSV?

Use json_normalize from pandas:

  • Given the sample data from the OP, in a file named test.json.
  • encoding='utf-8' may not be necessary.
  • The following code takes advantage of the pathlib library.
    • .open is a method of pathlib.
    • Works with non-Windows paths too.
  • Use pandas.to_csv(...) to save the data to a csv file.
import pandas as pd
# As of Pandas 1.01, json_normalize as pandas.io.json.json_normalize is deprecated and is now exposed in the top-level namespace.
# from pandas.io.json import json_normalize
from pathlib import Path
import json

# set path to file
p = Path(r'c:\some_path_to_file\test.json')

# read json
with p.open('r', encoding='utf-8') as f:
    data = json.loads(f.read())

# create dataframe
df = pd.json_normalize(data)

# dataframe view
 pk            model  fields.codename           fields.name  fields.content_type
 22  auth.permission     add_logentry     Can add log entry                    8
 23  auth.permission  change_logentry  Can change log entry                    8
 24  auth.permission  delete_logentry  Can delete log entry                    8
  4  auth.permission        add_group         Can add group                    2
 10  auth.permission      add_message       Can add message                    4

# save to csv
df.to_csv('test.csv', index=False, encoding='utf-8')

CSV Output:

pk,model,fields.codename,fields.name,fields.content_type
22,auth.permission,add_logentry,Can add log entry,8
23,auth.permission,change_logentry,Can change log entry,8
24,auth.permission,delete_logentry,Can delete log entry,8
4,auth.permission,add_group,Can add group,2
10,auth.permission,add_message,Can add message,4

Other Resources for more heavily nested JSON objects:

Arrays in cookies PHP

recently i've created this code for my client, i'm using array for cookie in this code, actually this code gets recently viewed pages by user using cookies, hope it helps you...!

function curPageURL() { // get url
return 'http' . ((
!empty($_SERVER['HTTPS']) &&
$_SERVER['HTTPS'] !== 'off' ||
$_SERVER['SERVER_PORT'] == 443
) ? 's' : '') . '://' . $_SERVER['SERVER_NAME'] . (
$_SERVER['SERVER_PORT'] == 80 ? '' :  $_SERVER['SERVER_PORT']
) . $_SERVER['REQUEST_URI'];
}

$currentPage = curPageURL(); // call function
$counter = $_COOKIE['_counter']; // set counter variable

if(!$_COOKIE['_PAGES']){ // if _Pages cookie
$default = 1; // set default value to 1
setcookie("_counter",$default,time()+7200); // set counter cookie
setcookie("_PAGES[$default]",$currentPage, time()+3600); // set cookie  
}
else{ // if ! _Pages cookie 
$default = $counter+1; // set default value to +1
setcookie("_counter",$default,time()+7200); // set counter cookie
}


if(@in_array($currentPage, @$_COOKIE['_PAGES'])){ // if same url found
}
else{ // if new url found
setcookie("_PAGES[$default]",$currentPage, time()+3600); // set cookie  
}


if($_COOKIE['_PAGES']){
foreach ($_COOKIE['_PAGES'] as $value){
    echo "<a href='{$value}'>{$value}</a>";
} 
}

Rails how to run rake task

In rails 4.2 the above methods didn't work.

  1. Go to the Terminal.
  2. Change the directory to the location where your rake file is present.
  3. run rake task_name.
  4. In the above case, run rake iqmedier - will run only iqmedir task.
  5. run rake euroads - will run only the euroads task.
  6. To Run all the tasks in that file assign the following inside the same file and run rake all

    task :all => [:iqmedier, :euroads, :mikkelsen, :orville ] do #This will print all the tasks o/p on the screen 
    end
    

Is it possible to install iOS 6 SDK on Xcode 5?

Linking the 6.1 SDK into Xcode 5 as described in the other answers is one step. However this still doesn't solve the problem that running on iOS 7 new UI elements are taken, view controllers are made full-size etc.

As described in this answer it is also required to switch the UI into legacy mode on iOS 7:

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"UIUseLegacyUI"];
[[NSUserDefaults standardUserDefaults] synchronize];

Beware: This is an undocumented key and not recommended for App Store builds!

Also, in my experience while testing on the device I found that it only works the second time I launch the app even though I'm running the code fairly early in the app launch, in +[AppDelegate initialize]. Also there are subtle differences to a version built using Xcode 4.6. For instance, transparent navigation bars behave differently (causing the view to be full-size).

However, since Xcode 4.6.3 crashes on Mavericks (at least for me, see rdar://15318883), this is at least a solution to continue using Xcode 5 for debugging.

rawQuery(query, selectionArgs)

if your SQL query is this

SELECT id,name,roll FROM student WHERE name='Amit' AND roll='7'

then rawQuery will be

String query="SELECT id, name, roll FROM student WHERE name = ? AND roll = ?";
String[] selectionArgs = {"Amit","7"} 
db.rawQuery(query, selectionArgs);

comparing elements of the same array in java

Try this or purpose will solve with lesser no of steps

for (int i = 0; i < a.length; i++) 
{
    for (int k = i+1; k < a.length; k++) 
    {
        if (a[i] != a[k]) 
         {
            System.out.println(a[i]+"not the same with"+a[k]+"\n");
        }
    }
}

for each loop in Objective-C for accessing NSMutable dictionary

The easiest way to enumerate a dictionary is

for (NSString *key in tDictionary.keyEnumerator) 
{
    //do something here;
}

where tDictionary is the NSDictionary or NSMutableDictionary you want to iterate.

How do I schedule jobs in Jenkins?

Jenkins uses Cron format on scheduling. You can refer this link for more detailhttps://en.wikipedia.org/wiki/Cron. One more thing, Jenkins provide us a very useful preview. Please take a look on the screenshot. enter image description here

I hope this help. Thanks

How do I import a sql data file into SQL Server?

Try this process -

Open the Query Analyzer

Start --> Programs --> MS SQL Server --> Query Analyzer

Once opened, connect to the database that you are wish running the script on.

Next, open the SQL file using File --> Open option. Select .sql file.

Once it is open, you can execute the file by pressing F5.

How to index into a dictionary?

If you need an ordered dictionary, you can use odict.

Compare a date string to datetime in SQL Server?

I normally convert date-time to date and compare them, like these:

SELECT 'Same Date' WHERE CAST(getDate() as date) = cast('2/24/2012 2:23 PM' as date)

or

SELECT 'Same Date' WHERE DATEDIFF(dd, cast(getDate() as date), cast('2/24/2012 2:23 PM' as date)) = 0

Setting up redirect in web.config file

You probably want to look at something like URL Rewrite to rewrite URLs to more user friendly ones rather than using a simple httpRedirect. You could then make a rule like this:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Rewrite to Category">
        <match url="^Category/([_0-9a-z-]+)/([_0-9a-z-]+)" />
        <action type="Rewrite" url="category.aspx?cid={R:2}" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

AngularJS not detecting Access-Control-Allow-Origin header?

CROS needs to be resolved from server side.

Create Filters as per requirement to allow access and add filters in web.xml

Example using spring:

Filter Class:

@Component
public class SimpleFilter implements Filter {

@Override
public void init(FilterConfig arg0) throws ServletException {}

@Override
public void doFilter(ServletRequest req, ServletResponse resp,
                     FilterChain chain) throws IOException, ServletException {

    HttpServletResponse response=(HttpServletResponse) resp;

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

    chain.doFilter(req, resp);
}

@Override
public void destroy() {}

}

Web.xml:

<filter>
    <filter-name>simpleCORSFilter</filter-name>
    <filter-class>
        com.abc.web.controller.general.SimpleFilter
    </filter-class>
</filter>
<filter-mapping>
    <filter-name>simpleCORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Data binding to SelectedItem in a WPF Treeview

Answer with attached properties and no external dependencies, should the need ever arise!

You can create an attached property that is bindable and has a getter and setter:

public class TreeViewHelper
{
    private static Dictionary<DependencyObject, TreeViewSelectedItemBehavior> behaviors = new Dictionary<DependencyObject, TreeViewSelectedItemBehavior>();

    public static object GetSelectedItem(DependencyObject obj)
    {
        return (object)obj.GetValue(SelectedItemProperty);
    }

    public static void SetSelectedItem(DependencyObject obj, object value)
    {
        obj.SetValue(SelectedItemProperty, value);
    }

    // Using a DependencyProperty as the backing store for SelectedItem.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SelectedItemProperty =
        DependencyProperty.RegisterAttached("SelectedItem", typeof(object), typeof(TreeViewHelper), new UIPropertyMetadata(null, SelectedItemChanged));

    private static void SelectedItemChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        if (!(obj is TreeView))
            return;

        if (!behaviors.ContainsKey(obj))
            behaviors.Add(obj, new TreeViewSelectedItemBehavior(obj as TreeView));

        TreeViewSelectedItemBehavior view = behaviors[obj];
        view.ChangeSelectedItem(e.NewValue);
    }

    private class TreeViewSelectedItemBehavior
    {
        TreeView view;
        public TreeViewSelectedItemBehavior(TreeView view)
        {
            this.view = view;
            view.SelectedItemChanged += (sender, e) => SetSelectedItem(view, e.NewValue);
        }

        internal void ChangeSelectedItem(object p)
        {
            TreeViewItem item = (TreeViewItem)view.ItemContainerGenerator.ContainerFromItem(p);
            item.IsSelected = true;
        }
    }
}

Add the namespace declaration containing that class to your XAML and bind as follows (local is how I named the namespace declaration):

        <TreeView ItemsSource="{Binding Path=Root.Children}" local:TreeViewHelper.SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay}">

    </TreeView>

Now you can bind the selected item, and also set it in your view model to change it programmatically, should that requirement ever arise. This is, of course, assuming that you implement INotifyPropertyChanged on that particular property.

PHP + MySQL transactions examples

The idea I generally use when working with transactions looks like this (semi-pseudo-code):

try {
    // First of all, let's begin a transaction
    $db->beginTransaction();
    
    // A set of queries; if one fails, an exception should be thrown
    $db->query('first query');
    $db->query('second query');
    $db->query('third query');
    
    // If we arrive here, it means that no exception was thrown
    // i.e. no query has failed, and we can commit the transaction
    $db->commit();
} catch (\Throwable $e) {
    // An exception has been thrown
    // We must rollback the transaction
    $db->rollback();
    throw $e; // but the error must be handled anyway
}

Note that, with this idea, if a query fails, an Exception must be thrown:
  • PDO can do that, depending on how you configure it
  • else, with some other API, you might have to test the result of the function used to execute a query, and throw an exception yourself.

Unfortunately, there is no magic involved. You cannot just put an instruction somewhere and have transactions done automatically: you still have to specific which group of queries must be executed in a transaction.

For example, quite often you'll have a couple of queries before the transaction (before the begin) and another couple of queries after the transaction (after either commit or rollback) and you'll want those queries executed no matter what happened (or not) in the transaction.

How do I convert date/time from 24-hour format to 12-hour AM/PM?

I think you can use date() function to achive this

$date = '19:24:15 06/13/2013'; 
echo date('h:i:s a m/d/Y', strtotime($date));

This will output

07:24:15 pm 06/13/2013

Live Sample

h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)

Updated

This is with DateTime

$date = new DateTime('19:24:15 06/13/2013');
echo $date->format('h:i:s a m/d/Y') ;

Live Sample

CSS to prevent child element from inheriting parent styles

Unfortunately, you're out of luck here.

There is inherit to copy a certain value from a parent to its children, but there is no property the other way round (which would involve another selector to decide which style to revert).

You will have to revert style changes manually:

div { color: green; }

form div { color: red; }

form div div.content { color: green; }

If you have access to the markup, you can add several classes to style precisely what you need:

form div.sub { color: red; }

form div div.content { /* remains green */ }

Edit: The CSS Working Group is up to something:

div.content {
  all: revert;
}

No idea, when or if ever this will be implemented by browsers.

Edit 2: As of March 2015 all modern browsers but Safari and IE/Edge have implemented it: https://twitter.com/LeaVerou/status/577390241763467264 (thanks, @Lea Verou!)

Edit 3: default was renamed to revert.

iCheck check if checkbox is checked

Use following code to check if iCheck is checked or not using single method.

$('Selector').on('ifChanged', function(event){

    //Check if checkbox is checked or not
    var checkboxChecked = $(this).is(':checked');

    if(checkboxChecked) {
        alert("checked");
    }else{
        alert("un-checked");
    }
});

Show/Hide Div on Scroll

$(window).scroll(function () {
  var Bottom = $(window).height() + $(window).scrollTop() >= $(document).height();
if(Bottom )
{
$('#div').hide();
}
});

How to get client IP address in Laravel 5+

For Laravel 5 you can use the Request object. Just call its ip() method, something like:

$request->ip();

How to convert a string variable containing time to time_t type in c++?

This should work:

int hh, mm, ss;
struct tm when = {0};

sscanf_s(date, "%d:%d:%d", &hh, &mm, &ss);


when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;

time_t converted;
converted = mktime(&when);

Modify as needed.

How do I convert a PDF document to a preview image in PHP?

You can also get the page count using

$im->getNumberImages();

Then you can can create thumbs of all the pages using a loop, eg.

'file.pdf['.$x.']'

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

What's an easy way to read random line from a file in Unix command line?

perlfaq5: How do I select a random line from a file? Here's a reservoir-sampling algorithm from the Camel Book:

perl -e 'srand; rand($.) < 1 && ($line = $_) while <>; print $line;' file

This has a significant advantage in space over reading the whole file in. You can find a proof of this method in The Art of Computer Programming, Volume 2, Section 3.4.2, by Donald E. Knuth.

How to make a cross-module variable?

I don't endorse this solution in any way, shape or form. But if you add a variable to the __builtin__ module, it will be accessible as if a global from any other module that includes __builtin__ -- which is all of them, by default.

a.py contains

print foo

b.py contains

import __builtin__
__builtin__.foo = 1
import a

The result is that "1" is printed.

Edit: The __builtin__ module is available as the local symbol __builtins__ -- that's the reason for the discrepancy between two of these answers. Also note that __builtin__ has been renamed to builtins in python3.

Cross origin requests are only supported for HTTP but it's not cross-domain

REM kill all existing instance of chrome 
taskkill /F /IM chrome.exe /T
REM directory path where chrome.exe is located
set chromeLocation="C:\Program Files (x86)\Google\Chrome\Application"
cd %chromeLocation%
cd c:
start chrome.exe --allow-file-access-from-files
  1. change chromeLocation path with yours.

  2. save above as .bat file.

  3. drag drop you file on the batch file you created. (chrome does give restore pages option though so if you have pages open just hit restore and it will work).

how to stop a loop arduino

The three options that come to mind:

1st) End void loop() with while(1)... or equally as good... while(true)

void loop(){
    //the code you want to run once here, 
    //e.g., If (blah == blah)...etc.

    while(1)        //last line of main loop
}

This option runs your code once and then kicks the Ard into an endless "invisible" loop. Perhaps not the nicest way to go, but as far as outside appearances, it gets the job done.
The Ard will continue to draw current while it spins itself in an endless circle... perhaps one could set up a sort of timer function that puts the Ard to sleep after so many seconds, minutes, etc., of looping... just a thought... there are certainly various sleep libraries out there... see e.g., Monk, Programming Arduino: Next Steps, pgs., 85-100 for further discussion of such.

2nd) Create a "stop main loop" function with a conditional control structure that makes its initial test fail on a second pass.
This often requires declaring a global variable and having the "stop main loop" function toggle the value of the variable upon termination. E.g.,

boolean stop_it = false;         //global variable

void setup(){
    Serial.begin(9600); 
    //blah...
}

boolean stop_main_loop(){        //fancy stop main loop function

    if(stop_it == false){   //which it will be the first time through

        Serial.println("This should print once.");

       //then do some more blah....you can locate all the
       // code you want to run once here....eventually end by 
       //toggling the "stop_it" variable ... 
    }
    stop_it = true; //...like this
    return stop_it;   //then send this newly updated "stop_it" value
                     // outside the function
}

void loop{ 

    stop_it = stop_main_loop();     //and finally catch that updated 
                                    //value and store it in the global stop_it 
                                    //variable, effectively 
                                    //halting the loop  ...
}

Granted, this might not be especially pretty, but it also works.
It kicks the Ard into another endless "invisible" loop, but this time it's a case of repeatedly checking the if(stop_it == false) condition in stop_main_loop() which of course fails to pass every time after the first time through.

3rd) One could once again use a global variable but use a simple if (test == blah){} structure instead of a fancy "stop main loop" function.

boolean start = true;                  //global variable

void setup(){

      Serial.begin(9600);
}

void loop(){

      if(start == true){           //which it will be the first time through



           Serial.println("This should print once.");       

           //the code you want to run once here, 
           //e.g., more If (blah == blah)...etc.

     }

start = false;                //toggle value of global "start" variable
                              //Next time around, the if test is sure to fail.
}

There are certainly other ways to "stop" that pesky endless main loop but these three as well as those already mentioned should get you started.

Is SQL syntax case sensitive?

The SQL Keywords are case-insensitive (SELECT, FROM, WHERE, etc), but are often written in all caps. However in some setups table and column names are case-sensitive. MySQL has a configuration option to enable/disable it. Usually case-sensitive table and column names are the default on Linux MySQL and case-insensitive used to be the default on Windows, but now the installer asked about this during setup. For MSSQL it is a function of the database's collation setting.

Here is the MySQL page about name case-sensitivity

Here is the article in MSDN about collations for MSSQL

How do I make a C++ console program exit?

simple enough..

exit ( 0 ); }//end of function

Make sure there is a space on both sides of the 0. Without spaces, the program will not stop.

switch() statement usage

Well, timing to the rescue again. It seems switch is generally faster than if statements. So that, and the fact that the code is shorter/neater with a switch statement leans in favor of switch:

# Simplified to only measure the overhead of switch vs if

test1 <- function(type) {
 switch(type,
        mean = 1,
        median = 2,
        trimmed = 3)
}

test2 <- function(type) {
 if (type == "mean") 1
 else if (type == "median") 2
 else if (type == "trimmed") 3
}

system.time( for(i in 1:1e6) test1('mean') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('mean') ) # 1.13 secs
system.time( for(i in 1:1e6) test1('trimmed') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('trimmed') ) # 2.28 secs

Update With Joshua's comment in mind, I tried other ways to benchmark. The microbenchmark seems the best. ...and it shows similar timings:

> library(microbenchmark)
> microbenchmark(test1('mean'), test2('mean'), times=1e6)
Unit: nanoseconds
           expr  min   lq median   uq      max
1 test1("mean")  709  771    864  951 16122411
2 test2("mean") 1007 1073   1147 1223  8012202

> microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)
Unit: nanoseconds
              expr  min   lq median   uq      max
1 test1("trimmed")  733  792    843  944 60440833
2 test2("trimmed") 2022 2133   2203 2309 60814430

Final Update Here's showing how versatile switch is:

switch(type, case1=1, case2=, case3=2.5, 99)

This maps case2 and case3 to 2.5 and the (unnamed) default to 99. For more information, try ?switch

Using margin:auto to vertically-align a div

Here's the best solution I've found: http://jsfiddle.net/yWnZ2/446/ Works in Chrome, Firefox, Safari, IE8-11 & Edge.

If you have a declared height (height: 1em, height: 50%, etc.) or it's an element where the browser knows the height (img, svg, or canvas for example), then all you need for vertical centering is this:

.message {
    position: absolute;
    top: 0; bottom: 0; left: 0; right: 0;
    margin: auto;
}

You'll usually want to specify a width or max-width so the content doesn't stretch the whole length of the screen/container.

If you're using this for a modal that you want always centered in the viewport overlapping other content, use position: fixed; for both elements instead of position: absolute. http://jsfiddle.net/yWnZ2/445/

Here's a more complete writeup: http://codepen.io/shshaw/pen/gEiDt

How to insert strings containing slashes with sed?

add \ before special characters:

s/\?page=one&/page\/one\//g

etc.

YAML mapping values are not allowed in this context

The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:

jobs:
 - - name: A
   - schedule: "0 0/5 * 1/1 * ? *"
   - - type: mongodb.cluster
     - config:
       - host: mongodb://localhost:27017/admin?replicaSet=rs
       - minSecondaries: 2
       - minOplogHours: 100
       - maxSecondaryDelay: 120
 - - name: B
   - schedule: "0 0/5 * 1/1 * ? *"
   - - type: mongodb.cluster
     - config:
       - host: mongodb://localhost:27017/admin?replicaSet=rs
       - minSecondaries: 2
       - minOplogHours: 100
       - maxSecondaryDelay: 120

Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

I was having the same problem. I tried

rm -f ./.git/index.lock 

and the console gave me an error message. Then, I tried

rm --force ./.git/index.lock

and that worked.

Good Luck! This works super

Solving a "communications link failure" with JDBC and MySQL

I found the solution

since MySQL need the Localhost in-order to work.

go to /etc/network/interfaces file and make sure you have the localhost configuration set there:

auto lo
iface lo inet loopback

NOW RESTART the Networking subsystem and the MySQL Services:

sudo /etc/init.d/networking restart

sudo /etc/init.d/mysql restart

Try it now

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 generate .NET 4.0 classes from xsd?

I used xsd.exe in the Windows command prompt.

However, since my xml referenced several online xml's (in my case http://www.w3.org/1999/xlink.xsd which references http://www.w3.org/2001/xml.xsd) I had to also download those schematics, put them in the same directory as my xsd, and then list those files in the command:

"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\xsd.exe" /classes /language:CS your.xsd xlink.xsd xml.xsd

How do I use vim registers?

I use the default register to grep for text in my vim window without having to reach for the mouse.

  1. yank text
  2. :!grep "<CTRL-R>0"<CR>

What tool can decompile a DLL into C++ source code?

There really isn't any way of doing this as most of the useful information is discarded in the compilation process. However, you may want to take a look at this site to see if you can find some way of extracting something from the DLL.

Hibernate table not mapped error in HQL query

hibernate3.HibernateQueryException: Books is not mapped [SELECT COUNT(*) FROM Books];

Hibernate is trying to say that it does not know an entity named "Books". Let's look at your entity:

@javax.persistence.Entity
@javax.persistence.Table(name = "Books")
public class Book {

Right. The table name for Book has been renamed to "Books" but the entity name is still "Book" from the class name. If you want to set the entity name, you should use the @Entity annotation's name instead:

// this allows you to use the entity Books in HQL queries
@javax.persistence.Entity(name = "Books")
public class Book {

That sets both the entity name and the table name.


The opposite problem happened to me when I was migrating from the Person.hbm.xml file to using the Java annotations to describe the hibernate fields. My old XML file had:

<hibernate-mapping package="...">
    <class name="Person" table="persons" lazy="true">
       ...
</hibernate-mapping>

And my new entity had a @Entity(name=...) which I needed to set the name of the table.

// this renames the entity and sets the table name
@javax.persistence.Entity(name = "persons")
public class Person {
    ...

What I then was seeing was HQL errors like:

QuerySyntaxException: Person is not mapped
     [SELECT id FROM Person WHERE id in (:ids)]

The problem with this was that the entity name was being renamed to persons as well. I should have set the table name using:

// no name = here so the entity can be used as Person
@javax.persistence.Entity
// table name specified here
@javax.persistence.Table(name = "persons")
public class Person extends BaseGeneratedId {

Hope this helps others.

HttpListener Access Denied

Yes you can run HttpListener in non-admin mode. All you need to do is grant permissions to the particular URL. e.g.

netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user

Documentation is here.

Get the latest record from mongodb collection

Yet another way of getting the last item from a MongoDB Collection (don't mind about the examples):

> db.collection.find().sort({'_id':-1}).limit(1)

Normal Projection

> db.Sports.find()
{ "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2017", "Body" : "Again, the Pats won the Super Bowl." }
{ "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }

Sorted Projection ( _id: reverse order )

> db.Sports.find().sort({'_id':-1})
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
{ "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
{ "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2018", "Body" : "Again, the Pats won the Super Bowl" }

sort({'_id':-1}), defines a projection in descending order of all documents, based on their _ids.

Sorted Projection ( _id: reverse order ): getting the latest (last) document from a collection.

> db.Sports.find().sort({'_id':-1}).limit(1)
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }

Apache: "AuthType not set!" 500 Error

I think that you have a version 2.4.x of Apache.

Have you sure that you load this 2 modules ? - mod_authn_core - mod_authz_core

LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authz_core_module modules/mod_authz_core.so

PS : My recommendation for authorization and rights is (by default) :

LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_core_module modules/mod_authz_core.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so

remove item from stored array in angular 2

That work for me

 this.array.pop(index);

 for example index = 3 

 this.array.pop(3);

Adding double quote delimiters into csv file

This is actually pretty easy in Excel (or any spreadsheet application).

You'll want to use the =CONCATENATE() function as shown in the formula bar in the following screenshot:

Step 1 involves adding quotes in column B,

Step 2 involves specifying the function and then copying it down column C (by now your spreadsheet should look like the screenshot),

enter image description here

Step 3 (if you need the text outside of the formula) involves copying column C, right-clicking on column D, choosing Paste Special >> Paste Values. Column D should then contain the text that was calculated in column C.

How to replace � in a string

Change the Encoding to UTF-8 while parsing .This will remove the special characters

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

time = Time.now.to_s

time = DateTime.parse(time).strftime("%d/%m/%Y %H:%M")

for increment decrement month use << >> operators

examples

datetime_month_before = DateTime.parse(time) << 1



datetime_month_before = DateTime.now << 1

Failed to connect to camera service

For newer android versions that support setting permissions per app (since Marshmallow, 6.0) the permission for camera could be disabled and should be enabled from the app settings.

How do you use NSAttributedString?

Super easy way to do this.

let text = "This is a colorful attributed string"
let attributedText = 
NSMutableAttributedString.getAttributedString(fromString: text)
attributedText.apply(color: .red, subString: "This")
//Apply yellow color on range
attributedText.apply(color: .yellow, onRange: NSMakeRange(5, 4))

For more detail click here; https://github.com/iOSTechHub/AttributedString

Create a dictionary with list comprehension

Use a dict comprehension:

{key: value for (key, value) in iterable}

Note: this is for Python 3.x (and 2.7 upwards). Formerly in Python 2.6 and earlier, the dict built-in could receive an iterable of key/value pairs, so you can pass it a list comprehension or generator expression. For example:

dict((key, func(key)) for key in keys)

In simple cases you don't need a comprehension at all...

But if you already have iterable(s) of keys and/or values, just call the dict built-in directly:

1) consumed from any iterable yielding pairs of keys/vals
dict(pairs)

2) "zip'ped" from two separate iterables of keys/vals
dict(zip(list_of_keys, list_of_values))

Read file from resources folder in Spring Boot

See my answer here: https://stackoverflow.com/a/56854431/4453282

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

Use these 2 imports.

Declare

@Autowired
ResourceLoader resourceLoader;

Use this in some function

Resource resource=resourceLoader.getResource("classpath:preferences.json");

In your case, as you need the file you may use following

File file = resource.getFile()

Reference:http://frugalisminds.com/spring/load-file-classpath-spring-boot/ As already mentioned in previous answers don't use ResourceUtils it doesn't work after deployment of JAR, this will work in IDE as well as after deployment

Programmatically change the src of an img tag

if you use the JQuery library use this instruction:

$("#imageID").attr('src', 'srcImage.jpg');

jQuery check if attr = value

Just remove the .val(). Like:

if ( $('html').attr('lang') == 'fr-FR' ) {
    // do this
} else {
    // do that
}

Execute a SQL Stored Procedure and process the results

My Stored Procedure Requires 2 Parameters and I needed my function to return a datatable here is 100% working code

Please make sure that your procedure return some rows

Public Shared Function Get_BillDetails(AccountNumber As String) As DataTable
    Try
        Connection.Connect()
        debug.print("Look up account number " & AccountNumber)
        Dim DP As New SqlDataAdapter("EXEC SP_GET_ACCOUNT_PAYABLES_GROUP  '" & AccountNumber & "' , '" & 08/28/2013 &"'", connection.Con)
        Dim DST As New DataSet
        DP.Fill(DST)
        Return DST.Tables(0)      
    Catch ex As Exception
        Return Nothing
    End Try
End Function

Uncaught ReferenceError: angular is not defined - AngularJS not working

i forgot to add below line to my HTML code after i add problem has resolved.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>

How do I get a computer's name and IP address using VB.NET?

Imports System.Net

Module MainLine
    Sub Main()
        Dim hostName As String = Dns.GetHostName
        Console.WriteLine("Host Name : " & hostName & vbNewLine)
        For Each address In Dns.GetHostEntry(hostName).AddressList()
            Select Case Convert.ToInt32(address.AddressFamily)
                Case 2
                    Console.WriteLine("IP Version 4 Address: " & address.ToString)
                Case 23
                    Console.WriteLine("IP Version 6 Address: " & address.ToString)
            End Select
        Next
        Console.ReadKey()
    End Sub
End Module

in querySelector: how to get the first and get the last elements? what traversal order is used in the dom?

Example to get the last input element:

document.querySelector(".groups-container >div:last-child input")

Remove Android App Title Bar

In the graphical editor, make sure you have chosen your theme at the top.

What is the standard way to add N seconds to datetime.time in Python?

One little thing, might add clarity to override the default value for seconds

>>> b = a + datetime.timedelta(seconds=3000)
>>> b
datetime.datetime(1, 1, 1, 12, 24, 59)

return in for loop or outside loop

There have been methodologies in all languages advocating for use of a single return statement in any function. However impossible it may be in certain code, some people do strive for that, however, it may end up making your code more complex (as in more lines of code), but on the other hand, somewhat easier to follow (as in logic flow).

This will not mess up garbage collection in any way!!

The better way to do it is to set a boolean value, if you want to listen to him.

boolean flag = false;
for(int i=0; i<array.length; ++i){
    if(array[i] == valueToFind) {
        flag = true;
        break;
    }
}
return flag;

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

I faced the same issue. Tried adding the US_export_policy.jar and local_policy.jar in the java security folder first but the issue persisted. Then added the below in java_opts inside tomcat setenv.shfile and it worked.

-Djdk.tls.ephemeralDHKeySize=2048

Please check this link for further info

What is a 'workspace' in Visual Studio Code?

If the Visual Studio Code is a fresh installation;

  1. Click on extensions, Search for "python" and click on install

  2. Click on view -> explorer If there in no folder added a folder to the Workspace (File->Add folder to Workspace)

  3. If you want to use a virtual python environment, Click on File -> Preference -> settings

Click on "{} open settings JSON" which is in top right corner of the window, then add the path to python.exe file which is in the virtual environment

{
    "python.pythonPath": "C:\\PathTo\\VirtualENV\\python.exe"
}
  1. Start a new terminal and check the correct python interpreter is selected

excel VBA run macro automatically whenever a cell is changed

Yes, this is possible by using worksheet events:

In the Visual Basic Editor open the worksheet you're interested in (i.e. "BigBoard") by double clicking on the name of the worksheet in the tree at the top left. Place the following code in the module:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Intersect(Target, Me.Range("D2")) Is Nothing Then Exit Sub
        Application.EnableEvents = False 'to prevent endless loop
        On Error Goto Finalize 'to re-enable the events      
        MsgBox "You changed THE CELL!"
    End If
Finalize:        
    Application.EnableEvents = True
End Sub

Add new item in existing array in c#.net

A new Append<TSource> method has been added to IEnumerable<TSource> since .NET Framework 4.7.1 and .NET Core 1.0.

Here is how to use it:

var numbers = new [] { "one", "two", "three" };
numbers = numbers.Append("four").ToArray();
Console.WriteLine(string.Join(", ", numbers)); // one, two, three, four

Note that if you want to add the element at the beginning of the array, you can use the new Prepend<TSource> method instead.

How to get input text value from inside td

Ah I think a understand now. Have a look if this really is what you want:

$(".start").keyup(function(){
    $(this).closest('tr').find("input").each(function() {
        alert(this.value)
    });
});

This will give you all input values of a row.

Update:
To get the value of not all elements you can use :not():

$(this).closest('tr').find("input:not([name^=desc][name^=phone])").each(function() {
     alert(this.value)
});

Actually I am not 100% sure whether it works this way, maybe you have to use two nots instead of this one combining both conditions.

Jquery UI tooltip does not support html content

To avoid placing HTML tags in the title attribute, another solution is to use markdown. For instance, you could use [br] to represent a line break, then perform a simple replace in the content function.

In title attribute:

"Sample Line 1[br][br]Sample Line 2"

In your content function:

content: function () {
    return $(this).attr('title').replace(/\[br\]/g,"<br />");
}

Plotting in a non-blocking way with Matplotlib

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

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

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

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

Or

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

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

Creating a constant Dictionary in C#

Creating a truly compile-time generated constant dictionary in C# is not really a straightforward task. Actually, none of the answers here really achieve that.

There is one solution though which meets your requirements, although not necessarily a nice one; remember that according to the C# specification, switch-case tables are compiled to constant hash jump tables. That is, they are constant dictionaries, not a series of if-else statements. So consider a switch-case statement like this:

switch (myString)
{
   case "cat": return 0;
   case "dog": return 1;
   case "elephant": return 3;
}

This is exactly what you want. And yes, I know, it's ugly.

Failed to load JavaHL Library

You may or may not need JavaHL depending on your OS. In addition to other suggestions just posting this here.

enter image description here

For other OS see this source: http://subclipse.tigris.org/wiki/JavaHL

How to run a shell script at startup

Painless, easiest and the most universal method is simply executing it with ~.bash_profile or ~.profile (if you don't have bash_profile file).

Just add the execution command at the bottom of that file and it will be executed when system started.

I have this one at the bottom an example; ~\Desktop\sound_fixer.sh

Path of currently executing powershell script

Split-Path $MyInvocation.MyCommand.Path -Parent

CheckBox in RecyclerView keeps on checking different items

Adding setItemViewCacheSize(int size) to recyclerview and passing size of list solved my problem.

mycode:

mrecyclerview.setItemViewCacheSize(mOrderList.size());
mBinding.mrecyclerview.setAdapter(mAdapter);

Source: https://stackoverflow.com/a/46951440/10459907

apply drop shadow to border-top only?

Multiple box shadows did it for me.

box-shadow:
        inset 0 -8px 4px 4px rgb(255,255,255),
        inset 0 2px 4px 0px rgba(50, 50, 50, 0.75);

http://jsfiddle.net/kk66f/

mvn command not found in OSX Mavrerick

I got same problem, I tried all above, noting solved my problem. Luckely, I solved the problem this way:

echo $SHELL

Output

/bin/zsh
OR 
/bin/bash

If it showing "bash" in output. You have to add env properties in .bashrc file (.bash_profile i did not tried, you can try) or else
It is showing 'zsh' in output. You have to add env properties in .zshrc file, if not exist already you create one no issue.

For loop in Objective-C

The traditional for loop in Objective-C is inherited from standard C and takes the following form:

for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
    // Do something.
}

For example, to print the numbers from 1 to 10, you could use the for loop:

for (int i = 1; i <= 10; i++)
{
    NSLog(@"%d", i);
}

On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.

for (NSString* currentString in myArrayOfStrings)
{
    NSLog(@"%@", currentString);
}

This is logically equivilant to the following traditional for loop:

for (int i = 0; i < [myArrayOfStrings count]; i++)
{
    NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}

The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.

Hope this helps.

What is python's site-packages directory?

When you use --user option with pip, the package gets installed in user's folder instead of global folder and you won't need to run pip command with admin privileges.

The location of user's packages folder can be found using:

python -m site --user-site

This will print something like:

C:\Users\%USERNAME%\AppData\Roaming\Python\Python35\site-packages

When you don't use --user option with pip, the package gets installed in global folder given by:

python -c "import site; print(site.getsitepackages())"

This will print something like:

['C:\\Program Files\\Anaconda3', 'C:\\Program Files\\Anaconda3\\lib\\site-packages'

Note: Above printed values are for On Windows 10 with Anaconda 4.x installed with defaults.

Is it possible to log all HTTP request headers with Apache?

In my case easiest way to get browser headers was to use php. It appends headers to file and prints them to test page.

<?php
$fp = fopen('m:/temp/requests.txt', 'a');
$time = $_SERVER['REQUEST_TIME'];
fwrite($fp, $time  "\n");
echo "$time.<br>";
foreach (getallheaders() as $name => $value) {
    $cur_hd = "$name: $value\n";
    fwrite($fp, $cur_hd);
    echo "$cur_hd.<br>";
}
fwrite($fp, "***\n");
fclose($fp);
?>

image.onload event and browser cache

I found that you can just do this in Chrome:

  $('.onload-fadein').each(function (k, v) {
    v.onload = function () {
        $(this).animate({opacity: 1}, 2000);
    };
    v.src = v.src;
});

Setting the .src to itself will trigger the onload event.

Customize list item bullets using CSS

Another way of changing the size of the bullets would be:

  1. Disabling the bullets altogether
  2. Re-adding the custom bullets with the help of ::before pseudo-element.

Example:

_x000D_
_x000D_
ul {_x000D_
  list-style-type: none;_x000D_
}_x000D_
_x000D_
li::before {_x000D_
  display:          inline-block;_x000D_
  vertical-align:   middle;_x000D_
  width:            5px;_x000D_
  height:           5px;_x000D_
  background-color: #000000;_x000D_
  margin-right:     8px;_x000D_
  content:          ' '_x000D_
}
_x000D_
<ul>_x000D_
  <li>first element</li>_x000D_
  <li>second element</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

No markup changes needed

How to access the correct `this` inside a callback?

Currently there is another approach possible if classes are used in code.

With support of class fields it's possible to make it next way:

class someView {
    onSomeInputKeyUp = (event) => {
        console.log(this); // this refers to correct value
    // ....
    someInitMethod() {
        //...
        someInput.addEventListener('input', this.onSomeInputKeyUp)

For sure under the hood it's all old good arrow function that bind context but in this form it looks much more clear that explicit binding.

Since it's Stage 3 Proposal you will need babel and appropriate babel plugin to process it as for now(08/2018).

__init__ and arguments in Python

Every method needs to accept one argument: The instance itself (or the class if it is a static method).

Read more about classes in Python.

Html table tr inside td

Try this code

_x000D_
_x000D_
<table border="1" width="100%">
  <tr>
    <td>Name 1</td>
    <td>Name 2</td>
    <td colspan="2">Name 3</td>
    <td>Name 4</td>
  </tr>

  <tr>
    <td rowspan="3">ITEM 1</td>
    <td rowspan="3">ITEM 2</td>
    <td>name</td>
    <td>price</td>
    <td rowspan="3">ITEM 4</td>
  </tr>
  <tr>
    <td>name</td>
    <td>price</td>
  </tr>
  <tr>
    <td>name</td>
    <td>price</td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

INNER JOIN in UPDATE sql for DB2

You don't say what platform you're targeting. Referring to tables as files, though, leads me to believe that you're NOT running DB2 on Linux, UNIX or Windows (LUW).

However, if you are on DB2 LUW, see the MERGE statement:

For your example statement, this would be written as:

merge into file1 a
   using (select anotherfield, something from file2) b
   on substr(a.firstfield,10,20) = substr(b.anotherfield,1,10)
when matched and a.firstfield like 'BLAH%'
   then update set a.firstfield = 'BIT OF TEXT' || b.something;

Please note: For DB2, the third argument of the SUBSTR function is the number of bytes to return, not the ending position. Therefore, SUBSTR(a.firstfield,10,20) returns CHAR(20). However, SUBSTR(b.anotherfield,1,10) returns CHAR(10). I'm not sure if this was done on purpose, but it may affect your comparison.

private final static attribute vs private final attribute

While the other answers seem to make it pretty clear that there is generally no reason to use non-static constants, I couldn't find anyone pointing out that it is possible to have various instances with different values on their constant variables.

Consider the following example:

public class TestClass {
    private final static double NUMBER = Math.random();

    public TestClass () {
        System.out.println(NUMBER);
    }
}

Creating three instances of TestClass would print the same random value three times, since only one value is generated and stored into the static constant.

However, when trying the following example instead:

public class TestClass {
    private final double NUMBER = Math.random();

    public TestClass () {
        System.out.println(NUMBER);
    }
}

Creating three instances of TestClass would now print three different random values, because each instance has its own randomly generated constant value.

I can't think of any situation where it would be really useful to have different constant values on different instances, but I hope this helps pointing out that there is a clear difference between static and non-static finals.

How to reference image resources in XAML?

If the image is in your resources folder and its build action is set to Resource. You can reference the image in XAML as follows:

"pack://application:,,,/Resources/Search.png"

Assuming you do not have any folder structure under the Resources folder and it is an application. For example I use:

ImageSource="pack://application:,,,/Resources/RibbonImages/CloseButton.png"

when I have a folder named RibbonImages under Resources folder.

Decoding and verifying JWT token using System.IdentityModel.Tokens.Jwt

I am just wondering why to use some libraries for JWT token decoding and verification at all.

Encoded JWT token can be created using following pseudocode

var headers = base64URLencode(myHeaders);
var claims = base64URLencode(myClaims);
var payload = header + "." + claims;

var signature = base64URLencode(HMACSHA256(payload, secret));

var encodedJWT = payload + "." + signature;

It is very easy to do without any specific library. Using following code:

using System;
using System.Text;
using System.Security.Cryptography;

public class Program
{   
    // More info: https://stormpath.com/blog/jwt-the-right-way/
    public static void Main()
    {           
        var header = "{\"typ\":\"JWT\",\"alg\":\"HS256\"}";
        var claims = "{\"sub\":\"1047986\",\"email\":\"[email protected]\",\"given_name\":\"John\",\"family_name\":\"Doe\",\"primarysid\":\"b521a2af99bfdc65e04010ac1d046ff5\",\"iss\":\"http://example.com\",\"aud\":\"myapp\",\"exp\":1460555281,\"nbf\":1457963281}";

        var b64header = Convert.ToBase64String(Encoding.UTF8.GetBytes(header))
            .Replace('+', '-')
            .Replace('/', '_')
            .Replace("=", "");
        var b64claims = Convert.ToBase64String(Encoding.UTF8.GetBytes(claims))
            .Replace('+', '-')
            .Replace('/', '_')
            .Replace("=", "");

        var payload = b64header + "." + b64claims;
        Console.WriteLine("JWT without sig:    " + payload);

        byte[] key = Convert.FromBase64String("mPorwQB8kMDNQeeYO35KOrMMFn6rFVmbIohBphJPnp4=");
        byte[] message = Encoding.UTF8.GetBytes(payload);

        string sig = Convert.ToBase64String(HashHMAC(key, message))
            .Replace('+', '-')
            .Replace('/', '_')
            .Replace("=", "");

        Console.WriteLine("JWT with signature: " + payload + "." + sig);        
    }

    private static byte[] HashHMAC(byte[] key, byte[] message)
    {
        var hash = new HMACSHA256(key);
        return hash.ComputeHash(message);
    }
}

The token decoding is reversed version of the code above.To verify the signature you will need to the same and compare signature part with calculated signature.

UPDATE: For those how are struggling how to do base64 urlsafe encoding/decoding please see another SO question, and also wiki and RFCs

Java SecurityException: signer information does not match

A simple way around it is just try changing the order of your imported jar files which can be done from (Eclipse). Right click on your package -> Build Path -> Configure build path -> References and Libraries -> Order and Export. Try changing the order of jars which contain signature files.

How do I style radio buttons with images - laughing smiley for good, sad smiley for bad?

Images can be placed in place of radio buttons by using label and span elements.

   <div class="customize-radio">
        <label>Favourite Smiley</label>
        <br>
        <label for="hahaha">
          <input type="radio" name="smiley" id="hahaha">
          <span class="haha-img"></span>
          HAHAHA
        </label>
        <label for="kiss">
          <input type="radio" name="smiley" id="kiss">
          <span class="kiss-img"></span>
          Kiss
        </label>
        <label for="tongueOut">
          <input type="radio" name="smiley" id="tongueOut">
          <span class="tongueout-img"></span>
          TongueOut
        </label>
    </div>

Radio button should be hidden,

.customize-radio label > input[type = 'radio'] {
    visibility: hidden;
    position: absolute;
}

Image can be given in the span tag,

.customize-radio label > input[type = 'radio'] ~ span{
    cursor: pointer;
    width: 27px;
    height: 24px;
    display: inline-block;
    background-size: 27px 24px;
    background-repeat: no-repeat;
}
.haha-img {
    background-image: url('hahabefore.png');
}

.kiss-img{
    background-image: url('kissbefore.png');
}
.tongueout-img{
    background-image: url('tongueoutbefore.png');
}

To change the image on click of radio button, add checked state to the input tag,

.customize-radio label > input[type = 'radio']:checked ~ span.haha-img{
     background-image: url('haha.png');
}
.customize-radio label > input[type = 'radio']:checked ~ span.kiss-img{
    background-image: url('kiss.png');
}
.customize-radio label > input[type = 'radio']:checked ~ span.tongueout-img{
        background-image: url('tongueout.png');
}

If you have any queries, Refer to the following link, As I have taken solution from the below blog, http://frontendsupport.blogspot.com/2018/06/cool-radio-buttons-with-images.html

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

Note: I had the same problem, and it was because the referenced field was in a different collation in the 2 different tables (they had exact same type).

Make sure all your referenced fields have the same type AND the same collation!

How to move the cursor word by word in the OS X Terminal

I have Alt+/ working: open Preferences » Settings » Keyboard, set the entry for option cursor left to send string to shell: \033b, and set option cursor right to send string to shell: \033f. You can also use this for other Control key combinations.

Difference between using gradlew and gradle

The difference lies in the fact that ./gradlew indicates you are using a gradle wrapper. The wrapper is generally part of a project and it facilitates installation of gradle. If you were using gradle without the wrapper you would have to manually install it - for example, on a mac brew install gradle and then invoke gradle using the gradle command. In both cases you are using gradle, but the former is more convenient and ensures version consistency across different machines.

Each Wrapper is tied to a specific version of Gradle, so when you first run one of the commands above for a given Gradle version, it will download the corresponding Gradle distribution and use it to execute the build.

Not only does this mean that you don’t have to manually install Gradle yourself, but you are also sure to use the version of Gradle that the build is designed for. This makes your historical builds more reliable

Read more here - https://docs.gradle.org/current/userguide/gradle_wrapper.html

Also, Udacity has a neat, high level video explaining the concept of the gradle wrapper - https://www.youtube.com/watch?v=1aA949H-shk

Java: How to convert String[] to List or Set

String[] w = {"a", "b", "c", "d", "e"};  

List<String> wL = Arrays.asList(w);  

AngularJS - convert dates in controller

create a filter.js and you can make this as reusable

angular.module('yourmodule').filter('date', function($filter)
{
    return function(input)
    {
        if(input == null){ return ""; }
        var _date = $filter('date')(new Date(input), 'dd/MM/yyyy');
        return _date.toUpperCase();
    };
});

view

<span>{{ d.time | date }}</span>

or in controller

var filterdatetime = $filter('date')( yourdate );

Date filtering and formatting in Angular js.

How to list AD group membership for AD users using input list?

Everything in one line:

get-aduser -filter * -Properties memberof | select name, @{ l="GroupMembership"; e={$_.memberof  -join ";"  } } | export-csv membership.csv

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

I had this issue with an MVC project and here is how I fixed it.

  1. Open BundleConfig.cs
  2. Find :

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js"));

    Change to:

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.bundle.min.js"));
    

This will set the bundle file to load. It is already in the correct order. You just have to make sure that you are rendering this bundle in your view.

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

See here: https://github.com/twbs/bootstrap/issues/7501

So try:

$('body').css('overflow','hidden');
$('body').css('position','fixed');

V3.0.0. should have fixed this issue. Do you use the latest version? If so post an issue on https://github.com/twbs/bootstrap/

Select SQL results grouped by weeks

This should do it for you:

Declare @DatePeriod datetime

Set @DatePeriod = '2011-05-30'

Select  ProductName,
        IsNull([1],0) as 'Week 1',
        IsNull([2],0) as 'Week 2',
        IsNull([3],0) as 'Week 3',
        IsNull([4],0) as 'Week 4',
        IsNull([5], 0) as 'Week 5'

From 
(
Select  ProductName,
        DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, InputDate), 0), InputDate) +1 as [Weeks],
        Sale as 'Sale'

From dbo.YourTable
-- Only get rows where the date is the same as the DatePeriod
-- i.e DatePeriod is 30th May 2011 then only the weeks of May will be calculated
Where DatePart(Month, InputDate)= DatePart(Month, @DatePeriod)
)p 
Pivot (Sum(Sale) for Weeks in ([1],[2],[3],[4],[5])) as pv

It will calculate the week number relative to the month. So instead of week 20 for the year it will be week 2. The @DatePeriod variable is used to fetch only rows relative to the month (in this example only for the month of May)

Output using my sample data:

enter image description here

Node.js quick file server (static files over HTTP)

For the benefit of searchers, I liked Jakub g's answer, but wanted a little error handling. Obviously it's best to handle errors properly, but this should help prevent a site stopping if an error occurs. Code below:

var http = require('http');
var express = require('express');

process.on('uncaughtException', function(err) {
  console.log(err);
});

var server = express();

server.use(express.static(__dirname));

var port = 10001;
server.listen(port, function() { 
    console.log('listening on port ' + port);     
    //var err = new Error('This error won't break the application...')
    //throw err
});

psql - save results of command to a file

\copy which is a postgres command can work for any user. Don't know if it works for \dt or not, but general syntax is reproduced from the following link Postgres SQL copy syntax

\copy (select * from tempTable limit 100) to 'filenameinquotes' with header delimiter as ','

The above will save the output of the select query in the filename provided as a csv file

EDIT:

For my psql server the following command works this is an older version v8.5

copy (select * from table1) to 'full_path_filename' csv header;

MVC 4 client side validation not working

If you use jquery.validate.js and jquery.validate.unobtrusive.js for validating on client side, you should remember that you have to register any validation attribute of any DOM element on your request. Therefor you can use this code:

$.validator.unobtrusive.parse('your main element on layout');

to register all validation attributes. You can call this method on (for example) : $(document).ajaxSuccess() or $(document).ready() to register all of them and your validation can be occurred successfully instead of registering all js files on cshtml files.

Extracting a parameter from a URL in WordPress

You can try this function

/**
 * Gets the request parameter.
 *
 * @param      string  $key      The query parameter
 * @param      string  $default  The default value to return if not found
 *
 * @return     string  The request parameter.
 */

function get_request_parameter( $key, $default = '' ) {
    // If not request set
    if ( ! isset( $_REQUEST[ $key ] ) || empty( $_REQUEST[ $key ] ) ) {
        return $default;
    }

    // Set so process it
    return strip_tags( (string) wp_unslash( $_REQUEST[ $key ] ) );
}

Here is what is happening in the function

Here three things are happening.

  • First we check if the request key is present or not. If not, then just return a default value.
  • If it is set, then we first remove slashes by doing wp_unslash. Read here why it is better than stripslashes_deep.
  • Then we sanitize the value by doing a simple strip_tags. If you expect rich text from parameter, then run it through wp_kses or similar functions.

All of this information plus more info on the thinking behind the function can be found on this link https://www.intechgrity.com/correct-way-get-url-parameter-values-wordpress/

How to define static property in TypeScript interface

Static properties are usually placed on the (global) constructor for the object, whereas the "interface" keyword applies to instances of the object.

The previous answer given is of course correct if you are writing the class in TypeScript. It may help others to know that if you are describing an object that is already implemented elsewhere, then the global constructor including static properties can be declared like this:

declare var myInterface : {
  new(): Interface;
  Name:string;
}

How do I use Ruby for shell scripting?

When you want to write more complex ruby scripts, these tools may help:

For example:

  • thor(a scripting framework)

  • gli(git like interface)

  • methadone(for creating simple tools)

They give you a quick start to write your own scripts, especially 'command line app'.

align right in a table cell with CSS

Use

text-align: right

The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content.

See

text-align

<td class='alnright'>text to be aligned to right</td>

<style>
    .alnright { text-align: right; }
</style>

Listing all permutations of a string/integer

Slightly modified version in C# that yields needed permutations in an array of ANY type.

    // USAGE: create an array of any type, and call Permutations()
    var vals = new[] {"a", "bb", "ccc"};
    foreach (var v in Permutations(vals))
        Console.WriteLine(string.Join(",", v)); // Print values separated by comma


public static IEnumerable<T[]> Permutations<T>(T[] values, int fromInd = 0)
{
    if (fromInd + 1 == values.Length)
        yield return values;
    else
    {
        foreach (var v in Permutations(values, fromInd + 1))
            yield return v;

        for (var i = fromInd + 1; i < values.Length; i++)
        {
            SwapValues(values, fromInd, i);
            foreach (var v in Permutations(values, fromInd + 1))
                yield return v;
            SwapValues(values, fromInd, i);
        }
    }
}

private static void SwapValues<T>(T[] values, int pos1, int pos2)
{
    if (pos1 != pos2)
    {
        T tmp = values[pos1];
        values[pos1] = values[pos2];
        values[pos2] = tmp;
    }
}

milliseconds to days

For simple cases like this, TimeUnit should be used. TimeUnit usage is a bit more explicit about what is being represented and is also much easier to read and write when compared to doing all of the arithmetic calculations explicitly. For example, to calculate the number days from milliseconds, the following statement would work:

    long days = TimeUnit.MILLISECONDS.toDays(milliseconds);

For cases more advanced, where more finely grained durations need to be represented in the context of working with time, an all encompassing and modern date/time API should be used. For JDK8+, java.time is now included (here are the tutorials and javadocs). For earlier versions of Java joda-time is a solid alternative.

How do I properly escape quotes inside HTML attributes?

If you are using Javascript and Lodash, then you can use _.escape(), which escapes ", ', <, >, and &.

See here: https://lodash.com/docs/#escape

Should black box or white box testing be the emphasis for testers?

Here is my 5 cents:

As a developer, I mostly write tests for methods (in a class) as white box tests, simple because I do not want my test to break just because I change the inner works of my code.

I only want to my tests to break if my method behavior changes (e.g. returns a different result than before).

Over the last 20 years of development, I simple got tired of doing up-to double work just because my unit tests was strongly tied to the code and I need to maintain both application code and test code.

I think making decoupling code (also when you code tests) is a very good practice.

Another 5 cents: I hardly never use mocking frameworks, because when I find it necessarily to mock something I prefer to decouple my code instead - and yes in many cases that is very possible (especially if you are not working in legacy code) :-)

How can I make a time delay in Python?

There are five methods which I know: time.sleep(), pygame.time.wait(), matplotlib's pyplot.pause(), .after(), and asyncio.sleep().


time.sleep() example (do not use if using tkinter):

import time
print('Hello')
time.sleep(5) # Number of seconds
print('Bye')

pygame.time.wait() example (not recommended if you are not using the pygame window, but you could exit the window instantly):

import pygame
# If you are going to use the time module
# don't do "from pygame import *"
pygame.init()
print('Hello')
pygame.time.wait(5000) # Milliseconds
print('Bye')

matplotlib's function pyplot.pause() example (not recommended if you are not using the graph, but you could exit the graph instantly):

import matplotlib
print('Hello')
matplotlib.pyplot.pause(5) # Seconds
print('Bye')

The .after() method (best with Tkinter):

import tkinter as tk # Tkinter for Python&nbsp;2
root = tk.Tk()
print('Hello')
def ohhi():
    print('Oh, hi!')
root.after(5000, ohhi) # Milliseconds and then a function
print('Bye')

Finally, the asyncio.sleep() method:

import asyncio
asyncio.sleep(5)

How to find the first and second maximum number?

OK I found it.

=LARGE($E$4:$E$9;A12)

=large(array, k)

Array Required. The array or range of data for which you want to determine the k-th largest value.

K Required. The position (from the largest) in the array or cell range of data to return.

Node.js: how to consume SOAP XML web service

For those who are new to SOAP and want a quick explanation and guide, I strongly recommend this awesome medium article.

You can also use node-soap package, with this simple tutorial.

How to import the class within the same directory or sub directory?

to import from the same directory

from . import the_file_you_want_to_import 

to import from sub directory the directory should contain

init.py

file other than you files then

from directory import your_file

Invalid application path

The error message might be a bug. I ignored it and everything worked for me.

IIS Invalid Application Path Screen Shot

See Here: http://forums.iis.net/t/1177952.aspx

and here http://forums.iis.net/p/1182820/2000936.aspx

What does the "at" (@) symbol do in Python?

If you are referring to some code in a python notebook which is using Numpy library, then @ operator means Matrix Multiplication. For example:

import numpy as np
def forward(xi, W1, b1, W2, b2):
    z1 = W1 @ xi + b1
    a1 = sigma(z1)
    z2 = W2 @ a1 + b2
    return z2, a1

Get selected element's outer HTML

2014 Edit : The question and this reply are from 2010. At the time, no better solution was widely available. Now, many of the other replies are better : Eric Hu's, or Re Capcha's for example.

This site seems to have a solution for you : jQuery: outerHTML | Yelotofu

jQuery.fn.outerHTML = function(s) {
    return s
        ? this.before(s).remove()
        : jQuery("<p>").append(this.eq(0).clone()).html();
};

Drag and drop elements from list into separate blocks

I wrote some test code to check JQueryUI drag/drop. The example shows how to drag an element from a container and drop it to another container.

Markup-

<div class="row">
    <div class="col-xs-3">
      <div class="panel panel-default">
        <div class="panel-heading">
          <h1 class="panel-title">Panel 1</h1>
        </div>
        <div id="container1" class="panel-body box-container">
          <div itemid="itm-1" class="btn btn-default box-item">Item 1</div>
          <div itemid="itm-2" class="btn btn-default box-item">Item 2</div>
          <div itemid="itm-3" class="btn btn-default box-item">Item 3</div>
          <div itemid="itm-4" class="btn btn-default box-item">Item 4</div>
          <div itemid="itm-5" class="btn btn-default box-item">Item 5</div>
        </div>
      </div>
    </div>
    <div class="col-xs-3">
      <div class="panel panel-default">
        <div class="panel-heading">
          <h1 class="panel-title">Panel 2</h1>
        </div>
        <div id="container2" class="panel-body box-container"></div>
      </div>
    </div>
  </div>

JQuery codes-

$(document).ready(function() {

$('.box-item').draggable({
    cursor: 'move',
    helper: "clone"
});

$("#container1").droppable({
  drop: function(event, ui) {
    var itemid = $(event.originalEvent.toElement).attr("itemid");
    $('.box-item').each(function() {
      if ($(this).attr("itemid") === itemid) {
        $(this).appendTo("#container1");
      }
    });
  }
});

$("#container2").droppable({
  drop: function(event, ui) {
    var itemid = $(event.originalEvent.toElement).attr("itemid");
    $('.box-item').each(function() {
      if ($(this).attr("itemid") === itemid) {
        $(this).appendTo("#container2");
      }
    });
  }
});

});

CSS-

.box-container {
    height: 200px;
}

.box-item {
    width: 100%;
    z-index: 1000
}

Check the plunker JQuery Drag Drop

Allow access permission to write in Program Files of Windows 7

If you have such a program just install it in C:\, not in Program Files. I had a lot of problems when I was installing Android SDK. My problem got solved by installing it in C:\.

What steps are needed to stream RTSP from FFmpeg?

FWIW, I was able to setup a local RTSP server for testing purposes using simple-rtsp-server and ffmpeg following these steps:

  1. Create a configuration file for the RTSP server called rtsp-simple-server.yml with this single line:
    protocols: [tcp]
    
  2. Start the RTSP server as a Docker container:
    $ docker run --rm -it -v $PWD/rtsp-simple-server.yml:/rtsp-simple-server.yml -p 8554:8554 aler9/rtsp-simple-server
    
  3. Use ffmpeg to stream a video file (looping forever) to the server:
    $ ffmpeg -re -stream_loop -1 -i test.mp4 -f rtsp -rtsp_transport tcp rtsp://localhost:8554/live.stream
    

Once you have that running you can use ffplay to view the stream:

$ ffplay -rtsp_transport tcp rtsp://localhost:8554/live.stream

Note that simple-rtsp-server can also handle UDP streams (i.s.o. TCP) but that's tricky running the server as a Docker container.

How to use XPath contains() here?

//ul[@class="featureList" and li//text()[contains(., "Model")]]

How should strace be used?

Strace Overview
strace can be seen as a light weight debugger. It allows a programmer / user to quickly find out how a program is interacting with the OS. It does this by monitoring system calls and signals.

Uses
Good for when you don't have source code or don't want to be bothered to really go through it.
Also, useful for your own code if you don't feel like opening up GDB, but are just interested in understanding external interaction.

A good little introduction
I ran into this intro to strace use just the other day: strace hello world

Reading RFID with Android phones

You can use a simple, low-cost USB port reader like this test connects directly to your Android device; it has a utility app and an SDK you can use for app development: https://www.atlasrfidstore.com/sls-rfid-smartmicro-android-micro-usb-reader/

<ng-container> vs <template>

Edit : Now it is documented

<ng-container> to the rescue

The Angular <ng-container> is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.

(...)

The <ng-container> is a syntax element recognized by the Angular parser. It's not a directive, component, class, or interface. It's more like the curly braces in a JavaScript if-block:

  if (someCondition) {
      statement1; 
      statement2;
      statement3;
     }

Without those braces, JavaScript would only execute the first statement when you intend to conditionally execute all of them as a single block. The <ng-container> satisfies a similar need in Angular templates.

Original answer:

According to this pull request :

<ng-container> is a logical container that can be used to group nodes but is not rendered in the DOM tree as a node.

<ng-container> is rendered as an HTML comment.

so this angular template :

<div>
    <ng-container>foo</ng-container>
<div>

will produce this kind of output :

<div>
    <!--template bindings={}-->foo
<div>

So ng-container is useful when you want to conditionaly append a group of elements (ie using *ngIf="foo") in your application but don't want to wrap them with another element.

<div>
    <ng-container *ngIf="true">
        <h2>Title</h2>
        <div>Content</div>
    </ng-container>
</div>

will then produce :

<div>
    <h2>Title</h2>
    <div>Content</div>
</div>

SQL ORDER BY date problem

this should work for your date format

order by convert(date, your_column, 104) desc

Python spacing and aligning strings

You should be able to use the format method:

"Location: {0:20} Revision {1}".format(Location,Revision)

You will have to figure out the of the format length for each line depending on the length of the label. The User line will need a wider format width than the Location or District lines.

Two onClick actions one button

Give your button an id something like this:


<input id="mybutton" type="button" value="Dont show this again! " />

Then use jquery (to make this unobtrusive) and attach click action like so:


$(document).ready(function (){
    $('#mybutton').click(function (){
       fbLikeDump();
       WriteCookie();
    });
});

(this part should be in your .js file too)

I should have mentioned that you will need the jquery libraries on your page, so right before your closing body tag add these:


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://PATHTOYOURJSFILE"></script>

The reason to add just before body closing tag is for performance of perceived page loading times

Allow anonymous authentication for a single folder in web.config?

To make it work I build my directory like this:

Project Public Restrict

So I edited my webconfig for my public folder:

<location path="Project/Public">
    <system.web>
      <authorization>
        <allow users="?"/>
      </authorization>
    </system.web>
  </location>

And for my Restricted folder:

 <location path="Project/Restricted">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorizatio>
    </system.web>
  </location>

See here for the spec of * and ?:

https://docs.microsoft.com/en-us/iis/configuration/system.webserver/security/authorization/add

I hope I have helped.

How to open the Chrome Developer Tools in a new window?

You have to click and hold until the other icon shows up, then slide the mouse down to the icon.

Regex match digits, comma and semicolon?

word.matches("^[0-9,;]+$"); you were almost there

Python equivalent of a given wget command

For Windows and Python 3.x, my two cents contribution about renaming the file on download :

  1. Install wget module : pip install wget
  2. Use wget :
import wget
wget.download('Url', 'C:\\PathToMyDownloadFolder\\NewFileName.extension')

Truely working command line example :

python -c "import wget; wget.download(""https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.17.2.tar.xz"", ""C:\\Users\\TestName.TestExtension"")"

Note : 'C:\\PathToMyDownloadFolder\\NewFileName.extension' is not mandatory. By default, the file is not renamed, and the download folder is your local path.

Installing Java 7 on Ubuntu

In addition to flup's answer you might also want to run the following to set JAVA_HOME and PATH:

sudo apt-get install oracle-java7-set-default

More information at: http://www.ubuntuupdates.org/package/webupd8_java/precise/main/base/oracle-java7-set-default

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

Here is the jQuery Tools bug on GitHub. You can try one of the patches.

edit — it doesn't look to me as if jQuery Tools is getting much support. I personally would not begin a new project with a dependency on that library unless I were prepared to take over support myself.

jQuery - Click event on <tr> elements with in a table and getting <td> element values

Try jQuery's delegate() function, like so:

$(document).ready(function(){
    $("div.custList table").delegate('tr', 'click', function() {
        alert("You clicked my <tr>!");
        //get <td> element values here!!??
    });
});

A delegate works in the same way as live() except that live() cannot be applied to chained items, whereas delegate() allows you to specify an element within an element to act on.

How to avoid the "divide by zero" error in SQL?

There is no magic global setting 'turn division by 0 exceptions off'. The operation has to to throw, since the mathematical meaning of x/0 is different from the NULL meaning, so it cannot return NULL. I assume you are taking care of the obvious and your queries have conditions that should eliminate the records with the 0 divisor and never evaluate the division. The usual 'gotcha' is than most developers expect SQL to behave like procedural languages and offer logical operator short-circuit, but it does NOT. I recommend you read this article: http://www.sqlmag.com/Articles/ArticleID/9148/pg/2/2.html

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

Where can I find "make" program for Mac OS X Lion?

Have you installed Xcode and the developer tools? I think make, along with gcc and friends, is installed with that and not before. Xcode 4.1 for Lion is free.

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

fig.add_subplot(ROW,COLUMN,POSITION)

  • ROW=number of rows
  • COLUMN=number of columns
  • POSITION= position of the graph you are plotting

Examples

`fig.add_subplot(111)` #There is only one subplot or graph  
`fig.add_subplot(211)`  *and*  `fig.add_subplot(212)` 

There are total 2 rows,1 column therefore 2 subgraphs can be plotted. Its location is 1st. There are total 2 rows,1 column therefore 2 subgraphs can be plotted.Its location is 2nd

How to detect simple geometric shapes using OpenCV

You can also use template matching to detect shapes inside an image.

find all the name using mysql query which start with the letter 'a'

In MySQL use the '^' to identify you want to check the first char of the string then define the array [] of letters you want to check for.

Try This

SELECT * FROM artists WHERE name REGEXP '^[abc]'

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

All the above mentioned solutions to the problem are correct. But if you are using lazy loading, FormsModule needs to be imported in the child module which has forms in it. Adding it in app.module.ts won't help.

C#: Printing all properties of an object

You can use the TypeDescriptor class to do this:

foreach(PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
{
    string name=descriptor.Name;
    object value=descriptor.GetValue(obj);
    Console.WriteLine("{0}={1}",name,value);
}

TypeDescriptor lives in the System.ComponentModel namespace and is the API that Visual Studio uses to display your object in its property browser. It's ultimately based on reflection (as any solution would be), but it provides a pretty good level of abstraction from the reflection API.

Just disable scroll not hide it?

I had a similar problem: a left-hand menu that, when it appears, prevents scrolling. As soon as height was set to 100vh, the scrollbar disappeared and the content jerked to the right.

So if you don't mind keeping the scrollbar enabled (but setting the window to full height so it won't actually scroll anywhere) then another possibility is setting a tiny bottom margin, which will keep the scroll bars showing:

body {
    height: 100vh;
    overflow: hidden;
    margin: 0 0 1px;
}

Find IP address of directly connected device

To use DHCP, you'd have to run a DHCP server on the primary and a client on the secondary; the primary could then query the server to find out what address it handed out. Probably overkill.

I can't help you with Windows directly. On Unix, the "arp" command will tell you what IP addresses are known to be attached to the local ethernet segment. Windows will have this same information (since it's a core part of the IP/Ethernet interface) but I don't know how you get at it.

Of course, the networking stack will only know about the other host if it has previously seen traffic from it. You may have to first send a broadcast packet on the interface to elicit some sort of response and thus populate the local ARP table.

Find and kill a process in one line using bash and regex

In some cases, I'd like kill processes simutaneously like this way:

?  ~  sleep 1000 &
[1] 25410
?  ~  sleep 1000 &
[2] 25415
?  ~  sleep 1000 &
[3] 25421
?  ~  pidof sleep
25421 25415 25410
?  ~  kill `pidof sleep`
[2]  - 25415 terminated  sleep 1000                                                             
[1]  - 25410 terminated  sleep 1000
[3]  + 25421 terminated  sleep 1000

But, I think it is a little bit inappropriate in your case.(May be there are running python a, python b, python x...in the background.)

What is a Question Mark "?" and Colon ":" Operator Used for?

a=1;
b=2;

x=3;
y=4;

answer = a > b ? x : y;

answer=4 since the condition is false it takes y value.

A question mark (?)
. The value to use if the condition is true

A colon (:)
. The value to use if the condition is false

where does MySQL store database files?

In any case you can know it:

mysql> select @@datadir;
+----------------------------------------------------------------+
| @@datadir                                                      |
+----------------------------------------------------------------+
| D:\Documents and Settings\b394382\My Documents\MySQL_5_1\data\ |
+----------------------------------------------------------------+
1 row in set (0.00 sec)

Thanks Barry Galbraith from the MySql Forum http://forums.mysql.com/read.php?10,379153,379167#msg-379167