Programs & Examples On #Ajax push

Passing data between view controllers

You have to always follow the MVC concept when creating apps for iOS.

There are two scenarios where you may want to pass data from a ViewController to another:

  1. When there is an "A" ViewContoller in the hierarchy and you want to send some data to "B" which is the next viewcontroller. In this case you have to use Segue. Just set an identifier for the segue and then in the "A" VC, write the following code:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "A to B segue identifier" {
            let bViewController = segue.destination as! UIDocumentBrowserViewController
            bViewController.data = someData
        }
    }
    
  2. When there is an A which opened B upon itself as modal (or embed). Now the B viewcontroller should be blind about its parent. So the best way to send data back to A is to use Delegation.

    Create a delegate protocol in the B viewcontroller and a delegate property. So B will report (send data back) to it's delegate. In the A viewcontroller, we implement the B viewcontroller's delegate protocol and will set self as the delegate property of B viewcontroller in prepare(forSegue:) method.

This is how it should be implemented correctly.

Set a request header in JavaScript

W3C Spec on setrequestheader.

The brief points:

If the request header had already been set, then the new value MUST be concatenated to the existing value using a U+002C COMMA followed by a U+0020 SPACE for separation.

UAs MAY give the User-Agent header an initial value, but MUST allow authors to append values to it.

However - After searching through the framework XHR in jQuery they don't allow you to change the User-Agent or Referer headers. The closest thing:

// Set header so the called script knows that it's an XMLHttpRequest
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

I'm leaning towards the opinion that what you want to do is being denied by a security policy in FF - if you want to pass some custom Referer type header you could always do:

xhr.setRequestHeader('X-Alt-Referer', 'http://www.google.com');

Integrity constraint violation: 1452 Cannot add or update a child row:

First delete the constraint "fk_comments_projects1" and also its index. After that recreate it.

How to convert Json array to list of objects in c#

You may use Json.Net framework to do this. Just like this :

Account account = JsonConvert.DeserializeObject<Account>(json);

the home page : http://json.codeplex.com/

the document about this : http://james.newtonking.com/json/help/index.html#

How to take the nth digit of a number in python

Here's my take on this problem.

I have defined a function 'index' which takes the number and the input index and outputs the digit at the desired index.

The enumerate method operates on the strings, therefore the number is first converted to a string. Since the indexing in Python starts from zero, but the desired functionality requires it to start with 1, therefore a 1 is placed in the enumerate function to indicate the start of the counter.

def index(number, i):

    for p,num in enumerate(str(number),1):

        if p == i:
            print(num)

What are Covering Indexes and Covered Queries in SQL Server?

If all the columns requested in the select list of query, are available in the index, then the query engine doesn't have to lookup the table again which can significantly increase the performance of the query. Since all the requested columns are available with in the index, the index is covering the query. So, the query is called a covering query and the index is a covering index.

A clustered index can always cover a query, if the columns in the select list are from the same table.

The following links can be helpful, if you are new to index concepts:

List files with certain extensions with ls and grep

the easiest way is to just use ls

ls *.mp4 *.mp3 *.exe

Find the last element of an array while using a foreach loop in PHP

You could also try this to make your query... shown here with INSERT

<?php
 $week=array('one'=>'monday','two'=>'tuesday','three'=>'wednesday','four'=>'thursday','five'=>'friday','six'=>'saturday','seven'=>'sunday');
 $keys = array_keys($week);
 $string = "INSERT INTO my_table ('";
 $string .= implode("','", $keys);
 $string .= "') VALUES ('";
 $string .= implode("','", $week);
 $string .= "');";
 echo $string;
?>

JPA: how do I persist a String into a database field, type MYSQL Text

Since you're using JPA, use the Lob annotation (and optionally the Column annotation). Here is what the JPA specification says about it:

9.1.19 Lob Annotation

A Lob annotation specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use the Lob annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with the Basic annotation. A Lob may be either a binary or character type. The Lob type is inferred from the type of the persistent field or property, and except for string and character-based types defaults to Blob.

So declare something like this:

@Lob 
@Column(name="CONTENT", length=512)
private String content;

References

  • JPA 1.0 specification:
    • Section 9.1.19 "Lob Annotation"

How to get first and last day of the current week in JavaScript

You can also use following lines of code to get first and last date of the week:

var curr = new Date;
var firstday = new Date(curr.setDate(curr.getDate() - curr.getDay()));
var lastday = new Date(curr.setDate(curr.getDate() - curr.getDay()+6));

Hope it will be useful..

Git remote branch deleted, but still it appears in 'branch -a'

Try:

git remote prune origin

From the Git remote documentation:

prune

Deletes all stale remote-tracking branches under <name>. These stale branches have already been removed from the remote repository referenced by <name>, but are still locally available in "remotes/<name>".

With --dry-run option, report what branches will be pruned, but do not actually prune them.

JAVA_HOME is set to an invalid directory:

Remove the \bin, and also remove the ; at the end. After restart the cmd and run.

String isNullOrEmpty in Java?

public static boolean isNull(String str) {
        return str == null ? true : false;
    }

    public static boolean isNullOrBlank(String param) {
        if (isNull(param) || param.trim().length() == 0) {
            return true;
        }
        return false;
    }

Whats the CSS to make something go to the next line in the page?

Have the element display as a block:

display: block;

Python string to unicode

Decode it with the unicode-escape codec:

>>> a="Hello\u2026"
>>> a.decode('unicode-escape')
u'Hello\u2026'
>>> print _
Hello…

This is because for a non-unicode string the \u2026 is not recognised but is instead treated as a literal series of characters (to put it more clearly, 'Hello\\u2026'). You need to decode the escapes, and the unicode-escape codec can do that for you.

Note that you can get unicode to recognise it in the same way by specifying the codec argument:

>>> unicode(a, 'unicode-escape')
u'Hello\u2026'

But the a.decode() way is nicer.

Deserialize json object into dynamic object using Json.net

If you just deserialize to dynamic you will get a JObject back. You can get what you want by using an ExpandoObject.

var converter = new ExpandoObjectConverter();    
dynamic message = JsonConvert.DeserializeObject<ExpandoObject>(jsonString, converter);

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

Upgrade MySql driver to Connector/Python 8.0.17 or greater than 8.0.17, Those who are using greater than MySQL 5.5 version

iOS: Multi-line UILabel in Auto Layout

None of the different solutions found in the many topics on the subject worked perfectly for my case (x dynamic multiline labels in dynamic table view cells) .

I found a way to do it :

After having set the constraints on your label and set its multiline property to 0, make a subclass of UILabel ; I called mine AutoLayoutLabel :

@implementation AutoLayoutLabel

- (void)layoutSubviews{
    [self setNeedsUpdateConstraints];
    [super layoutSubviews];
    self.preferredMaxLayoutWidth = CGRectGetWidth(self.bounds);
}

@end

redirect to current page in ASP.Net

http://en.wikipedia.org/wiki/Post/Redirect/Get

The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)

Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.

Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.

How to sort a collection by date in MongoDB?

Sushant Gupta's answers are a tad bit outdated and don't work anymore.

The following snippet should be like this now :

collection.find({}, {"sort" : ['datefield', 'asc']} ).toArray(function(err,docs) {});

How do you round a number to two decimal places in C#?

Try this:

twoDec = Math.Round(val, 2)

How can I convert uppercase letters to lowercase in Notepad++

Just select the text you want to change, right click and select UPPERCASE or lowercase depending on what you want.

SQL MAX of multiple columns?

If you're using MySQL, you can use

SELECT GREATEST(col1, col2 ...) FROM table

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

As @kirbyfan64sos notes in a comment, /home is NOT your home directory (a.k.a. home folder):

The fact that /home is an absolute, literal path that has no user-specific component provides a clue.

While /home happens to be the parent directory of all user-specific home directories on Linux-based systems, you shouldn't even rely on that, given that this differs across platforms: for instance, the equivalent directory on macOS is /Users.

What all Unix platforms DO have in common are the following ways to navigate to / refer to your home directory:

  • Using cd with NO argument changes to your home dir., i.e., makes your home dir. the working directory.
    • e.g.: cd # changes to home dir; e.g., '/home/jdoe'
  • Unquoted ~ by itself / unquoted ~/ at the start of a path string represents your home dir. / a path starting at your home dir.; this is referred to as tilde expansion (see man bash)
    • e.g.: echo ~ # outputs, e.g., '/home/jdoe'
  • $HOME - as part of either unquoted or preferably a double-quoted string - refers to your home dir. HOME is a predefined, user-specific environment variable:
    • e.g.: cd "$HOME/tmp" # changes to your personal folder for temp. files

Thus, to create the desired folder, you could use:

mkdir "$HOME/bin"  # same as: mkdir ~/bin

Note that most locations outside your home dir. require superuser (root user) privileges in order to create files or directories - that's why you ran into the Permission denied error.

TypeError: 'NoneType' object has no attribute '__getitem__'

BrenBarn is correct. The error means you tried to do something like None[5]. In the backtrace, it says self.imageDef=self.values[2], which means that your self.values is None.

You should go through all the functions that update self.values and make sure you account for all the corner cases.

How do I drop a MongoDB database from the command line?

Drop a MongoDB database using python:

import argparse

import pymongo


if __name__ == "__main__":
    """
    Drop a Database.
    """

    parser = argparse.ArgumentParser()
    parser.add_argument("--host", default='mongodb://localhost:27017',
                        help="mongodb URI [default: %(default)s]")
    parser.add_argument("--database", default=None,
                        help="database name: %(default)s]")

    args = parser.parse_args()

    client = pymongo.MongoClient(host=args.host)

    if args.database in client.list_database_names():
        client.drop_database(args.database)
        print(f"Dropped: '{args.database}'")
    else:
        print(f"Database '{args.database}' does not exist")

Why does PEP-8 specify a maximum line length of 79 characters?

I believe those who study typography would tell you that 66 characters per a line is supposed to be the most readable width for length. Even so, if you need to debug a machine remotely over an ssh session, most terminals default to 80 characters, 79 just fits, trying to work with anything wider becomes a real pain in such a case. You would also be suprised by the number of developers using vim + screen as a day to day environment.

Removing the fragment identifier from AngularJS urls (# symbol)

Guess this is reallllly late for this. But adding the below config to the app.module imports does the job:

RouterModule.forRoot(routes, { useHash: false })

What and When to use Tuple?

Tuple classes allow developers to be 'quick and lazy' by not defining a specific class for a specific use.

The property names are Item1, Item2, Item3 ..., which may not be meaningful in some cases or without documentation.

Tuple classes have strongly typed generic parameters. Still users of the Tuple classes may infer from the type of generic parameters.

Hadoop cluster setup - java.net.ConnectException: Connection refused

Make sure HDFS is online. Start it by $HADOOP_HOME/sbin/start-dfs.sh Once you do that, your test with telnet localhost 9001should work.

Beautiful Soup and extracting a div and its contents by ID

Here is a code fragment

soup = BeautifulSoup(:"index.html")
titleList = soup.findAll('title')
divList = soup.findAll('div', attrs={ "class" : "article story"})

As you can see I find all tags and then I find all tags with class="article" inside

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

In my case I had a ucfirst on the asian letters string. This was not possible and produced a non utf8 string.

Should I use Vagrant or Docker for creating an isolated environment?

Vagrant-lxc is a plugin for Vagrant that let's you use LXC to provision Vagrant. It does not have all the features that the default vagrant VM (VirtualBox) has but it should allow you more flexibility than docker containers. There is a video in the link showing its capabilities that is worth watching.

Using helpers in model: how do I include helper dependencies?

To access helpers from your own controllers, just use:

OrdersController.helpers.order_number(@order)

Rules for C++ string literals escape character

Control characters:

(Hex codes assume an ASCII-compatible character encoding.)

  • \a = \x07 = alert (bell)
  • \b = \x08 = backspace
  • \t = \x09 = horizonal tab
  • \n = \x0A = newline (or line feed)
  • \v = \x0B = vertical tab
  • \f = \x0C = form feed
  • \r = \x0D = carriage return
  • \e = \x1B = escape (non-standard GCC extension)

Punctuation characters:

  • \" = quotation mark (backslash not required for '"')
  • \' = apostrophe (backslash not required for "'")
  • \? = question mark (used to avoid trigraphs)
  • \\ = backslash

Numeric character references:

  • \ + up to 3 octal digits
  • \x + any number of hex digits
  • \u + 4 hex digits (Unicode BMP, new in C++11)
  • \U + 8 hex digits (Unicode astral planes, new in C++11)

\0 = \00 = \000 = octal ecape for null character

If you do want an actual digit character after a \0, then yes, I recommend string concatenation. Note that the whitespace between the parts of the literal is optional, so you can write "\0""0".

What does the "static" modifier after "import" mean?

The static modifier after import is for retrieving/using static fields of a class. One area in which I use import static is for retrieving constants from a class. We can also apply import static on static methods. Make sure to type import static because static import is wrong.

What is static import in Java - JavaRevisited - A very good resource to know more about import static.

R memory management / cannot allocate vector of size n Mb

If you are running your script at linux environment you can use this command:

bsub -q server_name -R "rusage[mem=requested_memory]" "Rscript script_name.R"

and the server will allocate the requested memory for you (according to the server limits, but with good server - hugefiles can be used)

JavaScript for handling Tab Key press

Having following html:

<!-- note that not all browsers focus on links when Tab is pressed -->
<a href="http://example.com">Link</a>

<input type="text" placeholder="Some input" />
<a href="http://example.com">Another Link</a>

<textarea>...</textarea>

You can get to active link with:

// event listener for keyup
function checkTabPress(e) {
    "use strict";
    // pick passed event or global event object if passed one is empty
    e = e || event;
    var activeElement;
    if (e.keyCode == 9) {
        // Here read the active selected link.
        activeElement = document.activeElement;
        // If HTML element is an anchor <a>
        if (activeElement.tagName.toLowerCase() == 'a')
            // get it's hyperlink
            alert(activeElement.href);
    }
}

var body = document.querySelector('body');
body.addEventListener('keyup', checkTabPress);

Here is working example.

cast or convert a float to nvarchar?

You can also do something:

SELECT CAST(CAST(34512367.392 AS decimal(30,9)) AS NVARCHAR(100))

Output: 34512367.392000000

How to get the date 7 days earlier date from current date in Java

Use the Calendar-API:

// get Calendar instance
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());

// substract 7 days
// If we give 7 there it will give 8 days back
cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)-6);

// convert to date
Date myDate = cal.getTime();

Hope this helps. Have Fun!

Serialize and Deserialize Json and Json Array in Unity

Like @Maximiliangerhardt said, MiniJson do not have the capability to deserialize properly. I used JsonFx and works like a charm. Works with the []

player[] p = JsonReader.Deserialize<player[]>(serviceData);
Debug.Log(p[0].playerId +" "+ p[0].playerLoc+"--"+ p[1].playerId + " " + p[1].playerLoc+"--"+ p[2].playerId + " " + p[2].playerLoc);

Set selected radio from radio group with a value

var key = "Name_radio";
var val = "value_radio";
var rdo = $('*[name="' + key + '"]');
if (rdo.attr('type') == "radio") {
 $.each(rdo, function (keyT, valT){
   if ((valT.value == $.trim(val)) && ($.trim(val) != '') && ($.trim(val) != null))

   {
     $('*[name="' + key + '"][value="' + (val) + '"]').prop('checked', true);
   }
  })
}

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

How do I get the serial key for Visual Studio Express?

The question is about VS 2008 Express.

Microsoft's web page for registering Visual Studio 2008 Express has been dead (404) for some time, so registering it is not possible.

Instead, as a workaround, you can temporarily remove the requirement to register VS2008Exp by deleting (or renaming) the registry key:

HKEY_CURRENT_USER/Software/Microsoft/VCExpress/9.0/Registration

To ensure that this is working beforehand, click Help -> register product within VS2008.

You should see text like

"You have not yet registered your copy of Visual C++ 2008 Express Edition. This product will run for 10 more days before you will be required to register it."

Close the application, delete that key, reopen, click help->register product.

The text should now say

"You have not yet registered your copy of Visual C++ 2008 Express Edition. This product will run for 30 more days before you will be required to register it."

So you have two options - delete that key manually every 30 days, or run it from a batch file that also contains a line like:

reg delete HKCU\Software\Microsoft\VCExpress\9.0\Registration /f

[Edit: User @i486 confirms on testing that this workaround works even after the expiration period has expired]

[Edit2: User @Wyatt8740 has a much more elegant way to prevent the value from reappearing.]

How to insert logo with the title of a HTML page?

Yes you right and I just want to make it understandable for complete beginners.

  1. Create favicon.ico file you want to be shown next to your url in browsers tab. You can do that online. I used http://www.prodraw.net/favicon/generator.php it worked juts fine.
  2. Save generated ico file in your web site root directory /images (yourwebsite/images) under the name favicon.ico.
  3. Copy this tag <link rel="shortcut icon" href="images/favicon.ico" /> and past it without any changes in between <head> opening and </head> closing tag.
  4. Save changes in your html file and reload your browser.

JSON formatter in C#?

Fixed it... somewhat.

public class JsonFormatter
{
    #region class members
    const string Space = " ";
    const int DefaultIndent = 0;
    const string Indent = Space + Space + Space + Space;
    static readonly string NewLine = Environment.NewLine;
    #endregion

    private enum JsonContextType
    {
        Object, Array
    }

    static void BuildIndents(int indents, StringBuilder output)
    {
        indents += DefaultIndent;
        for (; indents > 0; indents--)
            output.Append(Indent);
    }


    bool inDoubleString = false;
    bool inSingleString = false;
    bool inVariableAssignment = false;
    char prevChar = '\0';

    Stack<JsonContextType> context = new Stack<JsonContextType>();

    bool InString()
    {
        return inDoubleString || inSingleString;
    }

    public string PrettyPrint(string input)
    {
        var output = new StringBuilder(input.Length * 2);
        char c;

        for (int i = 0; i < input.Length; i++)
        {
            c = input[i];

            switch (c)
            {
                case '{':
                    if (!InString())
                    {
                        if (inVariableAssignment || (context.Count > 0 && context.Peek() != JsonContextType.Array))
                        {
                            output.Append(NewLine);
                            BuildIndents(context.Count, output);
                        }
                        output.Append(c);
                        context.Push(JsonContextType.Object);
                        output.Append(NewLine);
                        BuildIndents(context.Count, output);
                    }
                    else
                        output.Append(c);

                    break;

                case '}':
                    if (!InString())
                    {
                        output.Append(NewLine);
                        context.Pop();
                        BuildIndents(context.Count, output);
                        output.Append(c);
                    }
                    else
                        output.Append(c);

                    break;

                case '[':
                    output.Append(c);

                    if (!InString())
                        context.Push(JsonContextType.Array);

                    break;

                case ']':
                    if (!InString())
                    {
                        output.Append(c);
                        context.Pop();
                    }
                    else
                        output.Append(c);

                    break;

                case '=':
                    output.Append(c);
                    break;

                case ',':
                    output.Append(c);

                    if (!InString() && context.Peek() != JsonContextType.Array)
                    {
                        BuildIndents(context.Count, output);
                        output.Append(NewLine);
                        BuildIndents(context.Count, output);
                        inVariableAssignment = false;
                    }

                    break;

                case '\'':
                    if (!inDoubleString && prevChar != '\\')
                        inSingleString = !inSingleString;

                    output.Append(c);
                    break;

                case ':':
                    if (!InString())
                    {
                        inVariableAssignment = true;
                        output.Append(Space);
                        output.Append(c);
                        output.Append(Space);
                    }
                    else
                        output.Append(c);

                    break;

                case '"':
                    if (!inSingleString && prevChar != '\\')
                        inDoubleString = !inDoubleString;

                    output.Append(c);
                    break;
                case ' ':
                    if (InString())
                        output.Append(c);
                    break;

                default:
                    output.Append(c);
                    break;
            }
            prevChar = c;
        }

        return output.ToString();
    }
}

credit [dead link]

Convert generator object to list for debugging

Simply call list on the generator.

lst = list(gen)
lst

Be aware that this affects the generator which will not return any further items.

You also cannot directly call list in IPython, as it conflicts with a command for listing lines of code.

Tested on this file:

def gen():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
import ipdb
ipdb.set_trace()

g1 = gen()

text = "aha" + "bebe"

mylst = range(10, 20)

which when run:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.

General method for escaping function/variable/debugger name conflicts

There are debugger commands p and pp that will print and prettyprint any expression following them.

So you could use it as follows:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c

There is also an exec command, called by prefixing your expression with !, which forces debugger to take your expression as Python one.

ipdb> !list(g1)
[]

For more details see help p, help pp and help exec when in debugger.

ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']

Determine the number of NA values in a column

If you are looking for NA counts for each column in a dataframe then:

na_count <-sapply(x, function(y) sum(length(which(is.na(y)))))

should give you a list with the counts for each column.

na_count <- data.frame(na_count)

Should output the data nicely in a dataframe like:

----------------------
| row.names | na_count
------------------------
| column_1  | count

Query to check index on a table

Created a stored procedure to list indexes for a table in database in SQL Server

create procedure _ListIndexes(@tableName nvarchar(200))
as
begin
/*
exec _ListIndexes '<YOUR TABLE NAME>'
*/
SELECT DB_NAME(DB_ID()) as DBName,SCH.name + '.' + TBL.name AS TableName,IDX.name as IndexName, IDX.type_desc AS IndexType,COL.Name as ColumnName,IC.*
    FROM sys.tables AS TBL 
         INNER JOIN sys.schemas AS SCH ON TBL.schema_id = SCH.schema_id 
         INNER JOIN sys.indexes AS IDX ON TBL.object_id = IDX.object_id 
         INNER JOIN sys.index_columns IC ON  IDX.object_id = IC.object_id and IDX.index_id = IC.index_id 
         INNER JOIN sys.columns COL ON ic.object_id = COL.object_id and IC.column_id = COL.column_id 
        where TBL.name = @tableName
    ORDER BY TableName,IDX.name

end

How do I get the Date & Time (VBS)

To expound on Numenor's answer you can do something like, Format(Now(),"HH:mm:ss") using these custom date/time formating options


For everyone who is tempted to downvote this answer please be aware that the question was originally tagged VB and vbscript hence my answer, the VB tag was edited out leaving only the vbscript tag. The OP accepted this answer which I take to mean that it gave him the information that he needed.

How to auto adjust the div size for all mobile / tablet display formats?

I use something like this in my document.ready

var height = $(window).height();//gets height from device
var width = $(window).width(); //gets width from device

$("#container").width(width+"px");
$("#container").height(height+"px");

How can I rotate an HTML <div> 90 degrees?

You need CSS to achieve this, e.g.:

#container_2 {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg);
}

Demo:

_x000D_
_x000D_
#container_2 {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  border: 1px solid red;_x000D_
  -webkit-transform: rotate(45deg);_x000D_
  -moz-transform: rotate(45deg);_x000D_
  -o-transform: rotate(45deg);_x000D_
  -ms-transform: rotate(45deg);_x000D_
  transform: rotate(45deg);_x000D_
}
_x000D_
<div id="container_2"></div>
_x000D_
_x000D_
_x000D_

(There's 45 degrees rotation in the demo, so you can see the effect)

Note: The -o- and -moz- prefixes are no longer relevant and probably not required. IE9 requires -ms- and Safari and the Android browser require -webkit-


Update 2018: Vendor prefixes are not needed anymore. Only transform is sufficient. (thanks @rinogo)

Local dependency in package.json

npm >= 2.0.0

This feature was implemented in the version 2.0.0 of npm. Example:

{
  "name": "baz",
  "dependencies": {
    "bar": "file:../foo/bar"
  }
}

Any of the following paths are also valid:

../foo/bar
~/foo/bar
./foo/bar
/foo/bar

The local package will be copied to the prefix (./node-modules).

npm < 2.0.0

Put somelocallib as dependency in your package.json as normal:

"dependencies": {
  "somelocallib": "0.0.x"
}

Then run npm link ../somelocallib and npm will install the version you're working on as a symlink.

[email protected] /private/tmp/app
+-- [email protected] -> /private/tmp/somelocallib

Reference: link(1)

How do I convert a Django QuerySet into list of dicts?

If you need native data types for some reason (e.g. JSON serialization) this is my quick 'n' dirty way to do it:

data = [{'id': blog.pk, 'name': blog.name} for blog in blogs]

As you can see building the dict inside the list is not really DRY so if somebody knows a better way ...

Normalize numpy array columns in python

You can use sklearn.preprocessing:

from sklearn.preprocessing import normalize
data = np.array([
    [1000, 10, 0.5],
    [765, 5, 0.35],
    [800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1.     1.     1.   ]
[ 0.765  0.5    0.7  ]
[ 0.8    0.7    0.18 ]]

set the iframe height automatically

Solomon's answer about bootstrap inspired me to add the CSS the bootstrap solution uses, which works really well for me.

.iframe-embed {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    height: 100%;
    width: 100%;
    border: 0;
}
.iframe-embed-wrapper {
    position: relative;
    display: block;
    height: 0;
    padding: 0;
    overflow: hidden;
}
.iframe-embed-responsive-16by9 {
    padding-bottom: 56.25%;
}
<div class="iframe-embed-wrapper iframe-embed-responsive-16by9">
    <iframe class="iframe-embed" src="vid.mp4"></iframe>
</div>

Fully change package name including company domain

You can do this:

Change the package name manually in the manifest file. Click on your R.java class and the press F6 (Refactor->Move...). It will allow you to move the class to other package, and all references to that class will be updated.

reference: How do I rename the android package name?

UML diagram shapes missing on Visio 2013

I think because it's Standard's ver.

I don't know if you write your code in VS. But if you did, just go to ARCHITECTURE - new Diagram. & choose yours, & the VS 'll take the care of the rest :)

grant remote access of MySQL database from any IP address

For anyone who fumbled with this, here is how I got to grant the privileges, hope it helps someone

GRANT ALL ON yourdatabasename.* TO root@'%' IDENTIFIED BY
'yourRootPassword';

As noted % is a wildcard and this will allow any IP address to connect to your database. The assumption I make here is when you connect you'll have a user named root (which is the default though). Feed in the root password and you are good to go. Note that I have no single quotes (') around the user root.

How to iterate through SparseArray?

The answer is no because SparseArray doesn't provide it. As pst put it, this thing doesn't provide any interfaces.

You could loop from 0 - size() and skip values that return null, but that is about it.

As I state in my comment, if you need to iterate use a Map instead of a SparseArray. For example, use a TreeMap which iterates in order by the key.

TreeMap<Integer, MyType>

Faster way to zero memory than with memset?

If I remember correctly (from a couple of years ago), one of the senior developers was talking about a fast way to bzero() on PowerPC (specs said we needed to zero almost all the memory on power up). It might not translate well (if at all) to x86, but it could be worth exploring.

The idea was to load a data cache line, clear that data cache line, and then write the cleared data cache line back to memory.

For what it is worth, I hope it helps.

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

Configurations above didn't work for me. I tried a lot of combinations of keys, this one work fine:

enter image description here

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>mydomain.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <false/>
        </dict>
    </dict>
</dict>

Find indices of elements equal to zero in a NumPy array

If you are working with a one-dimensional array there is a syntactic sugar:

>>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])
>>> numpy.flatnonzero(x == 0)
array([1, 3, 5])

Proper use of errors

The convention for out of range in JavaScript is using RangeError. To check the type use if / else + instanceof starting at the most specific to the most generic

try {
    throw new RangeError();
}
catch (e){
    if (e instanceof RangeError){
        console.log('out of range');
    } else { 
        throw; 
    }
}

Error to run Android Studio

Check if your Java JDK is installed correctly

dpkg --list | grep -i jdk

If not, install JDK

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update && sudo apt-get install oracle-java8-installer

After the installation you have to enable the jdk

update-alternatives --display java

Check if Ubuntu uses Java JDK 8

java -version

If all went right the answer should be something like this:

java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)

Check what compiler is used

javac -version

It should show something like this

javac 1.8.0_91

Finally, add JAVA_HOME to the environment variable

Edit /etc/environment and add JAVA_HOME=/usr/lib/jvm/java-8-oracle to the end of the file

sudo nano /etc/environment

Append to the end of the file

JAVA_HOME=/usr/lib/jvm/java-8-oracle

You will then have to reboot, you can do this from the terminal with:

sudo reboot

In case you want to remove the JDK

sudo apt-get remove oracle-java8-installer

JavaScript Nested function

It is called closure.

Basically, the function defined within other function is accessible only within this function. But may be passed as a result and then this result may be called.

It is a very powerful feature. You can see more explanation here:

javascript_closures_for_dummies.html mirror on Archive.org

Add/remove HTML inside div using JavaScript

<!DOCTYPE html>
<html>
<head>
    <title>Dynamical Add/Remove Text Box</title>
    <script language="javascript">

        localStorage.i = Number(1);

        function myevent(action)
        {
            var i = Number(localStorage.i);
            var div = document.createElement('div');

            if(action.id == "add")
            {
                localStorage.i = Number(localStorage.i) + Number(1);
                var id = i;
                div.id = id;
                div.innerHTML = 'TextBox_'+id+': <input type="text" name="tbox_'+id+'"/>' + ' <input type="button" id='+id+' onclick="myevent(this)" value="Delete" />';

                document.getElementById('AddDel').appendChild(div);
            }
            else
            {
                var element = document.getElementById(action.id);
                element.parentNode.removeChild(element);
            }
        }
    </script>
</head>
<body>
    <fieldset>
    <legend>Dynamical Add / Remove Text Box</legend>
    <form>
        <div id="AddDel">
            Default TextBox:
            <input type="text" name="default_tb">
            <input type="button" id="add" onclick="myevent(this)" value="Add" />
        </div>
            <input type="button" type="submit" value="Submit Data" />
    </form>
    </fieldset>
</body>
</html>

What are database constraints?

Constraints are part of a database schema definition.

A constraint is usually associated with a table and is created with a CREATE CONSTRAINT or CREATE ASSERTION SQL statement.

They define certain properties that data in a database must comply with. They can apply to a column, a whole table, more than one table or an entire schema. A reliable database system ensures that constraints hold at all times (except possibly inside a transaction, for so called deferred constraints).

Common kinds of constraints are:

  • not null - each value in a column must not be NULL
  • unique - value(s) in specified column(s) must be unique for each row in a table
  • primary key - value(s) in specified column(s) must be unique for each row in a table and not be NULL; normally each table in a database should have a primary key - it is used to identify individual records
  • foreign key - value(s) in specified column(s) must reference an existing record in another table (via it's primary key or some other unique constraint)
  • check - an expression is specified, which must evaluate to true for constraint to be satisfied

How can I configure my makefile for debug and release builds?

You can use Target-specific Variable Values. Example:

CXXFLAGS = -g3 -gdwarf2
CCFLAGS = -g3 -gdwarf2

all: executable

debug: CXXFLAGS += -DDEBUG -g
debug: CCFLAGS += -DDEBUG -g
debug: executable

executable: CommandParser.tab.o CommandParser.yy.o Command.o
    $(CXX) -o output CommandParser.yy.o CommandParser.tab.o Command.o -lfl

CommandParser.yy.o: CommandParser.l 
    flex -o CommandParser.yy.c CommandParser.l
    $(CC) -c CommandParser.yy.c

Remember to use $(CXX) or $(CC) in all your compile commands.

Then, 'make debug' will have extra flags like -DDEBUG and -g where as 'make' will not.

On a side note, you can make your Makefile a lot more concise like other posts had suggested.

Babel 6 regeneratorRuntime is not defined

Alternatively, if you are not using a bundler like webpack or rollup, you could as a workaround just import the contents of https://raw.githubusercontent.com/facebook/regenerator/master/packages/regenerator-runtime/runtime.js using a plain old script tag in your index.html.

Not optimal, but in my case the only solution.

Datetime format Issue: String was not recognized as a valid DateTime

Your date time string doesn't contains any seconds. You need to reflect that in your format (remove the :ss).
Also, you need to specify H instead of h if you are using 24 hour times:

DateTime.ParseExact("04/30/2013 23:00", "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)

See here for more information:

Custom Date and Time Format Strings

Copy/Paste from Excel to a web page

Excel 2007 has a feature for doing this under the "Data" tab that works pretty nicely.

UIImageView aspect fit and center

You can achieve this by setting content mode of image view to UIViewContentModeScaleAspectFill.

Then use following method method to get the resized uiimage object.

- (UIImage*)setProfileImage:(UIImage *)imageToResize onImageView:(UIImageView *)imageView
{
    CGFloat width = imageToResize.size.width;
    CGFloat height = imageToResize.size.height;
    float scaleFactor;
    if(width > height)
    {
        scaleFactor = imageView.frame.size.height / height;
    }
    else
    {
        scaleFactor = imageView.frame.size.width / width;
    }

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), NO, 0.0);
    [imageToResize drawInRect:CGRectMake(0, 0, width * scaleFactor, height * scaleFactor)];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return resizedImage;
}

Edited Here (Swift Version)

func setProfileImage(imageToResize: UIImage, onImageView: UIImageView) -> UIImage
{
    let width = imageToResize.size.width
    let height = imageToResize.size.height

    var scaleFactor: CGFloat

    if(width > height)
    {
        scaleFactor = onImageView.frame.size.height / height;
    }
    else
    {
        scaleFactor = onImageView.frame.size.width / width;
    }

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), false, 0.0)
    imageToResize.drawInRect(CGRectMake(0, 0, width * scaleFactor, height * scaleFactor))
    let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return resizedImage;
}

Structure padding and packing

Padding and packing are just two aspects of the same thing:

  • packing or alignment is the size to which each member is rounded off
  • padding is the extra space added to match the alignment

In mystruct_A, assuming a default alignment of 4, each member is aligned on a multiple of 4 bytes. Since the size of char is 1, the padding for a and c is 4 - 1 = 3 bytes while no padding is required for int b which is already 4 bytes. It works the same way for mystruct_B.

Junit - run set up method once

My dirty solution is:

public class TestCaseExtended extends TestCase {

    private boolean isInitialized = false;
    private int serId;

    @Override
    public void setUp() throws Exception {
        super.setUp();
        if(!isInitialized) {
            loadSaveNewSerId();
            emptyTestResultsDirectory();
            isInitialized = true;
        }
    }

   ...

}

I use it as a base base to all my testCases.

Converting HTML element to string in JavaScript / JQuery

(document.body.outerHTML).constructor will return String. (take off .constructor and that's your string)

That aughta do it :)

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

Just to complement @maxkoryukov's answer regarding Alpine.

The equivalent to Debian's build-essential in Alpine is build-base. In fact, the above mentioned alpine-sdk depends on build-base.

/ # apk info -R build-base
build-base-0.5-r1 depends on:
binutils
file
gcc
g++
make
libc-dev
fortify-headers

/ # apk info -R alpine-sdk
alpine-sdk-1.0-r0 depends on:
abuild
build-base
git

Removing an activity from the history stack

Just call this.finish() before startActivity(intent) like this-

       Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
        this.finish();
        startActivity(intent);

How to load up CSS files using Javascript?

var elem = document.createElement('link');
elem.rel = ' stylesheet'
elem.href= 'style.css';//Link of the css file
document.head.appendChild(elem);

Database design for a survey

As a general rule, modifying schema based on something that a user could change (such as adding a question to a survey) should be considered fairly smelly. There's cases where it can be appropriate, particularly when dealing with large amounts of data, but know what you're getting into before you dive in. Having just a "responses" table for each survey means that adding or removing questions is potentially very costly, and it's very difficult to do analytics in a question-agnostic way.

I think your second approach is best, but if you're certain you're going to have a lot of scale concerns, one thing that has worked for me in the past is a hybrid approach:

  1. Create detailed response tables to store per-question responses as you've described in 2. This data would generally not be directly queried from your application, but would be used for generating summary data for reporting tables. You'd probably also want to implement some form of archiving or expunging for this data.
  2. Also create the responses table from 1 if necessary. This can be used whenever users want to see a simple table for results.
  3. For any analytics that need to be done for reporting purposes, schedule jobs to create additional summary data based on the data from 1.

This is absolutely a lot more work to implement, so I really wouldn't advise this unless you know for certain that this table is going to run into massive scale concerns.

How to simulate browsing from various locations?

This is a bit of self promotion, but I built a tool to do just this that you might find useful, called GeoPeeker.

It remotely accesses a site from servers spread around the world, renders the page with webkit and sends back an image. It will also report the IP address and DNS information of the site as it appears from that location.

There are no ads, and it's very stream-lined to serve this one purpose. It's still in development, and feedback is welcome. Here's hoping somebody besides myself finds it useful!

How to fix: Error device not found with ADB.exe

Another issue here is that you likely need to turn off "connect as media device" to be able to connect with adb.

How to use readline() method in Java?

This will explain it, I think...

import java.io.*;

class reading
{
    public static void  main(String args[]) throws IOException
    {
        float number;
        System.out.println("Enter a number");
        try
        {
            InputStreamReader in = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(in);
            String a = br.readLine();
            number = Float.valueOf(a);
            int x = (int)number;

            System.out.println("Your input=" + number);
            System.out.println("Your input in integer terms is = " + x);
        }
        catch(Exception e){
        }
    }
}

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

Task.Run with Parameter(s)?

private void RunAsync()
{
    string param = "Hi";
    Task.Run(() => MethodWithParameter(param));
}

private void MethodWithParameter(string param)
{
    //Do stuff
}

Edit

Due to popular demand I must note that the Task launched will run in parallel with the calling thread. Assuming the default TaskScheduler this will use the .NET ThreadPool. Anyways, this means you need to account for whatever parameter(s) being passed to the Task as potentially being accessed by multiple threads at once, making them shared state. This includes accessing them on the calling thread.

In my above code that case is made entirely moot. Strings are immutable. That's why I used them as an example. But say you're not using a String...

One solution is to use async and await. This, by default, will capture the SynchronizationContext of the calling thread and will create a continuation for the rest of the method after the call to await and attach it to the created Task. If this method is running on the WinForms GUI thread it will be of type WindowsFormsSynchronizationContext.

The continuation will run after being posted back to the captured SynchronizationContext - again only by default. So you'll be back on the thread you started with after the await call. You can change this in a variety of ways, notably using ConfigureAwait. In short, the rest of that method will not continue until after the Task has completed on another thread. But the calling thread will continue to run in parallel, just not the rest of the method.

This waiting to complete running the rest of the method may or may not be desirable. If nothing in that method later accesses the parameters passed to the Task you may not want to use await at all.

Or maybe you use those parameters much later on in the method. No reason to await immediately as you could continue safely doing work. Remember, you can store the Task returned in a variable and await on it later - even in the same method. For instance, once you need to access the passed parameters safely after doing a bunch some other work. Again, you do not need to await on the Task right when you run it.

Anyways, a simple way to make this thread-safe with respect to the parameters passed to Task.Run is to do this:

You must first decorate RunAsync with async:

private async void RunAsync()

Important Note

Preferably the method marked async should not return void, as the linked documentation mentions. The common exception to this is event handlers such as button clicks and such. They must return void. Otherwise I always try to return a Task or Task<TResult> when using async. It's good practice for a quite a few reasons.

Now you can await running the Task like below. You cannot use await without async.

await Task.Run(() => MethodWithParameter(param));
//Code here and below in the same method will not run until AFTER the above task has completed in one fashion or another

So, in general, if you await the task you can avoid treating passed in parameters as a potentially shared resource with all the pitfalls of modifying something from multiple threads at once. Also, beware of closures. I won't cover those in depth but the linked article does a great job of it.

Side Note

A bit off topic, but be careful using any type of "blocking" on the WinForms GUI thread due to it being marked with [STAThread]. Using await won't block at all, but I do sometimes see it used in conjunction with some sort of blocking.

"Block" is in quotes because you technically cannot block the WinForms GUI thread. Yes, if you use lock on the WinForms GUI thread it will still pump messages, despite you thinking it's "blocked". It's not.

This can cause bizarre issues in very rare cases. One of the reasons you never want to use a lock when painting, for example. But that's a fringe and complex case; however I've seen it cause crazy issues. So I noted it for completeness sake.

How do I iterate over the words of a string?

Based on Galik's answer I made this. This is mostly here so I don't have to keep writing it again and again. It's crazy that C++ still doesn't have a native split function. Features:

  • Should be very fast.
  • Easy to understand (I think).
  • Merges empty sections.
  • Trivial to use several delimiters (e.g. "\r\n")
#include <string>
#include <vector>
#include <algorithm>

std::vector<std::string> split(const std::string& s, const std::string& delims)
{
    using namespace std;

    vector<string> v;

    // Start of an element.
    size_t elemStart = 0;

    // We start searching from the end of the previous element, which
    // initially is the start of the string.
    size_t elemEnd = 0;

    // Find the first non-delim, i.e. the start of an element, after the end of the previous element.
    while((elemStart = s.find_first_not_of(delims, elemEnd)) != string::npos)
    {
        // Find the first delem, i.e. the end of the element (or if this fails it is the end of the string).
        elemEnd = s.find_first_of(delims, elemStart);
        // Add it.
        v.emplace_back(s, elemStart, elemEnd == string::npos ? string::npos : elemEnd - elemStart);
    }
    // When there are no more non-spaces, we are done.

    return v;
}

Android: adb pull file on desktop

do adb pull \sdcard\log.txt C:Users\admin\Desktop

php multidimensional array get values

This is the way to iterate on this array:

foreach($hotels as $row) {
       foreach($row['rooms'] as $k) {
             echo $k['boards']['board_id'];
             echo $k['boards']['price'];
       }
}

You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.

Path of assets in CSS files in Symfony 2

I'll post what worked for me, thanks to @xavi-montero.

Put your CSS in your bundle's Resource/public/css directory, and your images in say Resource/public/img.

Change assetic paths to the form 'bundles/mybundle/css/*.css', in your layout.

In config.yml, add rule css_rewrite to assetic:

assetic:
    filters:
        cssrewrite:
            apply_to: "\.css$"

Now install assets and compile with assetic:

$ rm -r app/cache/* # just in case
$ php app/console assets:install --symlink
$ php app/console assetic:dump --env=prod

This is good enough for the development box, and --symlink is useful, so you don't have to reinstall your assets (for example, you add a new image) when you enter through app_dev.php.

For the production server, I just removed the '--symlink' option (in my deployment script), and added this command at the end:

$ rm -r web/bundles/*/css web/bundles/*/js # all this is already compiled, we don't need the originals

All is done. With this, you can use paths like this in your .css files: ../img/picture.jpeg

Subset data.frame by date

Well, it's clearly not a number since it has dashes in it. The error message and the two comments tell you that it is a factor but the commentators are apparently waiting and letting the message sink in. Dirk is suggesting that you do this:

 EPL2011_12$Date2 <- as.Date( as.character(EPL2011_12$Date), "%d-%m-%y")

After that you can do this:

 EPL2011_12FirstHalf <- subset(EPL2011_12, Date2 > as.Date("2012-01-13") )

R date functions assume the format is either "YYYY-MM-DD" or "YYYY/MM/DD". You do need to compare like classes: date to date, or character to character.

"Debug certificate expired" error in Eclipse Android plugins

If a certificate expires in the middle of project debugging, you must do a manual uninstall:

Please execute adb uninstall <package_name> in a shell.

sort json object in javascript

Here is a simple snippet that sorts a javascript representation of a Json.

function isObject(v) {
    return '[object Object]' === Object.prototype.toString.call(v);
};

JSON.sort = function(o) {
if (Array.isArray(o)) {
        return o.sort().map(JSON.sort);
    } else if (isObject(o)) {
        return Object
            .keys(o)
        .sort()
            .reduce(function(a, k) {
                a[k] = JSON.sort(o[k]);

                return a;
            }, {});
    }

    return o;
}

It can be used as follows:

JSON.sort({
    c: {
        c3: null,
        c1: undefined,
        c2: [3, 2, 1, 0],
    },
    a: 0,
    b: 'Fun'
});

That will output:

{
  a: 0,
  b: 'Fun',
  c: {
    c2: [3, 2, 1, 0],
    c3: null
  }
}

In Java, how can I determine if a char array contains a particular character?

Here's a variation of Oscar's first version that doesn't use a for-each loop.

for (int i = 0; i < charArray.length; i++) {
    if (charArray[i] == 'q') {
        // do something
        break;
    }
}

You could have a boolean variable that gets set to false before the loop, then make "do something" set the variable to true, which you could test for after the loop. The loop could also be wrapped in a function call then just use 'return true' instead of the break, and add a 'return false' statement after the for loop.

CSS: fixed position on x-axis but not y?

Its a simple technique using the script also. You can check a demo here too.

JQuery

$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + 15 
         //Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
    });
});

CSS

#header {
    top: 15px;
    left: 15px;
    position: absolute;
}

Update Credit: @PierredeLESPINAY

As commented, to make the script support the changes in the css without having to recode them in the script. You can use the following.

var leftOffset = parseInt($("#header").css('left')); //Grab the left position left first
$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + leftOffset //Use it later
    });
});

Demo :)

Putting -moz-available and -webkit-fill-available in one width (css property)

CSS will skip over style declarations it doesn't understand. Mozilla-based browsers will not understand -webkit-prefixed declarations, and WebKit-based browsers will not understand -moz-prefixed declarations.

Because of this, we can simply declare width twice:

elem {
    width: 100%;
    width: -moz-available;          /* WebKit-based browsers will ignore this. */
    width: -webkit-fill-available;  /* Mozilla-based browsers will ignore this. */
    width: fill-available;
}

The width: 100% declared at the start will be used by browsers which ignore both the -moz and -webkit-prefixed declarations or do not support -moz-available or -webkit-fill-available.

How to dynamically create generic C# object using reflection?

Make sure you're doing this for a good reason, a simple function like the following would allow static typing and allows your IDE to do things like "Find References" and Refactor -> Rename.

public Task <T> factory (String name)
{
  Task <T> result;

  if (name.CompareTo ("A") == 0)
  {
    result = new TaskA ();
  }
  else if (name.CompareTo ("B") == 0)
  {
    result = new TaskB ();
  }

  return result;
}

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

HTTPScoop is awesome for inspecting the web traffic on your Mac. It's been incredibly helpful for me. I didn't think twice about the $15 price tag. There is a 14 day trial.

Excel function to get first word from sentence in other cell

I found this on exceljet.net and works for me:

=LEFT(B4,FIND(" ",B4)-1)

ORA-00984: column not allowed here

Replace double quotes with single ones:

INSERT
INTO    MY.LOGFILE
        (id,severity,category,logdate,appendername,message,extrainfo)
VALUES  (
       'dee205e29ec34',
       'FATAL',
       'facade.uploader.model',
       '2013-06-11 17:16:31',
       'LOGDB',
       NULL,
       NULL
       )

In SQL, double quotes are used to mark identifiers, not string constants.

How to return a html page from a restful controller in spring boot?

When using @RestController like this:

@RestController
public class HomeController {

    @RequestMapping("/")
    public String welcome() {
        return "login";
    }
}

This is the same as you do like this in a normal controller:

@Controller
public class HomeController {

    @RequestMapping("/")
    @ResponseBody
    public String welcome() {
        return "login";
    }
}

Using @ResponseBody returns return "login"; as a String object. Any object you return will be attached as payload in the HTTP body as JSON.

This is why you are getting just login in the response.

String Pattern Matching In Java

You can use the Pattern class for this. If you want to match only word characters inside the {} then you can use the following regex. \w is a shorthand for [a-zA-Z0-9_]. If you are ok with _ then use \w or else use [a-zA-Z0-9].

String URL = "https://localhost:8080/sbs/01.00/sip/dreamworks/v/01.00/cui/print/$fwVer/{$fwVer}/$lang/en/$model/{$model}/$region/us/$imageBg/{$imageBg}/$imageH/{$imageH}/$imageSz/{$imageSz}/$imageW/{$imageW}/movie/Kung_Fu_Panda_two/categories/3D_Pix/item/{item}/_back/2?$uniqueID={$uniqueID}";
Pattern pattern = Pattern.compile("/\\{\\w+\\}/");
Matcher matcher = pattern.matcher(URL);
if (matcher.find()) {
    System.out.println(matcher.group(0)); //prints /{item}/
} else {
    System.out.println("Match not found");
}

How to stretch a table over multiple pages

You should \usepackage{longtable}.

How do I get a Cron like scheduler in Python?

There isn't a "pure python" way to do this because some other process would have to launch python in order to run your solution. Every platform will have one or twenty different ways to launch processes and monitor their progress. On unix platforms, cron is the old standard. On Mac OS X there is also launchd, which combines cron-like launching with watchdog functionality that can keep your process alive if that's what you want. Once python is running, then you can use the sched module to schedule tasks.

String comparison in Python: is vs. ==

I would like to show a little example on how is and == are involved in immutable types. Try that:

a = 19998989890
b = 19998989889 +1
>>> a is b
False
>>> a == b
True

is compares two objects in memory, == compares their values. For example, you can see that small integers are cached by Python:

c = 1
b = 1
>>> b is c
True

You should use == when comparing values and is when comparing identities. (Also, from an English point of view, "equals" is different from "is".)

How to Customize a Progress Bar In Android

For using custom drawable:

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:drawable="@drawable/my_drawable"
android:pivotX="50%"
android:pivotY="50%" />

(add under res/drawable progress.xml). my_drawable may be xml, png

Then in your layout use

<ProgressBar
        android:id="@+id/progressBar"
        android:indeterminateDrawable="@drawable/progress_circle"
...
/>

Writing an input integer into a cell

You can use the Range object in VBA to set the value of a named cell, just like any other cell.

Range("C1").Value = Inputbox("Which job number would you like to add to the list?)

Where "C1" is the name of the cell you want to update.

My Excel VBA is a little bit old and crusty, so there may be a better way to do this in newer versions of Excel.

What are the different types of indexes, what are the benefits of each?

Different database systems have different names for the same type of index, so be careful with this. For example, what SQL Server and Sybase call "clustered index" is called in Oracle an "index-organised table".

Reading a binary input stream into a single byte array in Java

You can read it by chunks (byte buffer[] = new byte[2048]) and write the chunks to a ByteArrayOutputStream. From the ByteArrayOutputStream you can retrieve the contents as a byte[], without needing to determine its size beforehand.

Find the index of a char in string?

The String class exposes some methods to enable this, such as IndexOf and LastIndexOf, so that you may do this:

Dim myText = "abcde"
Dim dIndex = myText.IndexOf("d")
If (dIndex > -1) Then

End If

Why is there no xrange function in Python3?

comp:~$ python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2

>>> import timeit
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)

5.656799077987671

>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)

5.579368829727173

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

21.54827117919922

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

22.014557123184204

With timeit number=1 param:

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)

0.2245171070098877

>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=1)

0.10750913619995117

comp:~$ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

9.113872020003328

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

9.07014398300089

With timeit number=1,2,3,4 param works quick and in linear way:

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)

0.09329321900440846

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=2)

0.18501482300052885

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=3)

0.2703447980020428

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=4)

0.36209142999723554

So it seems if we measure 1 running loop cycle like timeit.timeit("[x for x in range(1000000) if x%4]",number=1) (as we actually use in real code) python3 works quick enough, but in repeated loops python 2 xrange() wins in speed against range() from python 3.

How to use variables in a command in sed?

Say:

sed "s|\$ROOT|${HOME}|" abc.sh

Note:

  • Use double quotes so that the shell would expand variables.
  • Use a separator different than / since the replacement contains /
  • Escape the $ in the pattern since you don't want to expand it.

EDIT: In order to replace all occurrences of $ROOT, say

sed "s|\$ROOT|${HOME}|g" abc.sh

Change the On/Off text of a toggle button Android

Set the XML as:

<ToggleButton
    android:id="@+id/flashlightButton"
    style="@style/Button"
    android:layout_above="@+id/buttonStrobeLight"
    android:layout_marginBottom="20dp"
    android:onClick="onToggleClicked"
    android:text="ToggleButton"
    android:textOn="Light ON"
    android:textOff="Light OFF" />

Matplotlib different size subplots

Another way is to use the subplots function and pass the width ratio with gridspec_kw:

import numpy as np
import matplotlib.pyplot as plt 

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
f, (a0, a1) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [3, 1]})
a0.plot(x, y)
a1.plot(y, x)

f.tight_layout()
f.savefig('grid_figure.pdf')

UnicodeEncodeError: 'ascii' codec can't encode character at special name

You really want to do this

flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))

This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).

Can You Get A Users Local LAN IP Address Via JavaScript?

As it turns out, the recent WebRTC extension of HTML5 allows javascript to query the local client IP address. A proof of concept is available here: http://net.ipcalf.com

This feature is apparently by design, and is not a bug. However, given its controversial nature, I would be cautious about relying on this behaviour. Nevertheless, I think it perfectly and appropriately addresses your intended purpose (revealing to the user what their browser is leaking).

Checking Bash exit status of several commands efficiently

You can use @john-kugelman 's awesome solution found above on non-RedHat systems by commenting out this line in his code:

. /etc/init.d/functions

Then, paste the below code at the end. Full disclosure: This is just a direct copy & paste of the relevant bits of the above mentioned file taken from Centos 7.

Tested on MacOS and Ubuntu 18.04.


BOOTUP=color
RES_COL=60
MOVE_TO_COL="echo -en \\033[${RES_COL}G"
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_WARNING="echo -en \\033[1;33m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"

echo_success() {
    [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
    echo -n "["
    [ "$BOOTUP" = "color" ] && $SETCOLOR_SUCCESS
    echo -n $"  OK  "
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "]"
    echo -ne "\r"
    return 0
}

echo_failure() {
    [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
    echo -n "["
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo -n $"FAILED"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "]"
    echo -ne "\r"
    return 1
}

echo_passed() {
    [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
    echo -n "["
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo -n $"PASSED"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "]"
    echo -ne "\r"
    return 1
}

echo_warning() {
    [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
    echo -n "["
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo -n $"WARNING"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "]"
    echo -ne "\r"
    return 1
} 

Checking if a website is up via Python

If by up, you simply mean "the server is serving", then you could use cURL, and if you get a response than it's up.

I can't give you specific advice because I'm not a python programmer, however here is a link to pycurl http://pycurl.sourceforge.net/.

Minimum and maximum date

To augment T.J.'s answer, exceeding the min/max values generates an Invalid Date.

_x000D_
_x000D_
let maxDate = new Date(8640000000000000);_x000D_
let minDate = new Date(-8640000000000000);_x000D_
_x000D_
console.log(new Date(maxDate.getTime()).toString());_x000D_
console.log(new Date(maxDate.getTime() - 1).toString());_x000D_
console.log(new Date(maxDate.getTime() + 1).toString()); // Invalid Date_x000D_
_x000D_
console.log(new Date(minDate.getTime()).toString());_x000D_
console.log(new Date(minDate.getTime() + 1).toString());_x000D_
console.log(new Date(minDate.getTime() - 1).toString()); // Invalid Date
_x000D_
_x000D_
_x000D_

Display Python datetime without time

If you need the result to be timezone-aware, you can use the replace() method of datetime objects. This preserves timezone, so you can do

>>> from django.utils import timezone
>>> now = timezone.now()
>>> now
datetime.datetime(2018, 8, 30, 14, 15, 43, 726252, tzinfo=<UTC>)
>>> now.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2018, 8, 30, 0, 0, tzinfo=<UTC>)

Note that this returns a new datetime object -- now remains unchanged.

How to split a line into words separated by one or more spaces in bash?

$ line="these are words"
$ ll=($line)
$ declare -p ll  # dump the array
declare -a ll='([0]="these" [1]="are" [2]="words")'
$ for w in ${ll[@]}; do echo $w; done
these
are
words

Measuring function execution time in R

The built-in function system.time() will do it.

Use like: system.time(result <- myfunction(with, arguments))

Java program to find the largest & smallest number in n numbers without using arrays

import java.util.Scanner;

public class LargestSmallestNumbers {

    private static Scanner input;

    public static void main(String[] args) {
       int count,items;
       int newnum =0 ;
       int highest=0;
       int lowest =0;

       input = new Scanner(System.in);
       System.out.println("How many numbers you want to enter?");
       items = input.nextInt();

       System.out.println("Enter "+items+" numbers: ");


       for (count=0; count<items; count++){
           newnum = input.nextInt();               
           if (highest<newnum)
               highest=newnum;

           if (lowest==0)
               lowest=newnum;

           else if (newnum<=lowest)
               lowest=newnum;
           }

       System.out.println("The highest number is "+highest);
       System.out.println("The lowest number is "+lowest);
    }
}

how to get session id of socket.io client in Client

On socket.io >=1.0, after the connect event has triggered:

var socket = io('localhost');
var id = socket.io.engine.id

How to remove a Gitlab project?

  • Click on Project you want to delete.
  • Click Setting on right buttom corner.
  • click general than go to advance
  • than remove project

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

What is the 'instanceof' operator used for in Java?

This operator allows you to determine the type of an object. It returns a boolean value.

For example

package test;

import java.util.Date;
import java.util.Map;
import java.util.HashMap;

public class instanceoftest
{
    public static void main(String args[])
    {
        Map m=new HashMap();
        System.out.println("Returns a boolean value "+(m instanceof Map));
        System.out.println("Returns a boolean value "+(m instanceof HashMap));
        System.out.println("Returns a boolean value "+(m instanceof Object));
        System.out.println("Returns a boolean value "+(m instanceof Date));
    }
} 

the output is:

Returns a boolean value true
Returns a boolean value true
Returns a boolean value true
Returns a boolean value false

BLOB to String, SQL Server

It depends on how the data was initially put into the column. Try either of these as one should work:

SELECT CONVERT(NVarChar(40), BLOBTextToExtract)
FROM [NavisionSQL$Customer];

Or if it was just varchar...

SELECT CONVERT(VarChar(40), BLOBTextToExtract)
FROM [NavisionSQL$Customer];

I used this script to verify and test on SQL Server 2K8 R2:

DECLARE @blob VarBinary(MAX) = CONVERT(VarBinary(MAX), 'test');

-- show the binary representation
SELECT @blob;

-- this doesn't work
SELECT CONVERT(NVarChar(100), @blob);

-- but this does
SELECT CONVERT(VarChar(100), @blob);

Prevent a webpage from navigating away using JavaScript

If you are catching a browser back/forward button and don't want to navigate away, you can use:

window.addEventListener('popstate', function() {
    if (window.location.origin !== 'http://example.com') {
        // Do something if not your domain
    } else if (window.location.href === 'http://example.com/sign-in/step-1') {
        window.history.go(2); // Skip the already-signed-in pages if the forward button was clicked
    } else if (window.location.href === 'http://example.com/sign-in/step-2') {
        window.history.go(-2); // Skip the already-signed-in pages if the back button was clicked
    } else {
        // Let it do its thing
    }
});

Otherwise, you can use the beforeunload event, but the message may or may not work cross-browser, and requires returning something that forces a built-in prompt.

Sending "User-agent" using Requests library in Python

It's more convenient to use a session, this way you don't have to remember to set headers each time:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

By default, session also manages cookies for you. In case you want to disable that, see this question.

Can I position an element fixed relative to parent?

first, set position: fixed and left: 50%, and second — now your start is a center and you can set new position with margin.

Find out time it took for a python script to complete execution

Do you execute the script from the command line on Linux or UNIX? In that case, you could just use

time ./script.py

Waiting for another flutter command to release the startup lock

For me, the issue's root cause on my Mac device was a version of the flock binary it was not expecting. Removing it from the path did the trick; probably a BSD vs GNU syntax issue.

Binding ConverterParameter

No, unfortunately this will not be possible because ConverterParameter is not a DependencyProperty so you won't be able to use bindings

But perhaps you could cheat and use a MultiBinding with IMultiValueConverter to pass in the 2 Tag properties.

How do you create a dropdownlist from an enum in ASP.NET MVC?

I would like to answer this question in a different way where, user need not to do anything in controller or Linq expression. This way...

I have a ENUM

public enum AccessLevelEnum
    {
        /// <summary>
        /// The user cannot access
        /// </summary>
        [EnumMember, Description("No Access")]
        NoAccess = 0x0,

        /// <summary>
        /// The user can read the entire record in question
        /// </summary>
        [EnumMember, Description("Read Only")]
        ReadOnly = 0x01,

        /// <summary>
        /// The user can read or write
        /// </summary>
        [EnumMember, Description("Read / Modify")]
        ReadModify = 0x02,

        /// <summary>
        /// User can create new records, modify and read existing ones
        /// </summary>
        [EnumMember, Description("Create / Read / Modify")]
        CreateReadModify = 0x04,

        /// <summary>
        /// User can read, write, or delete
        /// </summary>
        [EnumMember, Description("Create / Read / Modify / Delete")]
        CreateReadModifyDelete = 0x08,

        /*/// <summary>
        /// User can read, write, or delete
        /// </summary>
        [EnumMember, Description("Create / Read / Modify / Delete / Verify / Edit Capture Value")]
        CreateReadModifyDeleteVerify = 0x16*/
    }

Now I canto simply create a dropdown by using this enum.

@Html.DropDownList("accessLevel",new SelectList(AccessLevelEnum.GetValues(typeof(AccessLevelEnum))),new { @class = "form-control" })

OR

@Html.DropDownListFor(m=>m.accessLevel,new SelectList(AccessLevelEnum.GetValues(typeof(AccessLevelEnum))),new { @class = "form-control" })

If you want to make a index selected then try this

@Html.DropDownListFor(m=>m.accessLevel,new SelectList(AccessLevelEnum.GetValues(typeof(AccessLevelEnum)) , AccessLevelEnum.NoAccess ),new { @class = "form-control" })

Here I have used AccessLevelEnum.NoAccess as an extra parameter for default selecting the dropdown.

"Could not get any response" response when using postman with subdomain

For me, it was that route that I was calling in my node server wasn't returning anything. Adding

    return res.status(200).json({
        message: 'success!',
        response: 'success!'
    });//

to the route I was calling resolved the issue.

Set focus to field in dynamically loaded DIV

Dynamically added items have to be added to the DOM... clone().append() adds it to the DOM... which allows it to be selected via jquery.

Defining static const integer members in class definition

Here's another way to work around the problem:

std::min(9, int(test::N));

(I think Crazy Eddie's answer correctly describes why the problem exists.)

error: Libtool library used but 'LIBTOOL' is undefined

In my case on macOS I solved it with:

brew link libtool

Instagram API to fetch pictures with specific hashtags

Take a look here in order to get started: http://instagram.com/developer/

and then in order to retrieve pictures by tag, look here: http://instagram.com/developer/endpoints/tags/

Getting tags from Instagram doesn't require OAuth, so you can make the calls via these URLs:

GET IMAGES https://api.instagram.com/v1/tags/{tag-name}/media/recent?access_token={TOKEN}

SEARCH https://api.instagram.com/v1/tags/search?q={tag-query}&access_token={TOKEN}

TAG INFO https://api.instagram.com/v1/tags/{tag-name}?access_token={TOKEN}

How to perform OR condition in django queryset?

Both options are already mentioned in the existing answers:

from django.db.models import Q
q1 = User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))

and

q2 = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)

However, there seems to be some confusion regarding which one is to prefer.

The point is that they are identical on the SQL level, so feel free to pick whichever you like!

The Django ORM Cookbook talks in some detail about this, here is the relevant part:


queryset = User.objects.filter(
        first_name__startswith='R'
    ) | User.objects.filter(
    last_name__startswith='D'
)

leads to

In [5]: str(queryset.query)
Out[5]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
"auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
"auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
"auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'

and

qs = User.objects.filter(Q(first_name__startswith='R') | Q(last_name__startswith='D'))

leads to

In [9]: str(qs.query)
Out[9]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
 "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
  "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
  "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
  WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'

source: django-orm-cookbook


mysql: get record count between two date-time

select * from yourtable where created < now() and created > '2011-04-25 04:00:00'

Returning an array using C

You can use code like this:

char *MyFunction(some arguments...)
{
    char *pointer = malloc(size for the new array);
    if (!pointer)
        An error occurred, abort or do something about the error.
    return pointer; // Return address of memory to the caller.
}

When you do this, the memory should later be freed, by passing the address to free.

There are other options. A routine might return a pointer to an array (or portion of an array) that is part of some existing structure. The caller might pass an array, and the routine merely writes into the array, rather than allocating space for a new array.

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

  1. Make sure that both tables are using the same Engine type.
  2. Make sure the fields you are indexing have the same type and length.

Is it possible to use jQuery to read meta tags

jQuery now supports .data();, so if you have

<div id='author' data-content='stuff!'>

use

var author = $('#author').data("content"); // author = 'stuff!'

How can I set / change DNS using the command-prompt at windows 8

Batch file for setting a new dns server

@echo off
rem usage: setdns <dnsserver> <interface>
rem default dsnserver is dhcp
rem default interface is Wi-Fi
set dnsserver="%1"
if %dnsserver%=="" set dnsserver="dhcp"
set interface="%2"
if %interface%=="" set interface="Wi-Fi"
echo Showing current DNS setting for interface a%interface%
netsh interface ipv4 show dnsserver %interface%
echo Changing dnsserver on interface %interface% to %dnsserver%
if %dnsserver% == "dhcp" netsh interface ipv4 set dnsserver %interface% %dnsserver%
if NOT %dnsserver% == "dhcp" netsh interface ipv4 add dnsserver %interface% address=%dnsserver% index=1
echo Showing new DNS setting for interface %interface%
netsh interface ipv4 show dnsserver %interface%

How to recursively delete an entire directory with PowerShell 2.0?

To delete the complete contents including the folder structure use

get-childitem $dest -recurse | foreach ($_) {remove-item $_.fullname -recurse}

The -recurse added to remove-item ensures interactive prompts are disabled.

Return datetime object of previous month

def month_sub(year, month, sub_month):
    result_month = 0
    result_year = 0
    if month > (sub_month % 12):
        result_month = month - (sub_month % 12)
        result_year = year - (sub_month / 12)
    else:
        result_month = 12 - (sub_month % 12) + month
        result_year = year - (sub_month / 12 + 1)
    return (result_year, result_month)

>>> month_sub(2015, 7, 1)    
(2015, 6)
>>> month_sub(2015, 7, -1)
(2015, 8)
>>> month_sub(2015, 7, 13)
(2014, 6)
>>> month_sub(2015, 7, -14)
(2016, 9)

Nullable types: better way to check for null or zero in c#

Don't forget, for strings, you can always use:

String.IsNullOrEmpty(str)

Instead of:

str==null || str==""

Accessing Websites through a Different Port?

If your question is about IIS(or other server) configuration - yes, it's possible. All you need is to create ports mapping under your Default Site or Virtual Directory and assign specific ports to the site you need. For example it is sometimes very useful for web services, when default port is assigned to some UI front-end and you want to assign service to the same address but with different port.

Vue.js getting an element within a component

In Vue2 be aware that you can access this.$refs.uniqueName only after mounting the component.

Detect IF hovering over element with jQuery

https://api.jquery.com/hover/

Asynchronous function in line 38:

$( ".class#id" ).hover(function() {
  Your javascript
});

Parsing JSON array with PHP foreach

You maybe wanted to do the following:

foreach($user->data as $mydata)

    {
         echo $mydata->name . "\n";
         foreach($mydata->values as $values)
         {
              echo $values->value . "\n";
         }
    }        

Delete rows containing specific strings in R

This should do the trick:

df[- grep("REVERSE", df$Name),]

Or a safer version would be:

df[!grepl("REVERSE", df$Name),]

Oracle ORA-12154: TNS: Could not resolve service name Error?

If there is a space in the beginning of the tns name define in file tnsnames.ora, then some of the the connectors like odbc may give this error. Remove space character in the beginning.

Getting the last element of a split string array

You can access the array index directly:

var csv = 'zero,one,two,three'; csv.split(',')[0]; //result: zero csv.split(',')[3]; //result: three

Test process.env with Jest

In ./package.json:

"jest": {
  "setupFiles": [
    "<rootDir>/jest/setEnvVars.js"
  ]
}

In ./jest/setEnvVars.js:

process.env.SOME_VAR = 'value';

Manually Set Value for FormBuilder Control

Tip: If you're using setValue but not providing every property on the form you'll get an error:

Must supply a value for form control with name: 'stateOrProvince'.

So you may be tempted to use patchValue, but this can be dangerous if you're trying to update a whole form. I have an address that may not have stateOrProvince or stateCd depending upon whether it is US or worldwide.

Instead you can update like this - which will use the nulls as defaults:

this.form.setValue( { stateOrProvince: null, stateCd: null, ...address } );

Origin http://localhost is not allowed by Access-Control-Allow-Origin

a thorough reading of jQuery AJAX cross domain seems to indicate that the server you are querying is returning a header string that prohibits cross-domain json requests. Check the headers of the response you are receiving to see if the Access-Control-Allow-Origin header is set, and whether its value restricts cross-domain requests to the local host.

OSError - Errno 13 Permission denied

Simply try:

sudo cp /source /destination

Using Switch Statement to Handle Button Clicks

I have found that the simplest way to do this is to set onClick for each button in the xml

<Button
android:id="@+id/vrHelp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_menu_help"
android:onClick="helpB" />

and then you can do a switch case like this

  public void helpB(View v) {
    Button clickedButton = (Button) v;
    switch (clickedButton.getId()) {
      case R.id.vrHelp:
        dosomething...
        break;

      case R.id.coHelp:
        dosomething...
        break;

      case R.id.ksHelp:
        dosomething...
        break;

      case R.id.uHelp:
        dosomething...
        break;

      case R.id.pHelp:
        dosomething...
        break;
    }
  }

Div vertical scrollbar show

Always : If you always want vertical scrollbar, use overflow-y: scroll;

jsFiddle:

<div style="overflow-y: scroll;">
......
</div>

When needed: If you only want vertical scrollbar when needed, use overflow-y: auto; (You need to specify a height in this case)

jsFiddle:

<div style="overflow-y: auto; height:150px; ">
....
</div>

Inserting NOW() into Database with CodeIgniter's Active Record

According to the source code of codeigniter, the function set is defined as:

public function set($key, $value = '', $escape = TRUE)
{
    $key = $this->_object_to_array($key);

    if ( ! is_array($key))
    {
        $key = array($key => $value);
    }

    foreach ($key as $k => $v)
    {
        if ($escape === FALSE)
        {
            $this->ar_set[$this->_protect_identifiers($k)] = $v;
        }
        else
        {
            $this->ar_set[$this->_protect_identifiers($k, FALSE, TRUE)] = $this->escape($v);
        }
    }

    return $this;
}

Apparently, if $key is an array, codeigniter will simply ignore the second parameter $value, but the third parameter $escape will still work throughout the iteration of $key, so in this situation, the following codes work (using the chain method):

$this->db->set(array(
    'name' => $name ,
    'email' => $email,
    'time' => 'NOW()'), '', FALSE)->insert('mytable');

However, this will unescape all the data, so you can break your data into two parts:

$this->db->set(array(
    'name' => $name ,
    'email' => $email))->set(array('time' => 'NOW()'), '', FALSE)->insert('mytable');

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

I tried a couple of answers mentioned in this link, but couldn't figure out how to tell Jenkins about the user-selected branch. As mentioned in my previous comment in above thread, I had left the branch selector field empty.

But, during further investigations, I found another way to do the same thing - https://wiki.jenkins-ci.org/display/JENKINS/Git+Parameter+Plugin I found this method was a lot simpler, and had less things to configure!

Here's what I configured -

  1. Installed the git parameter plugin
  2. Checked the 'This build is parameterized' and added a 'Git parameter'
  3. Added the following values: Git Parameter plugin config in the job

  4. Then in the git SCM section of the job I added the same value mentioned in the 'Name' section, as if it were an environment variable. (If you read the help for this git parameter plugin carefully, you will realize this) Branch Selector

After this I just ran the build, chose my branch(Jenkins checks out this branch before building) and it completed the build successfully, AND by choosing the branch that I had specified.

How to enable native resolution for apps on iPhone 6 and 6 Plus?

I've made basic black launch screens that will make the app scale properly on the iPhone 6 and iPhone 6+:

iPhone 6 Portrait

iPhone 6 Plus Portrait

If you already have a LaunchImage in your .xcassett, open it, switch to the third tab in the right menu in Xcode and tick the iOS 8.0 iPhone images to add them to the existing set. Then drag the images over:

enter image description here

Java: Get first item from a collection

You could do this:

String strz[] = strs.toArray(String[strs.size()]);
String theFirstOne = strz[0];

The javadoc for Collection gives the following caveat wrt ordering of the elements of the array:

If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

I faced same issue but now i am happy to resolve this issue.

  1. npm i core-js
  2. put this line into the first line of your index.js file. import core-js

Getting GET "?" variable in laravel

We have similar situation right now and as of this answer, I am using laravel 5.6 release.

I will not use your example in the question but mine, because it's related though.

I have route like this:

Route::name('your.name.here')->get('/your/uri', 'YourController@someMethod');

Then in your controller method, make sure you include

use Illuminate\Http\Request;

and this should be above your controller, most likely a default, if generated using php artisan, now to get variable from the url it should look like this:

  public function someMethod(Request $request)
  {
    $foo = $request->input("start");
    $bar = $request->input("limit");

    // some codes here
  }

Regardless of the HTTP verb, the input() method may be used to retrieve user input.

https://laravel.com/docs/5.6/requests#retrieving-input

Hope this help.

How to convert a Django QuerySet to a list

def querySet_to_list(qs):
    """
    this will return python list<dict>
    """
    return [dict(q) for q in qs]

def get_answer_by_something(request):
    ss = Answer.objects.filter(something).values()
    querySet_to_list(ss) # python list return.(json-able)

this code convert django queryset to python list

Sleep function Visual Basic

Since you are asking about .NET, you should change the parameter from Long to Integer. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)

Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)

Really though, the managed method isn't difficult...

System.Threading.Thread.CurrentThread.Sleep(5000)

Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep a good idea.

Using ng-click vs bind within link function of Angular Directive

In this case, no need for a directive. This does the job :

<button ng-click="count = count + 1" ng-init="count=0">
  Increment
</button>
<span>
  count: {{count}}
</span>

Source: https://docs.angularjs.org/api/ng/directive/ngClick

Simple way to unzip a .zip file using zlib

Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.

Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.

// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>

#include "unzip.h"

#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192

int main( int argc, char **argv )
{
    if ( argc < 2 )
    {
        printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
        return -1;
    }

    // Open the zip file
    unzFile *zipfile = unzOpen( argv[ 1 ] );
    if ( zipfile == NULL )
    {
        printf( "%s: not found\n" );
        return -1;
    }

    // Get info about the zip file
    unz_global_info global_info;
    if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
    {
        printf( "could not read file global info\n" );
        unzClose( zipfile );
        return -1;
    }

    // Buffer to hold data read from the zip file.
    char read_buffer[ READ_SIZE ];

    // Loop to extract all files
    uLong i;
    for ( i = 0; i < global_info.number_entry; ++i )
    {
        // Get info about current file.
        unz_file_info file_info;
        char filename[ MAX_FILENAME ];
        if ( unzGetCurrentFileInfo(
            zipfile,
            &file_info,
            filename,
            MAX_FILENAME,
            NULL, 0, NULL, 0 ) != UNZ_OK )
        {
            printf( "could not read file info\n" );
            unzClose( zipfile );
            return -1;
        }

        // Check if this entry is a directory or file.
        const size_t filename_length = strlen( filename );
        if ( filename[ filename_length-1 ] == dir_delimter )
        {
            // Entry is a directory, so create it.
            printf( "dir:%s\n", filename );
            mkdir( filename );
        }
        else
        {
            // Entry is a file, so extract it.
            printf( "file:%s\n", filename );
            if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
            {
                printf( "could not open file\n" );
                unzClose( zipfile );
                return -1;
            }

            // Open a file to write out the data.
            FILE *out = fopen( filename, "wb" );
            if ( out == NULL )
            {
                printf( "could not open destination file\n" );
                unzCloseCurrentFile( zipfile );
                unzClose( zipfile );
                return -1;
            }

            int error = UNZ_OK;
            do    
            {
                error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
                if ( error < 0 )
                {
                    printf( "error %d\n", error );
                    unzCloseCurrentFile( zipfile );
                    unzClose( zipfile );
                    return -1;
                }

                // Write data to file.
                if ( error > 0 )
                {
                    fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
                }
            } while ( error > 0 );

            fclose( out );
        }

        unzCloseCurrentFile( zipfile );

        // Go the the next entry listed in the zip file.
        if ( ( i+1 ) < global_info.number_entry )
        {
            if ( unzGoToNextFile( zipfile ) != UNZ_OK )
            {
                printf( "cound not read next file\n" );
                unzClose( zipfile );
                return -1;
            }
        }
    }

    unzClose( zipfile );

    return 0;
}

I built and tested it with MinGW/MSYS on Windows like this:

contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip

PHP: if !empty & empty

For several cases, or even just a few cases involving a lot of criteria, consider using a switch.

switch( true ){

    case ( !empty($youtube) && !empty($link) ):{
        // Nothing is empty...
        break;
    }

    case ( !empty($youtube) && empty($link) ):{
        // One is empty...
        break;
    }

    case ( empty($youtube) && !empty($link) ):{
        // The other is empty...
        break;
    }

    case ( empty($youtube) && empty($link) ):{
        // Everything is empty
        break;
    }

    default:{
        // Even if you don't expect ever to use it, it's a good idea to ALWAYS have a default.
        // That way if you change it, or miss a case, you have some default handler.
        break;
    }

}

If you have multiple cases that require the same action, you can stack them and omit the break; to flowthrough. Just maybe put a comment like /*Flowing through*/ so you're explicit about doing it on purpose.

Note that the { } around the cases aren't required, but they are nice for readability and code folding.

More about switch: http://php.net/manual/en/control-structures.switch.php

What are the special dollar sign shell variables?

  • $1, $2, $3, ... are the positional parameters.
  • "$@" is an array-like construct of all positional parameters, {$1, $2, $3 ...}.
  • "$*" is the IFS expansion of all positional parameters, $1 $2 $3 ....
  • $# is the number of positional parameters.
  • $- current options set for the shell.
  • $$ pid of the current shell (not subshell).
  • $_ most recent parameter (or the abs path of the command to start the current shell immediately after startup).
  • $IFS is the (input) field separator.
  • $? is the most recent foreground pipeline exit status.
  • $! is the PID of the most recent background command.
  • $0 is the name of the shell or shell script.

Most of the above can be found under Special Parameters in the Bash Reference Manual. There are all the environment variables set by the shell.

For a comprehensive index, please see the Reference Manual Variable Index.

Display the binary representation of a number in C?

There is no direct way (i.e. using printf or another standard library function) to print it. You will have to write your own function.

/* This code has an obvious bug and another non-obvious one :) */
void printbits(unsigned char v) {
   for (; v; v >>= 1) putchar('0' + (v & 1));
}

If you're using terminal, you can use control codes to print out bytes in natural order:

void printbits(unsigned char v) {
    printf("%*s", (int)ceil(log2(v)) + 1, ""); 
    for (; v; v >>= 1) printf("\x1b[2D%c",'0' + (v & 1));
}

What are the integrity and crossorigin attributes?

Both attributes have been added to Bootstrap CDN to implement Subresource Integrity.

Subresource Integrity defines a mechanism by which user agents may verify that a fetched resource has been delivered without unexpected manipulation Reference

Integrity attribute is to allow the browser to check the file source to ensure that the code is never loaded if the source has been manipulated.

Crossorigin attribute is present when a request is loaded using 'CORS' which is now a requirement of SRI checking when not loaded from the 'same-origin'. More info on crossorigin

More detail on Bootstrap CDNs implementation

MySql Error: 1364 Field 'display_name' doesn't have default value

Also, I had this issue using Laravel, but fixed by changing my database schema to allow "null" inputs on a table where I plan to collect the information from separate forms:

public function up()
{

    Schema::create('trip_table', function (Blueprint $table) {
        $table->increments('trip_id')->unsigned();
        $table->time('est_start');
        $table->time('est_end');
        $table->time('act_start')->nullable();
        $table->time('act_end')->nullable();
        $table->date('Trip_Date');
        $table->integer('Starting_Miles')->nullable();
        $table->integer('Ending_Miles')->nullable();
        $table->string('Bus_id')->nullable();
        $table->string('Event');
        $table->string('Desc')->nullable();
        $table->string('Destination');
        $table->string('Departure_location');
        $table->text('Drivers_Comment')->nullable();
        $table->string('Requester')->nullable();
        $table->integer('driver_id')->nullable();
        $table->timestamps();
    });

}

The ->nullable(); Added to the end. This is using Laravel. Hope this helps someone, thanks!

Easiest way to split a string on newlines in .NET?

Regex is also an option:

    private string[] SplitStringByLineFeed(string inpString)
    {
        string[] locResult = Regex.Split(inpString, "[\r\n]+");
        return locResult;
    }

List of Java processes

ps axuwww | grep java | grep -v grep

The above will

  • show you all processes with long lines (arg: www)
  • filter (grep) only lines what contain the word java, and
  • filter out the line "grep java" :)

(btw, this example is not the effective one, but simple to remember) ;)

you can pipe the above to another commands, for example:

ps axuwww | grep java | grep -v grep | sed '.....'  | while read something
do
    something_another $something
done

etc...

How can I access an internal class from an external assembly?

Without access to the type (and no "InternalsVisibleTo" etc) you would have to use reflection. But a better question would be: should you be accessing this data? It isn't part of the public type contract... it sounds to me like it is intended to be treated as an opaque object (for their purposes, not yours).

You've described it as a public instance field; to get this via reflection:

object obj = ...
string value = (string)obj.GetType().GetField("test").GetValue(obj);

If it is actually a property (not a field):

string value = (string)obj.GetType().GetProperty("test").GetValue(obj,null);

If it is non-public, you'll need to use the BindingFlags overload of GetField/GetProperty.

Important aside: be careful with reflection like this; the implementation could change in the next version (breaking your code), or it could be obfuscated (breaking your code), or you might not have enough "trust" (breaking your code). Are you spotting the pattern?

Define an alias in fish shell

Save your files as ~/.config/fish/functions/{some_function_name}.fish and they should get autoloaded when you start fish.

how to create and call scalar function in sql server 2008

Your Call works if it were a Table Valued Function. Since its a scalar function, you need to call it like:

SELECT dbo.fn_HomePageSlider(9, 3025) AS MyResult

How do I make a "div" button submit the form its sitting in?

onClick="javascript:this.form.submit();">

this in div onclick don't have attribute form, you may try this.parentNode.submit() or document.forms[0].submit() will do

Also, onClick, should be onclick, some browsers don't work with onClick

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

I had trouble binding a value with any of the symbols in AngularJS 1.6. I did not get any value at all, only undefined, even though I did it the exact same way as other bindings in the same file that did work.

Problem was: my variable name had an underscore.

This fails:

bindings: { import_nr: '='}

This works:

bindings: { importnr: '='}

(Not completely related to the original question, but that was one of the top search results when I looked, so hopefully this helps someone with the same problem.)

Gradle: How to Display Test Results in the Console in Real Time?

For those using Kotlin DSL, you can do:

tasks {
  named<Test>("test") {
    testLogging.showStandardStreams = true
  }
}

how to convert an RGB image to numpy array?

You can use newer OpenCV python interface (if I'm not mistaken it is available since OpenCV 2.2). It natively uses numpy arrays:

import cv2
im = cv2.imread("abc.tiff",mode='RGB')
print type(im)

result:

<type 'numpy.ndarray'>

Converting between strings and ArrayBuffers

I'd recommend NOT using deprecated APIs like BlobBuilder

BlobBuilder has long been deprecated by the Blob object. Compare the code in Dennis' answer — where BlobBuilder is used — with the code below:

function arrayBufferGen(str, cb) {

  var b = new Blob([str]);
  var f = new FileReader();

  f.onload = function(e) {
    cb(e.target.result);
  }

  f.readAsArrayBuffer(b);

}

Note how much cleaner and less bloated this is compared to the deprecated method... Yeah, this is definitely something to consider here.

How can I send emails through SSL SMTP with the .NET Framework?

If any doubt in this code, please ask your questions(Here for gmail Port number is 587)

// code to Send Mail 
// Add following Lines in your web.config file 
//               <system.net>
//                  <mailSettings>
//                    <smtp>
//                        <network host="smtp.gmail.com" port="587" userName="[email protected]" password="yyy"   defaultCredentials="false"/>
//                    </smtp>
//               </mailSettings>
//               </system.net>
// Add below lines in your config file inside appsetting tag <appsetting></appsetting>
//          <add key="emailFromAddress" value="[email protected]"/>
//       <add key="emailToAddress" value="[email protected]"/>
//        <add key="EmailSsl" value="true"/>

// Namespace Used

using System.Net.Mail;
     public static bool SendingMail(string subject, string content)
    {
       // getting the values from config file through c#
        string fromEmail = ConfigurationSettings.AppSettings["emailFromAddress"];
        string mailid = ConfigurationSettings.AppSettings["emailToAddress"];
        bool useSSL;
        if (ConfigurationSettings.AppSettings["EmailSsl"] == "true")
        {
            useSSL = true;
        }
        else
        {
            useSSL = false;
        }



        SmtpClient emailClient;
        MailMessage message;
        message = new MailMessage();
        message.From = new MailAddress(fromEmail);
        message.ReplyTo = new MailAddress(fromEmail);
        if (SetMailAddressCollection(message.To, mailid))
        {
            message.Subject = subject;
            message.Body = content;
            message.IsBodyHtml = true;
            emailClient = new SmtpClient();
            emailClient.EnableSsl = useSSL;
            emailClient.Send(message);
        }
        return true;
    }
    // if you are sending mail in group

    private static bool SetMailAddressCollection(MailAddressCollection toAddresses, string    mailId)
    {
        bool successfulAddressCreation = true;
        toAddresses.Add(new MailAddress(mailId));
        return successfulAddressCreation;
    }

Hashmap does not work with int, char

You cannot put primitive types into collections. However, you can declare them using their corresponding object wrappers and still add the primitive values, as long as the boxing allows you.

How do I install PIL/Pillow for Python 3.6?

You can download the wheel corresponding to your configuration here ("Pillow-4.1.1-cp36-cp36m-win_amd64.whl" in your case) and install it with:

pip install some-package.whl

If you have problem to install the wheel read this answer

Async always WaitingForActivation

this code seems to have address the issue for me. it comes for a streaming class, ergo some of the nomenclature.

''' <summary> Reference to the awaiting task. </summary>
''' <value> The awaiting task. </value>
Protected ReadOnly Property AwaitingTask As Threading.Tasks.Task

''' <summary> Reference to the Action task; this task status undergoes changes. </summary>
Protected ReadOnly Property ActionTask As Threading.Tasks.Task

''' <summary> Reference to the cancellation source. </summary>
Protected ReadOnly Property TaskCancellationSource As Threading.CancellationTokenSource

''' <summary> Starts the action task. </summary>
''' <param name="taskAction"> The action to stream the entities, which calls
'''                           <see cref="StreamEvents(Of T)(IEnumerable(Of T), IEnumerable(Of Date), Integer, String)"/>. </param>
''' <returns> The awaiting task. </returns>
Private Async Function AsyncAwaitTask(ByVal taskAction As Action) As Task
    Me._ActionTask = Task.Run(taskAction)
    Await Me.ActionTask '  Task.Run(streamEntitiesAction)
    Try
        Me.ActionTask?.Wait()
        Me.OnStreamTaskEnded(If(Me.ActionTask Is Nothing, TaskStatus.RanToCompletion, Me.ActionTask.Status))
    Catch ex As AggregateException
        Me.OnExceptionOccurred(ex)
    Finally
        Me.TaskCancellationSource.Dispose()
    End Try
End Function

''' <summary> Starts Streaming the events. </summary>
''' <exception cref="InvalidOperationException"> Thrown when the requested operation is invalid. </exception>
''' <param name="bucketKey">            The bucket key. </param>
''' <param name="timeout">              The timeout. </param>
''' <param name="streamEntitiesAction"> The action to stream the entities, which calls
'''                                     <see cref="StreamEvents(Of T)(IEnumerable(Of T), IEnumerable(Of Date), Integer, String)"/>. </param>
Public Overridable Sub StartStreamEvents(ByVal bucketKey As String, ByVal timeout As TimeSpan, ByVal streamEntitiesAction As Action)
    If Me.IsTaskActive Then
        Throw New InvalidOperationException($"Stream task is {Me.ActionTask.Status}")
    Else
        Me._TaskCancellationSource = New Threading.CancellationTokenSource
        Me.TaskCancellationSource.Token.Register(AddressOf Me.StreamTaskCanceled)
        Me.TaskCancellationSource.CancelAfter(timeout)
        ' the action class is created withing the Async/Await function
        Me._AwaitingTask = Me.AsyncAwaitTask(streamEntitiesAction)
    End If
End Sub

Getting the base url of the website and globally passing it to twig in Symfony 2

For current Symfony version (as of writing this answer it's Symfony 4.1) do not directly access the service container as done in some of the other answers.

Instead (unless you don't use the standard services configuration), inject the request object by type-hinting.

<?php

namespace App\Service;

use Symfony\Component\HttpFoundation\RequestStack;

/**
 * The YourService class provides a method for retrieving the base URL.
 *
 * @package App\Service
 */
class YourService
{

    /**
     * @var string
     */
    protected $baseUrl;

    /**
     * YourService constructor.
     *
     * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
     */
    public function __construct(RequestStack $requestStack)
    {
        $this->baseUrl = $requestStack->getCurrentRequest()->getSchemeAndHttpHost();
    }

    /**
     * Returns the current base URL.
     *
     * @return string
     */
    public function getBaseUrl(): string
    {
        return $this->baseUrl;
    }
}

See also official Symfony docs about how to retrieve the current request object.

PHP - Notice: Undefined index:

You're getting errors because you're attempting to read post variables that haven't been set, they only get set on form submission. Wrap your php code at the bottom in an

if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... }

Also, your code is ripe for SQL injection. At the very least use mysql_real_escape_string on the post vars before using them in SQL queries. mysql_real_escape_string is not good enough for a production site, but should score you extra points in class.

Link and execute external JavaScript file hosted on GitHub

I had the same issue as you, what I did is change to

<script type="application/javascript" src="bootstrap-wysiwyg.js"></script>

It works for me.

How to limit depth for recursive file list?

tree -L 2 -u -g -p -d

Prints the directory tree in a pretty format up to depth 2 (-L 2). Print user (-u) and group (-g) and permissions (-p). Print only directories (-d). tree has a lot of other useful options.

Javascript : calling function from another file

Why don't you take a look to this answer

Including javascript files inside javascript files

In short you can load the script file with AJAX or put a script tag on the HTML to include it( before the script that uses the functions of the other script). The link I posted is a great answer and has multiple examples and explanations of both methods.

Get a worksheet name using Excel VBA

Extend Code for Show Selected Sheet(s) [ one or more sheets].

Sub Show_SelectSheet()
  For Each xSheet In ThisWorkbook.Worksheets
     For Each xSelectSheet In ActiveWindow.SelectedSheets
         If xSheet.Name = xSelectSheet.Name Then
            '=== Show Selected Sheet ===
            GoTo xNext_SelectSheet
         End If
     Next xSelectSheet
  xSheet.Visible = False  
xNext_SelectSheet:
Next xSheet
MsgBox "Show Selected Sheet(s) Completed !!!"
end sub