Programs & Examples On #Dynamic url

Simplest SOAP example

There are many quirks in the way browsers handle XMLHttpRequest, this JS code will work across all browsers:
https://github.com/ilinsky/xmlhttprequest

This JS code converts XML into easy to use JavaScript objects:
http://www.terracoder.com/index.php/xml-objectifier

The JS code above can be included in the page to meet your no external library requirement.

var symbol = "MSFT"; 
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://www.webservicex.net/stockquote.asmx?op=GetQuote",true);
xmlhttp.onreadystatechange=function() {
 if (xmlhttp.readyState == 4) {
  alert(xmlhttp.responseText);
  // http://www.terracoder.com convert XML to JSON 
  var json = XMLObjectifier.xmlToJSON(xmlhttp.responseXML);
  var result = json.Body[0].GetQuoteResponse[0].GetQuoteResult[0].Text;
  // Result text is escaped XML string, convert string to XML object then convert to JSON object
  json = XMLObjectifier.xmlToJSON(XMLObjectifier.textToXML(result));
  alert(symbol + ' Stock Quote: $' + json.Stock[0].Last[0].Text); 
 }
}
xmlhttp.setRequestHeader("SOAPAction", "http://www.webserviceX.NET/GetQuote");
xmlhttp.setRequestHeader("Content-Type", "text/xml");
var xml = '<?xml version="1.0" encoding="utf-8"?>' +
 '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
                'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
                'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' + 
   '<soap:Body> ' +
     '<GetQuote xmlns="http://www.webserviceX.NET/"> ' +
       '<symbol>' + symbol + '</symbol> ' +
     '</GetQuote> ' +
   '</soap:Body> ' +
 '</soap:Envelope>';
xmlhttp.send(xml);
// ...Include Google and Terracoder JS code here...

Two other options:

error: invalid type argument of ‘unary *’ (have ‘int’)

I have reformatted your code.

The error was situated in this line :

printf("%d", (**c));

To fix it, change to :

printf("%d", (*c));

The * retrieves the value from an address. The ** retrieves the value (an address in this case) of an other value from an address.

In addition, the () was optional.

#include <stdio.h>

int main(void)
{
    int b = 10; 
    int *a = NULL;
    int *c = NULL;

    a = &b;
    c = &a;

    printf("%d", *c);

    return 0;
} 

EDIT :

The line :

c = &a;

must be replaced by :

c = a;

It means that the value of the pointer 'c' equals the value of the pointer 'a'. So, 'c' and 'a' points to the same address ('b'). The output is :

10

EDIT 2:

If you want to use a double * :

#include <stdio.h>

int main(void)
{
    int b = 10; 
    int *a = NULL;
    int **c = NULL;

    a = &b;
    c = &a;

    printf("%d", **c);

    return 0;
} 

Output:

10

Launch Pycharm from command line (terminal)

I normally alias using built-in application launcher (open) from OS X:

alias pc='open -a /Applications/PyCharm\ CE.app'

Then I can type:

pc myfile1.txt myfiles*.py

Though you can't (easily) pass args to PyCharm, if you want a quick way to open files (without needing to use full pathnames to the file), this does the trick.

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

On mac and sublime text 3 , which version is 3103, the content should be

{
    "shell_cmd": "open -a 'Google Chrome' '$file'"
}

How to read PDF files using Java?

PDFBox is the best library I've found for this purpose, it's comprehensive and really quite easy to use if you're just doing basic text extraction. Examples can be found here.

It explains it on the page, but one thing to watch out for is that the start and end indexes when using setStartPage() and setEndPage() are both inclusive. I skipped over that explanation first time round and then it took me a while to realise why I was getting more than one page back with each call!

Itext is another alternative that also works with C#, though I've personally never used it. It's more low level than PDFBox, so less suited to the job if all you need is basic text extraction.

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

protected $primaryKey = 'SongID';

After adding to my model to tell the primary key because it was taking id(SongID) by default

MySQL error - #1062 - Duplicate entry ' ' for key 2

you can try adding

$db['db_debug'] = FALSE; 

in "your database file".php after that you can modify your database as you like.

Is it possible to specify a different ssh port when using rsync?

when you need to send files through a specific SSH port:

rsync -azP -e "ssh -p PORT_NUMBER" source destination

example

rsync -azP -e "ssh -p 2121" /path/to/files/source user@remoteip:/path/to/files/destination

Using underscores in Java variables and method names

I think any style that breaks a language's own style guidelines (without due reason) is ugly and therefore "bad".

No doubt the code you've seen was written by someone who used to work on a language where underscores were acceptable.

Some people just cannot adapt to new coding styles...

Can't get value of input type="file"?

$('input[type=file]').val()

That'll get you the file selected.

However, you can't set the value yourself.

Full Screen DialogFragment in Android

Try to use setStyle() in onCreate and override onCreateDialog make dialog without title

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme);        
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog dialog = super.onCreateDialog(savedInstanceState);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);        
    return dialog;
}

or just override onCreate() and setStyle fellow the code.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme);        
}

How to restore PostgreSQL dump file into Postgres databases?

The problem with your attempt at the psql command line is the direction of the slashes:

newTestDB-# /i E:\db-rbl-restore-20120511_Dump-20120514.sql   # incorrect
newTestDB-# \i E:/db-rbl-restore-20120511_Dump-20120514.sql   # correct

To be clear, psql commands start with a backslash, so you should have put \i instead. What happened as a result of your typo is that psql ignored everything until finding the first \, which happened to be followed by db, and \db happens to be the psql command for listing table spaces, hence why the output was a List of tablespaces. It was not a listing of "default tables of PostgreSQL" as you said.

Further, it seems that psql expects the filepath argument to delimit directories using the forward slash regardless of OS (thus on Windows this would be counter-intuitive).

It is worth noting that your attempt at "elevating permissions" had no relation to the outcome of the command you attempted to execute. Also, you did not say what caused the supposed "Permission Denied" error.

Finally, the extension on the dump file does not matter, in fact you don't even need an extension. Indeed, pgAdmin suggests a .backup extension when selecting a backup filename, but you can actually make it whatever you want, again, including having no extension at all. The problem is that pgAdmin seems to only allow a "Restore" of "Custom or tar" or "Directory" dumps (at least this is the case in the MAC OS X version of the app), so just use the psql \i command as shown above.

What is the difference between Html.Hidden and Html.HiddenFor

The Html.Hidden creates a hidden input but you have to specify the name and all the attributes you want to give that field and value. The Html.HiddenFor creates a hidden input for the object that you pass to it, they look like this:

Html.Hidden("yourProperty",model.yourProperty);

Html.HiddenFor(m => m.yourProperty)

In this case the output is the same!

Circle drawing with SVG's arc path

It's a good idea that using two arc command to draw a full circle.

usually, I use ellipse or circle element to draw a full circle.

What is the difference between call and apply?

Follows an extract from Closure: The Definitive Guide by Michael Bolin. It might look a bit lengthy, but it's saturated with a lot of insight. From "Appendix B. Frequently Misunderstood JavaScript Concepts":


What this Refers to When a Function is Called

When calling a function of the form foo.bar.baz(), the object foo.bar is referred to as the receiver. When the function is called, it is the receiver that is used as the value for this:

var obj = {};
obj.value = 10;
/** @param {...number} additionalValues */
obj.addValues = function(additionalValues) {
  for (var i = 0; i < arguments.length; i++) {
    this.value += arguments[i];
  }
  return this.value;
};
// Evaluates to 30 because obj is used as the value for 'this' when
// obj.addValues() is called, so obj.value becomes 10 + 20.
obj.addValues(20);

If there is no explicit receiver when a function is called, then the global object becomes the receiver. As explained in "goog.global" on page 47, window is the global object when JavaScript is executed in a web browser. This leads to some surprising behavior:

var f = obj.addValues;
// Evaluates to NaN because window is used as the value for 'this' when
// f() is called. Because and window.value is undefined, adding a number to
// it results in NaN.
f(20);
// This also has the unintentional side effect of adding a value to window:
alert(window.value); // Alerts NaN

Even though obj.addValues and f refer to the same function, they behave differently when called because the value of the receiver is different in each call. For this reason, when calling a function that refers to this, it is important to ensure that this will have the correct value when it is called. To be clear, if this were not referenced in the function body, then the behavior of f(20) and obj.addValues(20) would be the same.

Because functions are first-class objects in JavaScript, they can have their own methods. All functions have the methods call() and apply() which make it possible to redefine the receiver (i.e., the object that this refers to) when calling the function. The method signatures are as follows:

/**
* @param {*=} receiver to substitute for 'this'
* @param {...} parameters to use as arguments to the function
*/
Function.prototype.call;
/**
* @param {*=} receiver to substitute for 'this'
* @param {Array} parameters to use as arguments to the function
*/
Function.prototype.apply;

Note that the only difference between call() and apply() is that call() receives the function parameters as individual arguments, whereas apply() receives them as a single array:

// When f is called with obj as its receiver, it behaves the same as calling
// obj.addValues(). Both of the following increase obj.value by 60:
f.call(obj, 10, 20, 30);
f.apply(obj, [10, 20, 30]);

The following calls are equivalent, as f and obj.addValues refer to the same function:

obj.addValues.call(obj, 10, 20, 30);
obj.addValues.apply(obj, [10, 20, 30]);

However, since neither call() nor apply() uses the value of its own receiver to substitute for the receiver argument when it is unspecified, the following will not work:

// Both statements evaluate to NaN
obj.addValues.call(undefined, 10, 20, 30);
obj.addValues.apply(undefined, [10, 20, 30]);

The value of this can never be null or undefined when a function is called. When null or undefined is supplied as the receiver to call() or apply(), the global object is used as the value for receiver instead. Therefore, the previous code has the same undesirable side effect of adding a property named value to the global object.

It may be helpful to think of a function as having no knowledge of the variable to which it is assigned. This helps reinforce the idea that the value of this will be bound when the function is called rather than when it is defined.


End of extract.

Border Radius of Table is not working

A note to this old question:

My reset.css had set border-spacing: 0, causing the corners to get cut off. I had to set it to 3px for my radius to work properly (value will depend on the radius in question).

How to change Status Bar text color in iOS

This does seem to be an issue with the current build of Xcode and iOS 7.

Some related content on Apple's Developer Forums is in a search for UIStatusBarStyleLightContent in "iOS 7 Beta Livability" on the Apple Developer Forums* (currently 32 posts).

I came across it trying to set it to the light version.

(This is just a follow up on Aaron's answer.)

Show a message box from a class in c#?

using System.Windows.Forms;

public class message
{
    static void Main()
    {  
        MessageBox.Show("Hello World!"); 
    }
}

Serialize Property as Xml Attribute in Element

You will need wrapper classes:

public class SomeIntInfo
{
    [XmlAttribute]
    public int Value { get; set; }
}

public class SomeStringInfo
{
    [XmlAttribute]
    public string Value { get; set; }
}

public class SomeModel
{
    [XmlElement("SomeStringElementName")]
    public SomeStringInfo SomeString { get; set; }

    [XmlElement("SomeInfoElementName")]
    public SomeIntInfo SomeInfo { get; set; }
}

or a more generic approach if you prefer:

public class SomeInfo<T>
{
    [XmlAttribute]
    public T Value { get; set; }
}

public class SomeModel
{
    [XmlElement("SomeStringElementName")]
    public SomeInfo<string> SomeString { get; set; }

    [XmlElement("SomeInfoElementName")]
    public SomeInfo<int> SomeInfo { get; set; }
}

And then:

class Program
{
    static void Main()
    {
        var model = new SomeModel
        {
            SomeString = new SomeInfo<string> { Value = "testData" },
            SomeInfo = new SomeInfo<int> { Value = 5 }
        };
        var serializer = new XmlSerializer(model.GetType());
        serializer.Serialize(Console.Out, model);
    }
}

will produce:

<?xml version="1.0" encoding="ibm850"?>
<SomeModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SomeStringElementName Value="testData" />
  <SomeInfoElementName Value="5" />
</SomeModel>

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

[TestMethod]
public void BraceEscapingTest()
{
    var result = String.Format("Foo {{0}}", "1,2,3");  //"1,2,3" is not parsed
    Assert.AreEqual("Foo {0}", result);

    result = String.Format("Foo {{{0}}}", "1,2,3");
    Assert.AreEqual("Foo {1,2,3}", result);

    result = String.Format("Foo {0} {{bar}}", "1,2,3");
    Assert.AreEqual("Foo 1,2,3 {bar}", result);

    result = String.Format("{{{0:N}}}", 24); //24 is not parsed, see @Guru Kara answer
    Assert.AreEqual("{N}", result);

    result = String.Format("{0}{1:N}{2}", "{", 24, "}");
    Assert.AreEqual("{24.00}", result);

    result = String.Format("{{{0}}}", 24.ToString("N"));
    Assert.AreEqual("{24.00}", result);
}

Spring JSON request getting 406 (not Acceptable)

I was having the same problem because I was missing the @EnableWebMvc annotation. (All of my spring configurations are annotation-based, the XML equivalent would be mvc:annotation-driven)

Is ncurses available for windows?

Such a thing probably does not exist "as-is". It doesn't really exist on Linux or other UNIX-like operating systems either though.

ncurses is only a library that helps you manage interactions with the underlying terminal environment. But it doesn't provide a terminal emulator itself.

The thing that actually displays stuff on the screen (which in your requirement is listed as "native resizable win32 windows") is usually called a Terminal Emulator. If you don't like the one that comes with Windows (you aren't alone; no person on Earth does) there are a few alternatives. There is Console, which in my experience works sometimes and appears to just wrap an underlying Windows terminal emulator (I don't know for sure, but I'm guessing, since there is a menu option to actually get access to that underlying terminal emulator, and sure enough an old crusty Windows/DOS box appears which mirrors everything in the Console window).

A better option

Another option, which may be more appealing is puttycyg. It hooks in to Putty (which, coming from a Linux background, is pretty close to what I'm used to, and free) but actually accesses an underlying cygwin instead of the Windows command interpreter (CMD.EXE). So you get all the benefits of Putty's awesome terminal emulator, as well as nice ncurses (and many other) libraries provided by cygwin. Add a couple command line arguments to the Shortcut that launches Putty (or the Batch file) and your app can be automatically launched without going through Putty's UI.

How to download a file from a website in C#

You can use this code to Download file from a WebSite to Desktop:

using System.Net;

WebClient client = new WebClient ();
client.DownloadFileAsync(new Uri("http://www.Address.com/File.zip"), Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "File.zip");

What is the difference between signed and unsigned int

In laymen's terms an unsigned int is an integer that can not be negative and thus has a higher range of positive values that it can assume. A signed int is an integer that can be negative but has a lower positive range in exchange for more negative values it can assume.

Bootstrap 3 .col-xs-offset-* doesn't work?

Its not working because col-xs-offset-* is mentioned out of the media query. if you want to use it, you have to mention all the offset (eg: class="col-xs-offset-3 col-sm-offset-2 col-md-offset-1 col-lg-offset-0")

But this is not right, they should mention col-xs-offset-* in the media query

How do I run a node.js app as a background service?

If you are running OSX, then the easiest way to produce a true system process is to use launchd to launch it.

Build a plist like this, and put it into the /Library/LaunchDaemons with the name top-level-domain.your-domain.application.plist (you need to be root when placing it):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>top-level-domain.your-domain.application</string>

    <key>WorkingDirectory</key>
    <string>/your/preferred/workingdirectory</string>

    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/node</string>
        <string>your-script-file</string>
    </array>

    <key>RunAtLoad</key>
    <true/>

    <key>KeepAlive</key>
    <true/>

</dict>
</plist>

When done, issue this (as root):

launchctl load /Library/LaunchDaemons/top-level-domain.your-domain.application.plist
launchctl start top-level-domain.your-domain.application

and you are running.

And you will still be running after a restart.

For other options in the plist look at the man page here: https://developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man5/launchd.plist.5.html

How to enumerate an enum with String type?

Here's my suggested approach. It's not completely satisfactory (I'm very new to Swift and OOP!) but maybe someone can refine it. The idea is to have each enum provide its own range information as .first and .last properties. It adds just two lines of code to each enum: still a bit hard-coded, but at least it's not duplicating the whole set. It does require modifying the Suit enum to be an Int like the Rank enum is, instead of untyped.

Rather than echo the whole solution, here's the code I added to the . enum, somewhere after the case statements (Suit enum is similar):

var first: Int { return Ace.toRaw() }
var last: Int { return King.toRaw() }

and the loop I used to build the deck as an array of String. (The problem definition did not state how the deck was to be structured.)

func createDeck() -> [String] {
    var deck: [String] = []
    var card: String
    for r in Rank.Ace.first...Rank.Ace.last {
        for s in Suit.Hearts.first...Suit.Hearts.last {
            card = Rank.simpleDescription( Rank.fromRaw(r)!)() + " of " + Suit.simpleDescription( Suit.fromRaw(s)!)()
           deck.append( card)
       }
    }
    return deck
}

It's unsatisfactory because the properties are associated to an element rather than to the enum. But it does add clarity to the 'for' loops. I'd like it to say Rank.first instead of Rank.Ace.first. It works (with any element), but it's ugly. Can someone show how to elevate that to the enum level?

And to make it work, I lifted the createDeck method out of the Card struct. I could not figure out how to get a [String] array returned from that struct, and that seems a bad place to put such a method anyway.

Difference between Return and Break statements

No offence, but none of the other answers (so far) has it quite right.

break is used to immediately terminate a for loop, a while loop or a switch statement. You can not break from an if block.

return is used the terminate a method (and possibly return a value).

A return within any loop or block will of course also immediately terminate that loop/block.

What does the [Flags] Enum Attribute mean in C#?

There's something overly verbose to me about the if ((x & y) == y)... construct, especially if x AND y are both compound sets of flags and you only want to know if there's any overlap.

In this case, all you really need to know is if there's a non-zero value[1] after you've bitmasked.

[1] See Jaime's comment. If we were authentically bitmasking, we'd only need to check that the result was positive. But since enums can be negative, even, strangely, when combined with the [Flags] attribute, it's defensive to code for != 0 rather than > 0.

Building off of @andnil's setup...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BitFlagPlay
{
    class Program
    {
        [Flags]
        public enum MyColor
        {
            Yellow = 0x01,
            Green = 0x02,
            Red = 0x04,
            Blue = 0x08
        }

        static void Main(string[] args)
        {
            var myColor = MyColor.Yellow | MyColor.Blue;
            var acceptableColors = MyColor.Yellow | MyColor.Red;

            Console.WriteLine((myColor & MyColor.Blue) != 0);     // True
            Console.WriteLine((myColor & MyColor.Red) != 0);      // False                
            Console.WriteLine((myColor & acceptableColors) != 0); // True
            // ... though only Yellow is shared.

            Console.WriteLine((myColor & MyColor.Green) != 0);    // Wait a minute... ;^D

            Console.Read();
        }
    }
}

How to execute a remote command over ssh with arguments?

I'm using the following to execute commands on the remote from my local computer:

ssh -i ~/.ssh/$GIT_PRIVKEY user@$IP "bash -s" < localpath/script.sh $arg1 $arg2

Hide div by default and show it on click with bootstrap

Try this one:

<button class="button" onclick="$('#target').toggle();">
    Show/Hide
</button>
<div id="target" style="display: none">
    Hide show.....
</div>

what is reverse() in Django

The reverse() is used to adhere the django DRY principle i.e if you change the url in future then you can reference that url using reverse(urlname).

How can I close a login form and show the main form without my application closing?

I would do this the other way round.

In the OnLoad event for your Main form show the Logon form as a dialog. If the dialog result of that is OK then allow Main to continue loading, if the result is authentication failure then abort the load and show the message box.

EDIT Code sample(s)

private void MainForm_Load(object sender, EventArgs e)
{
    this.Hide();

    LogonForm logon = new LogonForm();

    if (logon.ShowDialog() != DialogResult.OK)
    {
        //Handle authentication failures as necessary, for example:
        Application.Exit();
    }
    else
    {
        this.Show();
    }
}

Another solution would be to show the LogonForm from the Main method in program.cs, something like this:

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    LogonForm logon = new LogonForm();

    Application.Run(logon);

    if (logon.LogonSuccessful)
    {
        Application.Run(new MainForm());
    }
}

In this example your LogonForm would have to expose out a LogonSuccessful bool property that is set to true when the user has entered valid credentials

Creating and Update Laravel Eloquent

check if a user exists or not. If not insert

$exist = DB::table('User')->where(['username'=>$username,'password'=>$password])->get();
if(count($exist)  >0) {
    echo "User already exist";;
}
else  {
    $data=array('username'=>$username,'password'=>$password);
    DB::table('User')->insert($data);
}
Laravel 5.4           

How to validate an email address in JavaScript

Regex for validating email address

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])+

Does WGET timeout?

The default timeout is 900 second. You can specify different timeout.

-T seconds
--timeout=seconds

The default is to retry 20 times. You can specify different tries.

-t number
--tries=number

link: wget man document

NuGet auto package restore does not work with MSBuild

Ian Kemp has the answer (have some points btw..), this is to simply add some meat to one of his steps.

The reason I ended up here was that dev's machines were building fine, but the build server simply wasn't pulling down the packages required (empty packages folder) and therefore the build was failing. Logging onto the build server and manually building the solution worked, however.

To fulfil the second of Ians 3 point steps (running nuget restore), you can create an MSBuild target running the exec command to run the nuget restore command, as below (in this case nuget.exe is in the .nuget folder, rather than on the path), which can then be run in a TeamCity build step (other CI available...) immediately prior to building the solution

<Target Name="BeforeBuild">
  <Exec Command="..\.nuget\nuget restore ..\MySolution.sln"/>
</Target>

For the record I'd already tried the "nuget installer" runner type but this step was hanging on web projects (worked for DLL's and Windows projects)

find filenames NOT ending in specific extensions on Unix?

Other solutions on this page aren't desirable if you have a long list of extensions -- maintaining a long sequence of -not -name 'this' -not -name 'that' -not -name 'other' would be tedious and error-prone -- or if the search is programmatic and the list of extensions is built at runtime.

For those situations, a solution that more clearly separates data (the list of extensions) and code (the parameters to find) may be desirable. Given a directory & file structure that looks like this:

.
+-- a
    +-- 1.txt
    +-- 15.xml
    +-- 8.dll
    +-- b
    ¦   +-- 16.xml
    ¦   +-- 2.txt
    ¦   +-- 9.dll
    ¦   +-- c
    ¦       +-- 10.dll
    ¦       +-- 17.xml
    ¦       +-- 3.txt
    +-- d
    ¦   +-- 11.dll
    ¦   +-- 18.xml
    ¦   +-- 4.txt
    ¦   +-- e
    ¦       +-- 12.dll
    ¦       +-- 19.xml
    ¦       +-- 5.txt
    +-- f
        +-- 13.dll
        +-- 20.xml
        +-- 6.txt
        +-- g
            +-- 14.dll
            +-- 21.xml
            +-- 7.txt

You can do something like this:

## data section, list undesired extensions here
declare -a _BADEXT=(xml dll)

## code section, this never changes
BADEXT="$( IFS="|" ; echo "${_BADEXT[*]}" | sed 's/|/\\|/g' )"
find . -type f ! -regex ".*\.\($BADEXT\)"

Which results in:

./a/1.txt
./a/b/2.txt
./a/b/c/3.txt
./a/d/4.txt
./a/d/e/5.txt
./a/f/6.txt
./a/f/g/7.txt

You can change the extensions list without changing the code block.

NOTE doesn't work with native OSX find - use gnu find instead.

How do I get and set Environment variables in C#?

Use the System.Environment class.

The methods

var value = System.Environment.GetEnvironmentVariable(variable [, Target])

and

System.Environment.SetEnvironmentVariable(variable, value [, Target])

will do the job for you.

The optional parameter Target is an enum of type EnvironmentVariableTarget and it can be one of: Machine, Process, or User. If you omit it, the default target is the current process.

Absolute position of an element on the screen using jQuery

See .offset() here in the jQuery doc. It gives the position relative to the document, not to the parent. You perhaps have .offset() and .position() confused. If you want the position in the window instead of the position in the document, you can subtract off the .scrollTop() and .scrollLeft() values to account for the scrolled position.

Here's an excerpt from the doc:

The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.

To combine these:

var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft(); 

You can try it here (scroll to see the numbers change): http://jsfiddle.net/jfriend00/hxRPQ/

Adding :default => true to boolean in existing Rails column

If you don't want to create another migration-file for a small, recent change - from Rails Console:

ActiveRecord::Migration.change_column :profiles, :show_attribute, :boolean, :default => true

Then exit and re-enter rails console, so DB-Changes will be in-effect. Then, if you do this ...

Profile.new()

You should see the "show_attribute" default-value as true.

For existing records, if you want to preserve existing "false" settings and only update "nil" values to your new default:

Profile.all.each{|profile| profile.update_attributes(:show_attribute => (profile.show_attribute == nil ? true : false))  }

Update the migration that created this table, so any future builds of the DB will get it right from the onset. Also run the same process on any deployed-instances of the DB.

If using the "new db migration" method, you can do the update of existing nil-values in that migration.

Mongoose query where value is not null

total count the documents where the value of the field is not equal to the specified value.

async function getRegisterUser() {
    return Login.count({"role": { $ne: 'Super Admin' }}, (err, totResUser) => {
        if (err) {
            return err;
        }
        return totResUser;
    })
}

Why is it common to put CSRF prevention tokens in cookies?

A good reason, which you have sort of touched on, is that once the CSRF cookie has been received, it is then available for use throughout the application in client script for use in both regular forms and AJAX POSTs. This will make sense in a JavaScript heavy application such as one employed by AngularJS (using AngularJS doesn't require that the application will be a single page app, so it would be useful where state needs to flow between different page requests where the CSRF value cannot normally persist in the browser).

Consider the following scenarios and processes in a typical application for some pros and cons of each approach you describe. These are based on the Synchronizer Token Pattern.

Request Body Approach

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. If not yet generated for this session, server generates CSRF token, stores it against the user session and outputs it to a hidden field.
  5. User submits form.
  6. Server checks hidden field matches session stored token.

Advantages:

  • Simple to implement.
  • Works with AJAX.
  • Works with forms.
  • Cookie can actually be HTTP Only.

Disadvantages:

  • All forms must output the hidden field in HTML.
  • Any AJAX POSTs must also include the value.
  • The page must know in advance that it requires the CSRF token so it can include it in the page content so all pages must contain the token value somewhere, which could make it time consuming to implement for a large site.

Custom HTTP Header (downstream)

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. Page loads in browser, then an AJAX request is made to retrieve the CSRF token.
  5. Server generates CSRF token (if not already generated for session), stores it against the user session and outputs it to a header.
  6. User submits form (token is sent via hidden field).
  7. Server checks hidden field matches session stored token.

Advantages:

Disadvantages:

  • Doesn't work without an AJAX request to get the header value.
  • All forms must have the value added to its HTML dynamically.
  • Any AJAX POSTs must also include the value.
  • The page must make an AJAX request first to get the CSRF token, so it will mean an extra round trip each time.
  • Might as well have simply output the token to the page which would save the extra request.

Custom HTTP Header (upstream)

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. If not yet generated for this session, server generates CSRF token, stores it against the user session and outputs it in the page content somewhere.
  5. User submits form via AJAX (token is sent via header).
  6. Server checks custom header matches session stored token.

Advantages:

Disadvantages:

  • Doesn't work with forms.
  • All AJAX POSTs must include the header.

Custom HTTP Header (upstream & downstream)

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. Page loads in browser, then an AJAX request is made to retrieve the CSRF token.
  5. Server generates CSRF token (if not already generated for session), stores it against the user session and outputs it to a header.
  6. User submits form via AJAX (token is sent via header) .
  7. Server checks custom header matches session stored token.

Advantages:

Disadvantages:

  • Doesn't work with forms.
  • All AJAX POSTs must also include the value.
  • The page must make an AJAX request first to get the CRSF token, so it will mean an extra round trip each time.

Set-Cookie

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. Server generates CSRF token, stores it against the user session and outputs it to a cookie.
  5. User submits form via AJAX or via HTML form.
  6. Server checks custom header (or hidden form field) matches session stored token.
  7. Cookie is available in browser for use in additional AJAX and form requests without additional requests to server to retrieve the CSRF token.

Advantages:

  • Simple to implement.
  • Works with AJAX.
  • Works with forms.
  • Doesn't necessarily require an AJAX request to get the cookie value. Any HTTP request can retrieve it and it can be appended to all forms/AJAX requests via JavaScript.
  • Once the CSRF token has been retrieved, as it is stored in a cookie the value can be reused without additional requests.

Disadvantages:

  • All forms must have the value added to its HTML dynamically.
  • Any AJAX POSTs must also include the value.
  • The cookie will be submitted for every request (i.e. all GETs for images, CSS, JS, etc, that are not involved in the CSRF process) increasing request size.
  • Cookie cannot be HTTP Only.

So the cookie approach is fairly dynamic offering an easy way to retrieve the cookie value (any HTTP request) and to use it (JS can add the value to any form automatically and it can be employed in AJAX requests either as a header or as a form value). Once the CSRF token has been received for the session, there is no need to regenerate it as an attacker employing a CSRF exploit has no method of retrieving this token. If a malicious user tries to read the user's CSRF token in any of the above methods then this will be prevented by the Same Origin Policy. If a malicious user tries to retrieve the CSRF token server side (e.g. via curl) then this token will not be associated to the same user account as the victim's auth session cookie will be missing from the request (it would be the attacker's - therefore it won't be associated server side with the victim's session).

As well as the Synchronizer Token Pattern there is also the Double Submit Cookie CSRF prevention method, which of course uses cookies to store a type of CSRF token. This is easier to implement as it does not require any server side state for the CSRF token. The CSRF token in fact could be the standard authentication cookie when using this method, and this value is submitted via cookies as usual with the request, but the value is also repeated in either a hidden field or header, of which an attacker cannot replicate as they cannot read the value in the first place. It would be recommended to choose another cookie however, other than the authentication cookie so that the authentication cookie can be secured by being marked HttpOnly. So this is another common reason why you'd find CSRF prevention using a cookie based method.

How to publish a website made by Node.js to Github Pages?

GitHub pages host only static HTML pages. No server side technology is supported, so Node.js applications won't run on GitHub pages. There are lots of hosting providers, as listed on the Node.js wiki.

App fog seems to be the most economical as it provides free hosting for projects with 2GB of RAM (which is pretty good if you ask me).
As stated here, AppFog removed their free plan for new users.

If you want to host static pages on GitHub, then read this guide. If you plan on using Jekyll, then this guide will be very helpful.

How to clear gradle cache?

My ~/.gradle/caches/ folder was using 14G.

After using the following solution, it went from 14G to 1.7G.

$ rm -rf ~/.gradle/caches/transforms-*
$ rm -rf ~/.gradle/caches/build-cache-*

Bonus

This command shows you in detail the used cache space

$ sudo du -ah --max-depth = 1 ~/.gradle/caches/ | sort -hr

Making a DateTime field in a database automatic?

Yes, here's an example:

CREATE TABLE myTable ( col1 int, createdDate datetime DEFAULT(getdate()), updatedDate datetime DEFAULT(getdate()) )

You can INSERT into the table without indicating the createdDate and updatedDate columns:

INSERT INTO myTable (col1) VALUES (1)

Or use the keyword DEFAULT:

INSERT INTO myTable (col1, createdDate, updatedDate) VALUES (1, DEFAULT, DEFAULT)

Then create a trigger for updating the updatedDate column:

CREATE TRIGGER dbo.updateMyTable 
ON dbo.myTable
FOR UPDATE 
AS 
BEGIN 
    IF NOT UPDATE(updatedDate) 
        UPDATE dbo.myTable SET updatedDate=GETDATE() 
        WHERE col1 IN (SELECT col1 FROM inserted) 
END 
GO

What is "string[] args" in Main class for?

Further to everyone else's answer, you should note that the parameters are optional in C# if your application does not use command line arguments.

This code is perfectly valid:

internal static Program
{
    private static void Main()
    {
        // Get on with it, without any arguments...
    }
}

HTTP test server accepting GET/POST requests

If you need or want a simple HTTP server with the following:

  • Can be run locally or in a network sealed from the public Internet
  • Has some basic auth
  • Handles POST requests

I built one on top of the excellent SimpleHTTPAuthServer already on PyPI. This adds handling of POST requests: https://github.com/arielampol/SimpleHTTPAuthServerWithPOST

Otherwise, all the other options publicly available are already so good and robust.

Javascript geocoding from address to latitude and longitude numbers not working

The script tag to the api has changed recently. Use something like this to query the Geocoding API and get the JSON object back

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/geocode/json?address=THE_ADDRESS_YOU_WANT_TO_GEOCODE&key=YOUR_API_KEY"></script>

The address could be something like

1600+Amphitheatre+Parkway,+Mountain+View,+CA (URI Encoded; you should Google it. Very useful)

or simply

1600 Amphitheatre Parkway, Mountain View, CA

By entering this address https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY inside the browser, along with my API Key, I get back a JSON object which contains the Latitude & Longitude for the city of Moutain view, CA.

{"results" : [
  {
     "address_components" : [
        {
           "long_name" : "1600",
           "short_name" : "1600",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Amphitheatre Parkway",
           "short_name" : "Amphitheatre Pkwy",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Mountain View",
           "short_name" : "Mountain View",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Santa Clara County",
           "short_name" : "Santa Clara County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "California",
           "short_name" : "CA",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "94043",
           "short_name" : "94043",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
     "geometry" : {
        "location" : {
           "lat" : 37.4222556,
           "lng" : -122.0838589
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 37.4236045802915,
              "lng" : -122.0825099197085
           },
           "southwest" : {
              "lat" : 37.4209066197085,
              "lng" : -122.0852078802915
           }
        }
     },
     "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
     "types" : [ "street_address" ]
  }],"status" : "OK"}

Web Frameworks such like AngularJS allow us to perform these queries with ease.

How to make the web page height to fit screen height

Fixed positioning will do what you need:

#main
{         
    position:fixed;
    top:0px;
    bottom:0px;
    left:0px;
    right:0px;
}

Printing Batch file results to a text file

Step 1: Simply put all the required code in a "MAIN.BAT" file.

Step 2: Create another bat file, say MainCaller.bat, and just copy/paste these 3 lines of code:

REM THE MAIN FILE WILL BE CALLED FROM HERE..........
CD "File_Path_Where_Main.bat_is_located"
MAIN.BAT > log.txt

Step 3: Just double click "MainCaller.bat".

All the output will be logged into the text file named "log".

onchange event for html.dropdownlist

You can try this if you are passing a value to the action method.

@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem() { Text = "Newest to Oldest", Value = "0" }, new SelectListItem() { Text = "Oldest to Newest", Value = "1" }},new { onchange = "document.location.href = '/ControllerName/ActionName?id=' + this.options[this.selectedIndex].value;" })

Remove the query string in case of no parameter passing.

Submit form using AJAX and jQuery

There is a nice form plugin that allows you to send an HTML form asynchroniously.

$(document).ready(function() { 
    $('#myForm1').ajaxForm(); 
});

or

$("select").change(function(){
    $('#myForm1').ajaxSubmit();
});

to submit the form immediately

What is the difference between atan and atan2 in C++?

Consider a right angled triangle. We label the hypotenuse r, the horizontal side y and the vertical side x. The angle of interest α is the angle between x and r.

C++ atan2(y, x) will give us the value of angle α in radians. atan is used if we only know or are interested in y/x not y and x individually. So if p = y/x then to get α we'd use atan(p).

You cannot use atan2 to determine the quadrant, you can use atan2 only if you already know which quadrant your in! In particular positive x and y imply the first quadrant, positive y and negative x, the second and so on. atan or atan2 themselves simply return a positive or a negative number, nothing more.

Limit characters displayed in span

use js:

 $(document).ready(function ()
   { $(".class-span").each(function(i){
        var len=$(this).text().trim().length;
        if(len>100)
        {
            $(this).text($(this).text().substr(0,100)+'...');
        }
    });
 });

Prevent overwriting a file using cmd if exist

As in the answer of Escobar Ceaser, I suggest to use quotes arround the whole path. It's the common way to wrap the whole path in "", not only separate directory names within the path.

I had a similar issue that it didn't work for me. But it was no option to use "" within the path for separate directory names because the path contained environment variables, which theirself cover more than one directory hierarchies. The conclusion was that I missed the space between the closing " and the (

The correct version, with the space before the bracket, would be

If NOT exist "C:\Documents and Settings\John\Start Menu\Programs\Software Folder" (
 start "\\filer\repo\lab\software\myapp\setup.exe"
 pause
) 

Proper way to exit command line program?

if you do ctrl-z and then type exit it will close background applications.

Ctrl+Q is another good way to kill the application.

How to create a List with a dynamic object type

It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.

Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.

DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj

...

The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.

var DyObjectsList = new List<dynamic>; 
if (condition1) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = true; 
    DyObj.Message = "Message 1"; 
    DyObjectsList .Add(DyObj); 
} 
if (condition2) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = false; 
    DyObj.Message = "Message 2"; 
    DyObjectsList .Add(DyObj); 
} 

your resulting List essentially looks like this

DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj

Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.

However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.

Checking if a variable is initialized

Variable that is not defined will cause compilation error.

What you're asking is about checking if it is initialized. But initialization is just a value, that you should choose and assign in the constructor.

For example:

class MyClass
{
    MyClass() : mCharacter('0'), mDecimal(-1.0){};
    void SomeMethod();

    char mCharacter;
    double mDecimal;
};

void MyClass::SomeMethod()
{
    if ( mCharacter != '0')
    {
        // touched after the constructor
        // do something with mCharacter.
    }

    if ( mDecimal != -1.0 )
    {
        // touched after the constructor
        // define mDecimal.
    }
}

You should initialize to a default value that will mean something in the context of your logic, of course.

Microsoft.ReportViewer.Common Version=12.0.0.0

here the link to webreports version 12 https://www.nuget.org/packages/Microsoft.ReportViewer.WebForms.v12/12.0.0?_src=template

after the package installed

on your toolbox browse the dll reference it to bin then that's it run the visual studio

Use and meaning of "in" in an if statement?

Maybe these examples will help illustrate what in does. It basically translate to Is this item in this other item?

listOfNums = [ 1, 2, 3, 4, 5, 6, 45, 'j' ]

>>> 3 in listOfNums:
>>> True

>>> 'j' in listOfNums:
>>> True

>>> 66 in listOfNums:
>>> False

python NameError: name 'file' is not defined

file() is not supported in Python 3

Use open() instead; see Built-in Functions - open().

Git stash pop- needs merge, unable to refresh index

First, check git status.
As the OP mentions,

The actual issue was an unresolved merge conflict from the merge, NOT that the stash would cause a merge conflict.

That is where git status would mention that file as being "both modified"

Resolution: Commit the conflicted file.


You can find a similar situation 4 days ago at the time of writing this answer (March 13th, 2012) with this post: "‘Pull is not possible because you have unmerged files’":

julita@yulys:~/GNOME/baobab/help/C$ git stash pop
help/C/scan-remote.page: needs merge
unable to refresh index

What you did was to fix the merge conflict (editing the right file, and committing it):
See "How do I fix merge conflicts in Git?"

What the blog post's author did was:

julita@yulys:~/GNOME/baobab/help/C$ git reset --hard origin/mallard-documentation
HEAD is now at ff2e1e2 Add more steps for optional information for scanning.

I.e aborting the current merge completely, allowing the git stash pop to be applied.
See "Aborting a merge in Git".

Those are your two options.

Set size on background image with CSS?

background-size is working in Chrome 4.1, but so far I couldn't make it work in Firefox 3.6.

Sending SMS from PHP

PHP by itself has no SMS module or functions and doesn't allow you to send SMS.

SMS ( Short Messaging System) is a GSM technology an you need a GSM provider that will provide this service for you and may have an PHP API implementation for it.

Usually people in telecom business use Asterisk to handle calls and sms programming.

How to join (merge) data frames (inner, outer, left, right)

I would recommend checking out Gabor Grothendieck's sqldf package, which allows you to express these operations in SQL.

library(sqldf)

## inner join
df3 <- sqldf("SELECT CustomerId, Product, State 
              FROM df1
              JOIN df2 USING(CustomerID)")

## left join (substitute 'right' for right join)
df4 <- sqldf("SELECT CustomerId, Product, State 
              FROM df1
              LEFT JOIN df2 USING(CustomerID)")

I find the SQL syntax to be simpler and more natural than its R equivalent (but this may just reflect my RDBMS bias).

See Gabor's sqldf GitHub for more information on joins.

Loop through each row of a range in Excel

In Loops, I always prefer to use the Cells class, using the R1C1 reference method, like this:

Cells(rr, col).Formula = ...

This allows me to quickly and easily loop over a Range of cells easily:

Dim r As Long
Dim c As Long

c = GetTargetColumn() ' Or you could just set this manually, like: c = 1

With Sheet1 ' <-- You should always qualify a range with a sheet!

    For r = 1 To 10 ' Or 1 To (Ubound(MyListOfStuff) + 1)

        ' Here we're looping over all the cells in rows 1 to 10, in Column "c"
        .Cells(r, c).Value = MyListOfStuff(r)

        '---- or ----

        '...to easily copy from one place to another (even with an offset of rows and columns)
        .Cells(r, c).Value = Sheet2.Cells(r + 3, 17).Value


    Next r

End With

Check if number is decimal

another way to solve this: preg_match('/^\d+\.\d+$/',$number); :)

Http post and get request in angular 6

You can do a post/get using a library which allows you to use HttpClient with strongly-typed callbacks.

The data and the error are available directly via these callbacks.

The library is called angular-extended-http-client.

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

Very easy to use.

Traditional approach

In the traditional approach you return Observable<HttpResponse<T>> from Service API. This is tied to HttpResponse.

With this approach you have to use .subscribe(x => ...) in the rest of your code.

This creates a tight coupling between the http layer and the rest of your code.

Strongly-typed callback approach

You only deal with your Models in these strongly-typed callbacks.

Hence, The rest of your code only knows about your Models.

Sample usage

The strongly-typed callbacks are

Success:

  • IObservable<T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse<T>

Failure:

  • IObservableError<TError>
  • IObservableHttpError
  • IObservableHttpCustomError<TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client';

and in the @NgModule imports

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

Your Models


export class SearchModel {
    code: string;
}

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core'
import { SearchModel, RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    searchRaceInfo(model: SearchModel, success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        this.client.post<SearchModel, RacingResponse>(url, model, 
                                                      ResponseType.IObservable, success, 
                                                      ErrorType.IObservableError, failure);
    }
}

Your Component

In your Component, your Service is injected and the searchRaceInfo API called as shown below.

  search() {    


    this.service.searchRaceInfo(this.searchModel, response => this.result = response.result,
                                                  error => this.errorMsg = error.className);

  }

Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.

Difference between id and name attributes in HTML

There is no literal difference between an id and name.

name is identifier and is used in http request sent by browser to server as a variable name associated with data contained in the value attribute of element.

The id on the other hand is a unique identifier for browser, client side and JavaScript.Hence form needs an id while its elements need a name.

id is more specifically used in adding attributes to unique elements.In DOM methods,Id is used in Javascript for referencing the specific element you want your action to take place on.

For example:

<html>
<body>

<h1 id="demo"></h1>

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>

Same can be achieved by name attribute, but it's preferred to use id in form and name for small form elements like the input tag or select tag.

What do Push and Pop mean for Stacks?

Ok. As the other answerers explained, a stack is a last-in, first-out data structure. You add an element to the top of the stack with a Push operation. You take an element off the top with a Pop operation. The elements are removed in reverse order to the order they were put inserted (hence Last In, First Out). For example, if you push the elments 1,2,3 in that order, the number 3 will be at the top of the stack. A Pop operation will remove it (it was the last in) and leave 2 at the top of the stack.

Regarding the rest of the lecture, the lecturer tried to describe a stack-based machine that evaluates arithmetic expressions. The machine operates by continuously popping 3 elements from the top of the stack. The first two elements are operands and the third is an operator (+, -, *, /). It then applies this operator on the operands, and pushes the result onto the stack. The process continues until there is only one element on the stack, which is the value of the expression.

So, suppose we begin by pushing the values "+/*23-21*5-41" in left-to-right order onto the stack. We then pop 3 elements from the top. The last in is first out, which means the first 3 element are "1", "4", and "-" in that order. We push the number 3 (the result of 4-1) onto the stack, then pop the three topmost elements: 3, 5, *. Push the result, 15, onto the stack, and so on.

Google Map API - Removing Markers

You need to keep an array of the google.maps.Marker objects to hide (or remove or run other operations on them).

In the global scope:

var gmarkers = [];

Then push the markers on that array as you create them:

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),
    title: locations[i].title,
    icon: icon,
    map:map
});

// Push your newly created marker into the array:
gmarkers.push(marker);

Then to remove them:

function removeMarkers(){
    for(i=0; i<gmarkers.length; i++){
        gmarkers[i].setMap(null);
    }
}

working example (toggles the markers)

code snippet:

_x000D_
_x000D_
var gmarkers = [];_x000D_
var RoseHulman = new google.maps.LatLng(39.483558, -87.324593);_x000D_
var styles = [{_x000D_
  stylers: [{_x000D_
    hue: "black"_x000D_
  }, {_x000D_
    saturation: -90_x000D_
  }]_x000D_
}, {_x000D_
  featureType: "road",_x000D_
  elementType: "geometry",_x000D_
  stylers: [{_x000D_
    lightness: 100_x000D_
  }, {_x000D_
    visibility: "simplified"_x000D_
  }]_x000D_
}, {_x000D_
  featureType: "road",_x000D_
  elementType: "labels",_x000D_
  stylers: [{_x000D_
    visibility: "on"_x000D_
  }]_x000D_
}];_x000D_
_x000D_
var styledMap = new google.maps.StyledMapType(styles, {_x000D_
  name: "Campus"_x000D_
});_x000D_
var mapOptions = {_x000D_
  center: RoseHulman,_x000D_
  zoom: 15,_x000D_
  mapTypeControl: true,_x000D_
  zoomControl: true,_x000D_
  zoomControlOptions: {_x000D_
    style: google.maps.ZoomControlStyle.SMALL_x000D_
  },_x000D_
  mapTypeControlOptions: {_x000D_
    mapTypeIds: ['map_style', google.maps.MapTypeId.HYBRID],_x000D_
    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU_x000D_
  },_x000D_
  scrollwheel: false,_x000D_
  streetViewControl: true,_x000D_
_x000D_
};_x000D_
_x000D_
var map = new google.maps.Map(document.getElementById('map'), mapOptions);_x000D_
map.mapTypes.set('map_style', styledMap);_x000D_
map.setMapTypeId('map_style');_x000D_
_x000D_
var infowindow = new google.maps.InfoWindow({_x000D_
  maxWidth: 300,_x000D_
  infoBoxClearance: new google.maps.Size(1, 1),_x000D_
  disableAutoPan: false_x000D_
});_x000D_
_x000D_
var marker, i, icon, image;_x000D_
_x000D_
var locations = [{_x000D_
  "id": "1",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Alpha Tau Omega Fraternity",_x000D_
  "description": "<p>Alpha Tau Omega house</p>",_x000D_
  "longitude": "-87.321133",_x000D_
  "latitude": "39.484092"_x000D_
}, {_x000D_
  "id": "2",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Apartment Commons",_x000D_
  "description": "<p>The commons area of the apartment-style residential complex</p>",_x000D_
  "longitude": "-87.329282",_x000D_
  "latitude": "39.483599"_x000D_
}, {_x000D_
  "id": "3",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Apartment East",_x000D_
  "description": "<p>Apartment East</p>",_x000D_
  "longitude": "-87.328809",_x000D_
  "latitude": "39.483748"_x000D_
}, {_x000D_
  "id": "4",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Apartment West",_x000D_
  "description": "<p>Apartment West</p>",_x000D_
  "longitude": "-87.329732",_x000D_
  "latitude": "39.483429"_x000D_
}, {_x000D_
  "id": "5",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Baur-Sames-Bogart (BSB) Hall",_x000D_
  "description": "<p>Baur-Sames-Bogart Hall</p>",_x000D_
  "longitude": "-87.325714",_x000D_
  "latitude": "39.482382"_x000D_
}, {_x000D_
  "id": "6",_x000D_
  "category": "6",_x000D_
  "campus_location": "D3",_x000D_
  "title": "Blumberg Hall",_x000D_
  "description": "<p>Blumberg Hall</p>",_x000D_
  "longitude": "-87.328321",_x000D_
  "latitude": "39.483388"_x000D_
}, {_x000D_
  "id": "7",_x000D_
  "category": "1",_x000D_
  "campus_location": "E1",_x000D_
  "title": "The Branam Innovation Center",_x000D_
  "description": "<p>The Branam Innovation Center</p>",_x000D_
  "longitude": "-87.322614",_x000D_
  "latitude": "39.48494"_x000D_
}, {_x000D_
  "id": "8",_x000D_
  "category": "6",_x000D_
  "campus_location": "G3",_x000D_
  "title": "Chi Omega Sorority",_x000D_
  "description": "<p>Chi Omega house</p>",_x000D_
  "longitude": "-87.319905",_x000D_
  "latitude": "39.482071"_x000D_
}, {_x000D_
  "id": "9",_x000D_
  "category": "3",_x000D_
  "campus_location": "D1",_x000D_
  "title": "Cook Stadium/Phil Brown Field",_x000D_
  "description": "<p>Cook Stadium at Phil Brown Field</p>",_x000D_
  "longitude": "-87.325258",_x000D_
  "latitude": "39.485007"_x000D_
}, {_x000D_
  "id": "10",_x000D_
  "category": "1",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Crapo Hall",_x000D_
  "description": "<p>Crapo Hall</p>",_x000D_
  "longitude": "-87.324368",_x000D_
  "latitude": "39.483709"_x000D_
}, {_x000D_
  "id": "11",_x000D_
  "category": "6",_x000D_
  "campus_location": "G3",_x000D_
  "title": "Delta Delta Delta Sorority",_x000D_
  "description": "<p>Delta Delta Delta</p>",_x000D_
  "longitude": "-87.317477",_x000D_
  "latitude": "39.482951"_x000D_
}, {_x000D_
  "id": "12",_x000D_
  "category": "6",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Deming Hall",_x000D_
  "description": "<p>Deming Hall</p>",_x000D_
  "longitude": "-87.325822",_x000D_
  "latitude": "39.483421"_x000D_
}, {_x000D_
  "id": "13",_x000D_
  "category": "5",_x000D_
  "campus_location": "F1",_x000D_
  "title": "Facilities Operations",_x000D_
  "description": "<p>Facilities Operations</p>",_x000D_
  "longitude": "-87.321782",_x000D_
  "latitude": "39.484916"_x000D_
}, {_x000D_
  "id": "14",_x000D_
  "category": "2",_x000D_
  "campus_location": "E3",_x000D_
  "title": "Flame of the Millennium",_x000D_
  "description": "<p>Flame of Millennium sculpture</p>",_x000D_
  "longitude": "-87.323306",_x000D_
  "latitude": "39.481978"_x000D_
}, {_x000D_
  "id": "15",_x000D_
  "category": "5",_x000D_
  "campus_location": "E2",_x000D_
  "title": "Hadley Hall",_x000D_
  "description": "<p>Hadley Hall</p>",_x000D_
  "longitude": "-87.324046",_x000D_
  "latitude": "39.482887"_x000D_
}, {_x000D_
  "id": "16",_x000D_
  "category": "2",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Hatfield Hall",_x000D_
  "description": "<p>Hatfield Hall</p>",_x000D_
  "longitude": "-87.322340",_x000D_
  "latitude": "39.482146"_x000D_
}, {_x000D_
  "id": "17",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Hulman Memorial Union",_x000D_
  "description": "<p>Hulman Memorial Union</p>",_x000D_
  "longitude": "-87.32698",_x000D_
  "latitude": "39.483574"_x000D_
}, {_x000D_
  "id": "18",_x000D_
  "category": "1",_x000D_
  "campus_location": "E2",_x000D_
  "title": "John T. Myers Center for Technological Research with Industry",_x000D_
  "description": "<p>John T. Myers Center for Technological Research With Industry</p>",_x000D_
  "longitude": "-87.322984",_x000D_
  "latitude": "39.484063"_x000D_
}, {_x000D_
  "id": "19",_x000D_
  "category": "6",_x000D_
  "campus_location": "A2",_x000D_
  "title": "Lakeside Hall",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.330612",_x000D_
  "latitude": "39.482804"_x000D_
}, {_x000D_
  "id": "20",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Lambda Chi Alpha Fraternity",_x000D_
  "description": "<p>Lambda Chi Alpha</p>",_x000D_
  "longitude": "-87.320999",_x000D_
  "latitude": "39.48305"_x000D_
}, {_x000D_
  "id": "21",_x000D_
  "category": "1",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Logan Library",_x000D_
  "description": "<p>Logan Library</p>",_x000D_
  "longitude": "-87.324851",_x000D_
  "latitude": "39.483408"_x000D_
}, {_x000D_
  "id": "22",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Mees Hall",_x000D_
  "description": "<p>Mees Hall</p>",_x000D_
  "longitude": "-87.32778",_x000D_
  "latitude": "39.483533"_x000D_
}, {_x000D_
  "id": "23",_x000D_
  "category": "1",_x000D_
  "campus_location": "E2",_x000D_
  "title": "Moench Hall",_x000D_
  "description": "<p>Moench Hall</p>",_x000D_
  "longitude": "-87.323695",_x000D_
  "latitude": "39.483471"_x000D_
}, {_x000D_
  "id": "24",_x000D_
  "category": "1",_x000D_
  "campus_location": "G4",_x000D_
  "title": "Oakley Observatory",_x000D_
  "description": "<p>Oakley Observatory</p>",_x000D_
  "longitude": "-87.31616",_x000D_
  "latitude": "39.483789"_x000D_
}, {_x000D_
  "id": "25",_x000D_
  "category": "1",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Olin Hall and Olin Advanced Learning Center",_x000D_
  "description": "<p>Olin Hall</p>",_x000D_
  "longitude": "-87.324550",_x000D_
  "latitude": "39.482796"_x000D_
}, {_x000D_
  "id": "26",_x000D_
  "category": "6",_x000D_
  "campus_location": "C3",_x000D_
  "title": "Percopo Hall",_x000D_
  "description": "<p>Percopo Hall</p>",_x000D_
  "longitude": "-87.328182",_x000D_
  "latitude": "39.482121"_x000D_
}, {_x000D_
  "id": "27",_x000D_
  "category": "6",_x000D_
  "campus_location": "G3",_x000D_
  "title": "Public Safety Office",_x000D_
  "description": "<p>The Office of Public Safety</p>",_x000D_
  "longitude": "-87.320377",_x000D_
  "latitude": "39.48191"_x000D_
}, {_x000D_
  "id": "28",_x000D_
  "category": "1",_x000D_
  "campus_location": "E2",_x000D_
  "title": "Rotz Mechanical Engineering Lab",_x000D_
  "description": "<p>Rotz Lab</p>",_x000D_
  "longitude": "-87.323247",_x000D_
  "latitude": "39.483711"_x000D_
}, {_x000D_
  "id": "28",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Scharpenberg Hall",_x000D_
  "description": "<p>Scharpenberg Hall</p>",_x000D_
  "longitude": "-87.328139",_x000D_
  "latitude": "39.483582"_x000D_
}, {_x000D_
  "id": "29",_x000D_
  "category": "6",_x000D_
  "campus_location": "G2",_x000D_
  "title": "Sigma Nu Fraternity",_x000D_
  "description": "<p>The Sigma Nu house</p>",_x000D_
  "longitude": "-87.31999",_x000D_
  "latitude": "39.48374"_x000D_
}, {_x000D_
  "id": "30",_x000D_
  "category": "6",_x000D_
  "campus_location": "E4",_x000D_
  "title": "South Campus / Rose-Hulman Ventures",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.330623",_x000D_
  "latitude": "39.417646"_x000D_
}, {_x000D_
  "id": "31",_x000D_
  "category": "6",_x000D_
  "campus_location": "C3",_x000D_
  "title": "Speed Hall",_x000D_
  "description": "<p>Speed Hall</p>",_x000D_
  "longitude": "-87.326632",_x000D_
  "latitude": "39.482121"_x000D_
}, {_x000D_
  "id": "32",_x000D_
  "category": "3",_x000D_
  "campus_location": "C1",_x000D_
  "title": "Sports and Recreation Center",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.3272",_x000D_
  "latitude": "39.484874"_x000D_
}, {_x000D_
  "id": "33",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Triangle Fraternity",_x000D_
  "description": "<p>Triangle fraternity</p>",_x000D_
  "longitude": "-87.32113",_x000D_
  "latitude": "39.483659"_x000D_
}, {_x000D_
  "id": "34",_x000D_
  "category": "6",_x000D_
  "campus_location": "B3",_x000D_
  "title": "White Chapel",_x000D_
  "description": "<p>The White Chapel</p>",_x000D_
  "longitude": "-87.329367",_x000D_
  "latitude": "39.482481"_x000D_
}, {_x000D_
  "id": "35",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Women's Fraternity Housing",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.320753",_x000D_
  "latitude": "39.482401"_x000D_
}, {_x000D_
  "id": "36",_x000D_
  "category": "3",_x000D_
  "campus_location": "E1",_x000D_
  "title": "Intramural Fields",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.321267",_x000D_
  "latitude": "39.485934"_x000D_
}, {_x000D_
  "id": "37",_x000D_
  "category": "3",_x000D_
  "campus_location": "A3",_x000D_
  "title": "James Rendel Soccer Field",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.332135",_x000D_
  "latitude": "39.480933"_x000D_
}, {_x000D_
  "id": "38",_x000D_
  "category": "3",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Art Nehf Field",_x000D_
  "description": "<p>Art Nehf Field</p>",_x000D_
  "longitude": "-87.330923",_x000D_
  "latitude": "39.48022"_x000D_
}, {_x000D_
  "id": "39",_x000D_
  "category": "3",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Women's Softball Field",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.329904",_x000D_
  "latitude": "39.480278"_x000D_
}, {_x000D_
  "id": "40",_x000D_
  "category": "3",_x000D_
  "campus_location": "D1",_x000D_
  "title": "Joy Hulbert Tennis Courts",_x000D_
  "description": "<p>The Joy Hulbert Outdoor Tennis Courts</p>",_x000D_
  "longitude": "-87.323767",_x000D_
  "latitude": "39.485595"_x000D_
}, {_x000D_
  "id": "41",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Speed Lake",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.328134",_x000D_
  "latitude": "39.482779"_x000D_
}, {_x000D_
  "id": "42",_x000D_
  "category": "5",_x000D_
  "campus_location": "F1",_x000D_
  "title": "Recycling Center",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.320098",_x000D_
  "latitude": "39.484593"_x000D_
}, {_x000D_
  "id": "43",_x000D_
  "category": "1",_x000D_
  "campus_location": "F3",_x000D_
  "title": "Army ROTC",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.321342",_x000D_
  "latitude": "39.481992"_x000D_
}, {_x000D_
  "id": "44",_x000D_
  "category": "2",_x000D_
  "campus_location": "  ",_x000D_
  "title": "Self Made Man",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.326272",_x000D_
  "latitude": "39.484481"_x000D_
}, {_x000D_
  "id": "P1",_x000D_
  "category": "4",_x000D_
  "title": "Percopo Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.328756",_x000D_
  "latitude": "39.481587"_x000D_
}, {_x000D_
  "id": "P2",_x000D_
  "category": "4",_x000D_
  "title": "Speed Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.327361",_x000D_
  "latitude": "39.481694"_x000D_
}, {_x000D_
  "id": "P3",_x000D_
  "category": "4",_x000D_
  "title": "Main Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.326245",_x000D_
  "latitude": "39.481446"_x000D_
}, {_x000D_
  "id": "P4",_x000D_
  "category": "4",_x000D_
  "title": "Lakeside Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.330848",_x000D_
  "latitude": "39.483284"_x000D_
}, {_x000D_
  "id": "P5",_x000D_
  "category": "4",_x000D_
  "title": "Hatfield Hall Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.321417",_x000D_
  "latitude": "39.482398"_x000D_
}, {_x000D_
  "id": "P6",_x000D_
  "category": "4",_x000D_
  "title": "Women's Fraternity Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.320977",_x000D_
  "latitude": "39.482315"_x000D_
}, {_x000D_
  "id": "P7",_x000D_
  "category": "4",_x000D_
  "title": "Myers and Facilities Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.322243",_x000D_
  "latitude": "39.48417"_x000D_
}, {_x000D_
  "id": "P8",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.323241",_x000D_
  "latitude": "39.484758"_x000D_
}, {_x000D_
  "id": "P9",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.323617",_x000D_
  "latitude": "39.484311"_x000D_
}, {_x000D_
  "id": "P10",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.325714",_x000D_
  "latitude": "39.484584"_x000D_
}, {_x000D_
  "id": "P11",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.32778",_x000D_
  "latitude": "39.484145"_x000D_
}, {_x000D_
  "id": "P12",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.329035",_x000D_
  "latitude": "39.4848"_x000D_
}];_x000D_
_x000D_
for (i = 0; i < locations.length; i++) {_x000D_
_x000D_
  var marker = new google.maps.Marker({_x000D_
    position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),_x000D_
    title: locations[i].title,_x000D_
    map: map_x000D_
  });_x000D_
  gmarkers.push(marker);_x000D_
  google.maps.event.addListener(marker, 'click', (function(marker, i) {_x000D_
    return function() {_x000D_
      if (locations[i].description !== "" || locations[i].title !== "") {_x000D_
        infowindow.setContent('<div class="content" id="content-' + locations[i].id +_x000D_
          '" style="max-height:300px; font-size:12px;"><h3>' + locations[i].title + '</h3>' +_x000D_
          '<hr class="grey" />' +_x000D_
          hasImage(locations[i]) +_x000D_
          locations[i].description) + '</div>';_x000D_
        infowindow.open(map, marker);_x000D_
      }_x000D_
    }_x000D_
  })(marker, i));_x000D_
}_x000D_
_x000D_
function toggleMarkers() {_x000D_
  for (i = 0; i < gmarkers.length; i++) {_x000D_
    if (gmarkers[i].getMap() != null) gmarkers[i].setMap(null);_x000D_
    else gmarkers[i].setMap(map);_x000D_
  }_x000D_
}_x000D_
_x000D_
function hasImage(location) {_x000D_
  return '';_x000D_
}
_x000D_
html,_x000D_
body,_x000D_
#map {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>_x000D_
<div id="controls">_x000D_
  <input type="button" value="Toggle All Markers" onClick="toggleMarkers()" />_x000D_
</div>_x000D_
<div id="map"></div>
_x000D_
_x000D_
_x000D_

How do I pass multiple parameter in URL?

You can pass multiple parameters as "?param1=value1&param2=value2"

But it's not secure. It's vulnerable to Cross Site Scripting (XSS) Attack.

Your parameter can be simply replaced with a script.

Have a look at this article and article

You can make it secure by using API of StringEscapeUtils

static String   escapeHtml(String str) 
          Escapes the characters in a String using HTML entities.

Even using https url for security without above precautions is not a good practice.

Have a look at related SE question:

Is URLEncoder.encode(string, "UTF-8") a poor validation?

What is the size limit of a post request?

By default, the post request has maximum size of 8mb. But you can modify it according to your requirements. The modification can be done by opening php.ini file (php configuration setting).

Find

post_max_size=8M  //for me, that was on line:771

replace 8 according to your requirements.

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

html select option SELECTED

Just use the array of options, to see, which option is currently selected.

$options = array( 'one', 'two', 'three' );

$output = '';
for( $i=0; $i<count($options); $i++ ) {
  $output .= '<option ' 
             . ( $_GET['sel'] == $options[$i] ? 'selected="selected"' : '' ) . '>' 
             . $options[$i] 
             . '</option>';
}

Sidenote: I would define a value to be some kind of id for each element, else you may run into problems, when two options have the same string representation.

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

You need to add icon.png through visual.

Resouces... / Dravable/ Add ///

Python Remove last char from string and return it

Not only is it the preferred way, it's the only reasonable way. Because strings are immutable, in order to "remove" a char from a string you have to create a new string whenever you want a different string value.

You may be wondering why strings are immutable, given that you have to make a whole new string every time you change a character. After all, C strings are just arrays of characters and are thus mutable, and some languages that support strings more cleanly than C allow mutable strings as well. There are two reasons to have immutable strings: security/safety and performance.

Security is probably the most important reason for strings to be immutable. When strings are immutable, you can't pass a string into some library and then have that string change from under your feet when you don't expect it. You may wonder which library would change string parameters, but if you're shipping code to clients you can't control their versions of the standard library, and malicious clients may change out their standard libraries in order to break your program and find out more about its internals. Immutable objects are also easier to reason about, which is really important when you try to prove that your system is secure against particular threats. This ease of reasoning is especially important for thread safety, since immutable objects are automatically thread-safe.

Performance is surprisingly often better for immutable strings. Whenever you take a slice of a string, the Python runtime only places a view over the original string, so there is no new string allocation. Since strings are immutable, you get copy semantics without actually copying, which is a real performance win.

Eric Lippert explains more about the rationale behind immutable of strings (in C#, not Python) here.

Get column index from column name in python pandas

To modify DSM's answer a bit, get_loc has some weird properties depending on the type of index in the current version of Pandas (1.1.5) so depending on your Index type you might get back an index, a mask, or a slice. This is somewhat frustrating for me because I don't want to modify the entire columns just to extract one variable's index. Much simpler is to avoid the function altogether:

list(df.columns).index('pear')

Very straightforward and probably fairly quick.

How can I select item with class within a DIV?

try this instead $(".video-divs.focused"). This works if you are looking for video-divs that are focused.

Android 5.0 - Add header/footer to a RecyclerView

You can use the library SectionedRecyclerViewAdapter to group your items in sections and add a header to each section, like on the image below:

enter image description here

First you create your section class:

class MySection extends StatelessSection {

    String title;
    List<String> list;

    public MySection(String title, List<String> list) {
        // call constructor with layout resources for this Section header, footer and items 
        super(R.layout.section_header, R.layout.section_item);

        this.title = title;
        this.list = list;
    }

    @Override
    public int getContentItemsTotal() {
        return list.size(); // number of items of this section
    }

    @Override
    public RecyclerView.ViewHolder getItemViewHolder(View view) {
        // return a custom instance of ViewHolder for the items of this section
        return new MyItemViewHolder(view);
    }

    @Override
    public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
        MyItemViewHolder itemHolder = (MyItemViewHolder) holder;

        // bind your view here
        itemHolder.tvItem.setText(list.get(position));
    }

    @Override
    public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
        return new SimpleHeaderViewHolder(view);
    }

    @Override
    public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
        MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder;

        // bind your header view here
        headerHolder.tvItem.setText(title);
    }
}

Then you set up the RecyclerView with your sections and change the SpanSize of the headers with a GridLayoutManager:

// Create an instance of SectionedRecyclerViewAdapter 
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();

// Create your sections with the list of data
MySection section1 = new MySection("My Section 1 title", dataList1);
MySection section2 = new MySection("My Section 2 title", dataList2);

// Add your Sections to the adapter
sectionAdapter.addSection(section1);
sectionAdapter.addSection(section2);

// Set up a GridLayoutManager to change the SpanSize of the header
GridLayoutManager glm = new GridLayoutManager(getContext(), 2);
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
    @Override
    public int getSpanSize(int position) {
        switch(sectionAdapter.getSectionItemViewType(position)) {
            case SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER:
                return 2;
            default:
                return 1;
        }
    }
});

// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(glm);
recyclerView.setAdapter(sectionAdapter);

How to check if a Java 8 Stream is empty?

I would simply use:

stream.count()>0

Bigger Glyphicons

The .btn-lg class has the following CSS in Bootstrap 3 (link):

.btn-lg {
  padding: 10px 16px;
  font-size: 18px;
  line-height: 1.33;
  border-radius: 6px;
}

If you apply the same font-size and line-height to your span (either .glyphicon-link or a newly created .glyphicons-lg if you're going to use this effect in more than one instance), you'll get a Glyphicon the same size as the large button.

NodeJS/express: Cache and 304 status code

I had the same problem in Safari and Chrome (the only ones I've tested) but I just did something that seems to work, at least I haven't been able to reproduce the problem since I added the solution. What I did was add a metatag to the header with a generated timstamp. Doesn't seem right but it's simple :)

<meta name="304workaround" content="2013-10-24 21:17:23">

Update P.S As far as I can tell, the problem disappears when I remove my node proxy (by proxy i mean both express.vhost and http-proxy module), which is weird...

Check if record exists from controller in Rails

ActiveRecord#where will return an ActiveRecord::Relation object (which will never be nil). Try using .empty? on the relation to test if it will return any records.

Javascript Object push() function

    tempData.push( data[index] );

I agree with the correct answer above, but.... your still not giving the index value for the data that you want to add to tempData. Without the [index] value the whole array will be added.

Java int to String - Integer.toString(i) vs new Integer(i).toString()

Another option is the static String.valueOf method.

String.valueOf(i)

It feels slightly more right than Integer.toString(i) to me. When the type of i changes, for example from int to double, the code will stay correct.

Understanding colors on Android (six characters)

On Android, colors are can be specified as RGB or ARGB.

http://en.wikipedia.org/wiki/ARGB

In RGB you have two characters for every color (red, green, blue), and in ARGB you have two additional chars for the alpha channel.

So, if you have 8 characters, it's ARGB, with the first two characters specifying the alpha channel. If you remove the leading two characters it's only RGB (solid colors, no alpha/transparency). If you want to specify a color in your Java source code, you have to use:

int Color.argb (int alpha, int red, int green, int blue)

alpha  Alpha component [0..255] of the color
red    Red component [0..255] of the color
green  Green component [0..255] of the color
blue   Blue component [0..255] of the color

Reference: argb

Is it possible to have empty RequestParam values use the defaultValue?

You can keep primitive type by setting default value, in the your case just add "required = false" property:

@RequestParam(value = "i", required = false, defaultValue = "10") int i

P.S. This page from Spring documentation might be useful: Annotation Type RequestParam

Loop X number of times

Here is a simple way to loop any number of times in PowerShell.

It is the same as the for loop above, but much easier to understand for newer programmers and scripters. It uses a range, and foreach. A range is defined as:

range = lower..upper

or

$range = 1..10

A range can be used directly in a for loop as well, although not the most optimal approach, any performance loss or additional instruction to process would be unnoticeable. The solution is below:

foreach($i in 1..10){
    Write-Host $i
}

Or in your case:

$ActiveCampaigns = 10
foreach($i in 1..$ActiveCampaigns)
{
    Write-Host $i
    If($i==$ActiveCampaigns){
        // Do your stuff on the last iteration here
    }
}

How do I do top 1 in Oracle?

If you want just a first selected row, you can:

select fname from MyTbl where rownum = 1

You can also use analytic functions to order and take the top x:

select max(fname) over (rank() order by some_factor) from MyTbl

MySQL Workbench Dark Theme

Edit: Advise: This answer is old and a better solution can be found in this same page. This answer referred to MySQL Workbench 6.3 and is outdated. If you are using a new version (8.0 as today) look for @VSingh comment in this very page.


Original answer:

Just a copy of Gaston's answer, but with Monokai theme colors.

<!-- 
    dark-gray:         #282828;
    brown-gray:        #49483E;
    gray:              #888888;
    light-gray:        #CCCCCC;
    ghost-white:       #F8F8F0;
    light-ghost-white: #F8F8F2;
    yellow:            #E6DB74;
    blue:              #66D9EF;
    pink:              #F92672;
    purple:            #AE81FF;
    brown:             #75715E;
    orange:            #FD971F;
    light-orange:      #FFD569;
    green:             #A6E22E;
    sea-green:         #529B2F; 
-->
<style id="32" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- STYLE_DEFAULT       !BACKGROUND!   -->
<style id="33" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- STYLE_LINENUMBER                   -->
<style id= "0" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_DEFAULT                  -->
<style id= "1" fore-color="#999999" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_COMMENT                  -->
<style id= "2" fore-color="#999999" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_COMMENTLINE              -->
<style id= "3" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_VARIABLE                 -->
<style id= "4" fore-color="#66D9EF" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_SYSTEMVARIABLE           -->
<style id= "5" fore-color="#66D9EF" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE      -->
<style id= "6" fore-color="#AE81FF" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_NUMBER                   -->
<style id= "7" fore-color="#F92672" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_MAJORKEYWORD             -->
<style id= "8" fore-color="#F92672" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_KEYWORD                  -->
<style id= "9" fore-color="#9B859D" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_DATABASEOBJECT           -->
<style id="10" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_PROCEDUREKEYWORD         -->
<style id="11" fore-color="#E6DB74" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_STRING                   -->
<style id="12" fore-color="#E6DB74" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_SQSTRING                 -->
<style id="13" fore-color="#E6DB74" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_DQSTRING                 -->
<style id="14" fore-color="#F92672" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_OPERATOR                 -->
<style id="15" fore-color="#9B859D" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_FUNCTION                 -->
<style id="16" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_IDENTIFIER               -->
<style id="17" fore-color="#E6DB74" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_QUOTEDIDENTIFIER         -->
<style id="18" fore-color="#529B2F" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_USER1                    -->
<style id="19" fore-color="#529B2F" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_USER2                    -->
<style id="20" fore-color="#529B2F" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_USER3                    -->
<style id="21" fore-color="#66D9EF" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_HIDDENCOMMAND            -->
<style id="22" fore-color="#909090" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_PLACEHOLDER              -->
<!-- All styles again in their variant in a hidden command -->
<style id="65" fore-color="#999999" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_COMMENT                  -->
<style id="66" fore-color="#999999" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_COMMENTLINE              -->
<style id="67" fore-color="#DDDDDD" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_VARIABLE                 -->
<style id="68" fore-color="#66D9EF" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_SYSTEMVARIABLE           -->
<style id="69" fore-color="#66D9EF" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE      -->
<style id="70" fore-color="#AE81FF" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_NUMBER                   -->
<style id="71" fore-color="#F92672" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_MAJORKEYWORD             -->
<style id="72" fore-color="#F92672" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_KEYWORD                  -->
<style id="73" fore-color="#9B859D" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_DATABASEOBJECT           -->
<style id="74" fore-color="#DDDDDD" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_PROCEDUREKEYWORD         -->
<style id="75" fore-color="#E6DB74" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_STRING                   -->
<style id="76" fore-color="#E6DB74" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_SQSTRING                 -->
<style id="77" fore-color="#E6DB74" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_DQSTRING                 -->
<style id="78" fore-color="#F92672" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_OPERATOR                 -->
<style id="79" fore-color="#9B859D" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_FUNCTION                 -->
<style id="80" fore-color="#DDDDDD" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_IDENTIFIER               -->
<style id="81" fore-color="#E6DB74" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_QUOTEDIDENTIFIER         -->
<style id="82" fore-color="#529B2F" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_USER1                    -->
<style id="83" fore-color="#529B2F" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_USER2                    -->
<style id="84" fore-color="#529B2F" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_USER3                    -->
<style id="85" fore-color="#66D9EF" back-color="#888888" bold="No" />   <!-- SCE_MYSQL_HIDDENCOMMAND            -->
<style id="86" fore-color="#AAAAAA" back-color="#888888" bold="No" />   <!-- SCE_MYSQL_PLACEHOLDER              -->

Mysql password expired. Can't connect

mysqladmin -u [username] -p password worked for me on OS X El Capitan and MySQL 5.7.12 Community Server. Example:

$ /usr/local/mysql/bin/mysqladmin -u root -p password
Enter password:
New password:
Confirm new password:
Warning: Since password will be sent to server in plain text, use ssl connection to ensure password safety.

This is similar to pavan sachi's answer, but with password prompts.

My error was "#1862 - Your password has expired. To log in you must change it using a client that supports expired passwords." at phpMyAdmin login screen first time.

jQuery get selected option value (not the text, but the attribute 'value')

It's working better. Try it.

let value = $("select#yourId option").filter(":selected").val();

How to make join queries using Sequelize on Node.js

Model1.belongsTo(Model2, { as: 'alias' })

Model1.findAll({include: [{model: Model2  , as: 'alias'  }]},{raw: true}).success(onSuccess).error(onError);

How can I determine the current CPU utilization from the shell?

Linux does not have any system variables that give the current CPU utilization. Instead, you have to read /proc/stat several times: each column in the cpu(n) lines gives the total CPU time, and you have to take subsequent readings of it to get percentages. See this document to find out what the various columns mean.

Android TabLayout Android Design

I've just managed to setup new TabLayout, so here are the quick steps to do this (????)?*:???

  1. Add dependencies inside your build.gradle file:

    dependencies {
        compile 'com.android.support:design:23.1.1'
    }
    
  2. Add TabLayout inside your layout

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical">
    
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"/>
    
        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    
        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    
    </LinearLayout>
    
  3. Setup your Activity like this:

    import android.os.Bundle;
    import android.support.design.widget.TabLayout;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentPagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    
    public class TabLayoutActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_pull_to_refresh);
    
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
            ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    
            if (toolbar != null) {
                setSupportActionBar(toolbar);
            }
    
            viewPager.setAdapter(new SectionPagerAdapter(getSupportFragmentManager()));
            tabLayout.setupWithViewPager(viewPager);
        }
    
        public class SectionPagerAdapter extends FragmentPagerAdapter {
    
            public SectionPagerAdapter(FragmentManager fm) {
                super(fm);
            }
    
            @Override
            public Fragment getItem(int position) {
                switch (position) {
                    case 0:
                        return new FirstTabFragment();
                    case 1:
                    default:
                        return new SecondTabFragment();
                }
            }
    
            @Override
            public int getCount() {
                return 2;
            }
    
            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                    case 0:
                        return "First Tab";
                    case 1:
                    default:
                        return "Second Tab";
                }
            }
        }
    
    }
    

Find by key deep in a nested array

Another recursive solution, that works for arrays/lists and objects, or a mixture of both:

function deepSearchByKey(object, originalKey, matches = []) {

    if(object != null) {
        if(Array.isArray(object)) {
            for(let arrayItem of object) {
                deepSearchByKey(arrayItem, originalKey, matches);
            }
        } else if(typeof object == 'object') {

            for(let key of Object.keys(object)) {
                if(key == originalKey) {
                    matches.push(object);
                } else {
                    deepSearchByKey(object[key], originalKey, matches);
                }

            }

        }
    }


    return matches;
}

usage:

let result = deepSearchByKey(arrayOrObject, 'key'); // returns an array with the objects containing the key

Adding default parameter value with type hint in Python

Your second way is correct.

def foo(opts: dict = {}):
    pass

print(foo.__annotations__)

this outputs

{'opts': <class 'dict'>}

It's true that's it's not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section makes it clear that keyword arguments works with function annotations in this way.

I strongly advise against using mutable keyword arguments. More information here.

batch/bat to copy folder and content at once

The old way:

xcopy [source] [destination] /E

xcopy is deprecated. Robocopy replaces Xcopy. It comes with Windows 8, 8.1 and 10.

robocopy [source] [destination] /E

robocopy has several advantages:

  • copy paths exceeding 259 characters
  • multithreaded copying

More details here.

how to stop a loop arduino

This isn't published on Arduino.cc but you can in fact exit from the loop routine with a simple exit(0);

This will compile on pretty much any board you have in your board list. I'm using IDE 1.0.6. I've tested it with Uno, Mega, Micro Pro and even the Adafruit Trinket

void loop() {
// All of your code here

/* Note you should clean up any of your I/O here as on exit, 
all 'ON'outputs remain HIGH */

// Exit the loop 
exit(0);  //The 0 is required to prevent compile error.
}

I use this in projects where I wire in a button to the reset pin. Basically your loop runs until exit(0); and then just persists in the last state. I've made some robots for my kids, and each time the press a button (reset) the code starts from the start of the loop() function.

Git - Ignore node_modules folder everywhere

it will automatically create a .gitignore file if not then create a file name .gitignore and add copy & paste the below code

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*

these below are all unnecessary files

See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

and save the .gitignore file and you can upload

How to keep the console window open in Visual C++?

Another option is to use

#include <process.h>
system("pause");

Though this is not very portable because it will only work on Windows, but it will automatically print

Press any key to continue...

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

In our case we were getting UnmarshalException because a wrong Java package was specified in the following. The issue was resolved once the right package was in place:

@Bean
public Unmarshaller tmsUnmarshaller() {
    final Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
    jaxb2Marshaller
            .setPackagesToScan("java.package.to.generated.java.classes.for.xsd");
    return jaxb2Marshaller;
}

Getting a Request.Headers value

Header exists:

if (Request.Headers["XYZComponent"] != null)

or even better:

string xyzHeader = Request.Headers["XYZComponent"];
bool isXYZ;

if (bool.TryParse(xyzHeader, out isXYZ) && isXYZ)

which will check whether it is set to true. This should be fool-proof because it does not care on leading/trailing whitespace and is case-insensitive (bool.TryParse does work on null)

Addon: You could make this more simple with this extension method which returns a nullable boolean. It should work on both invalid input and null.

public static bool? ToBoolean(this string s)
{
    bool result;

    if (bool.TryParse(s, out result))
        return result;
    else
        return null;
}

Usage (because this is an extension method and not instance method this will not throw an exception on null - it may be confusing, though):

if (Request.Headers["XYZComponent"].ToBoolean() == true)

UIButton Image + Text IOS

It's really simple,just add image to background of you button and give text to titlelabel of button for uicontrolstatenormal. That's it.

[btn setBackgroundImage:[UIImage imageNamed:@"img.png"] forState:UIControlStateNormal];
[btn setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
[btn setTitle:@"Click Me" forState:UIControlStateNormal];

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

Unless otherwise definied (<tfoot>, <thead>), browsers put <tr> implicitly in a <tbody>.

You need to put a > tbody in between > table and > tr:

$("div.custList > table > tbody > tr")

Alternatively, you can also be less strict in selecting the rows (the > denotes the immediate child):

$("div.custList table tr")

That said, you can get the immediate <td> children there by $(this).children('td').

Getting URL parameter in java and extract a specific text from that URL

Using pure Java 8

Assumming you want to extract param "v" from url:

             String paramV = Stream.of(url.split("?")[1].split("&"))
                        .map(kv -> kv.split("="))
                        .filter(kv -> "v".equalsIgnoreCase(kv[0]))
                        .map(kv -> kv[1])
                        .findFirst()
                        .orElse("");

Understanding the order() function

Running this little piece of code allowed me to understand the order function

x <- c(3, 22, 5, 1, 77)

cbind(
  index=1:length(x),
  rank=rank(x),
  x, 
  order=order(x), 
  sort=sort(x)
)

     index rank  x order sort
[1,]     1    2  3     4    1
[2,]     2    4 22     1    3
[3,]     3    3  5     3    5
[4,]     4    1  1     2   22
[5,]     5    5 77     5   77

Reference: http://r.789695.n4.nabble.com/I-don-t-understand-the-order-function-td4664384.html

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

There are 3 ways to allow cross domain origin (excluding jsonp):

1) Set the header in the page directly using a templating language like PHP. Keep in mind there can be no HTML before your header or it will fail.

 <?php header("Access-Control-Allow-Origin: http://example.com"); ?>

2) Modify the server configuration file (apache.conf) and add this line. Note that "*" represents allow all. Some systems might also need the credential set. In general allow all access is a security risk and should be avoided:

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Credentials true

3) To allow multiple domains on Apache web servers add the following to your config file

<IfModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www\.)?(example.org|example.com)$" AccessControlAllowOrigin=$0$1
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header set Access-Control-Allow-Credentials true
</IfModule>

4) For development use only hack your browser and allow unlimited CORS using the Chrome Allow-Control-Allow-Origin extension

5) Disable CORS in Chrome: Quit Chrome completely. Open a terminal and execute the following. Just be cautious you are disabling web security:

open -a Google\ Chrome --args --disable-web-security --user-data-dir

How to do a simple file search in cmd

dir /s *foo* searches in current folder and sub folders.

It finds directories as well as files.

where /s means(documentation):

/s Lists every occurrence of the specified file name within the specified directory and all subdirectories.

How do I turn a python datetime into a string, with readable format date?

This is for format the date?

def format_date(day, month, year):
        # {} betekent 'plaats hier stringvoorstelling van volgend argument'
        return "{}/{}/{}".format(day, month, year)

Roblox Admin Command Script

for i=1,#target do
    game.Players.target[i].Character:BreakJoints()
end

Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:

game.Players.target.1.Character:BreakJoints()

Which is completely incorrect.


c = game.Players:GetChildren()

Never use "Players:GetChildren()", it is not guaranteed to return only players.

Instead use:

c = Game.Players:GetPlayers()

if msg:lower()=="me" then
    table.insert(people, source)
    return people

Here you add the player's name in the list "people", where you in the other places adds the player object.


Fixed code:

local Admins = {"FakeNameHereSoNoStalkers"}

function Kill(Players)
    for i,Player in ipairs(Players) do
        if Player.Character then
            Player.Character:BreakJoints()
        end
    end
end

function IsAdmin(Player)
    for i,AdminName in ipairs(Admins) do
        if Player.Name:lower() == AdminName:lower() then return true end
    end
    return false
end

function GetPlayers(Player,Msg)
    local Targets = {}
    local Players = Game.Players:GetPlayers()

    if Msg:lower() == "me" then
        Targets = { Player }
    elseif Msg:lower() == "all" then
        Targets = Players
    elseif Msg:lower() == "others" then
        for i,Plr in ipairs(Players) do
            if Plr ~= Player then
                table.insert(Targets,Plr)
            end
        end
    else
        for i,Plr in ipairs(Players) do
            if Plr.Name:lower():sub(1,Msg:len()) == Msg then
                table.insert(Targets,Plr)
            end
        end
    end
    return Targets
end

Game.Players.PlayerAdded:connect(function(Player)
    if IsAdmin(Player) then
        Player.Chatted:connect(function(Msg)
            if Msg:lower():sub(1,6) == ":kill " then
                Kill(GetPlayers(Player,Msg:sub(7)))
            end
        end)
    end
end)

jQuery: Test if checkbox is NOT checked

Here I have a snippet for this question.

_x000D_
_x000D_
$(function(){_x000D_
   $("#buttoncheck").click(function(){_x000D_
        if($('[type="checkbox"]').is(":checked")){_x000D_
            $('.checkboxStatus').html("Congratulations! "+$('[type="checkbox"]:checked').length+" checkbox checked");_x000D_
        }else{_x000D_
            $('.checkboxStatus').html("Sorry! Checkbox is not checked");_x000D_
         }_x000D_
         return false;_x000D_
   })_x000D_
    _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form>_x000D_
  <p>_x000D_
    <label>_x000D_
      <input type="checkbox" name="CheckboxGroup1" value="checkbox" id="CheckboxGroup1_0">_x000D_
      Checkbox</label>_x000D_
    <br>_x000D_
    <label>_x000D_
      <input type="checkbox" name="CheckboxGroup1_" value="checkbox" id="CheckboxGroup1_1">_x000D_
      Checkbox</label>_x000D_
    <br>_x000D_
  </p>_x000D_
  <p>_x000D_
    <input type="reset" value="Reset">_x000D_
    <input type="submit" id="buttoncheck" value="Check">_x000D_
  </p>_x000D_
  <p class="checkboxStatus"></p>_x000D_
</form>
_x000D_
_x000D_
_x000D_

what exactly is device pixel ratio?

Device Pixel Ratio == CSS Pixel Ratio

In the world of web development, the device pixel ratio (also called CSS Pixel Ratio) is what determines how a device's screen resolution is interpreted by the CSS.

A browser's CSS calculates a device's logical (or interpreted) resolution by the formula:

formula

For example:

Apple iPhone 6s

  • Actual Resolution: 750 x 1334
  • CSS Pixel Ratio: 2
  • Logical Resolution:

formula

When viewing a web page, the CSS will think the device has a 375x667 resolution screen and Media Queries will respond as if the screen is 375x667. But the rendered elements on the screen will be twice as sharp as an actual 375x667 screen because there are twice as many physical pixels in the physical screen.

Some other examples:

Samsung Galaxy S4

  • Actual Resolution: 1080 x 1920
  • CSS Pixel Ratio: 3
  • Logical Resolution:

formula

iPhone 5s

  • Actual Resolution: 640 x 1136
  • CSS Pixel Ratio: 2
  • Logical Resolution:

formula

Why does the Device Pixel Ratio exist?

The reason that CSS pixel ratio was created is because as phones screens get higher resolutions, if every device still had a CSS pixel ratio of 1 then webpages would render too small to see.

A typical full screen desktop monitor is a roughly 24" at 1920x1080 resolution. Imagine if that monitor was shrunk down to about 5" but had the same resolution. Viewing things on the screen would be impossible because they would be so small. But manufactures are coming out with 1920x1080 resolution phone screens consistently now.

So the device pixel ratio was invented by phone makers so that they could continue to push the resolution, sharpness and quality of phone screens, without making elements on the screen too small to see or read.

Here is a tool that also tells you your current device's pixel density:

http://bjango.com/articles/min-device-pixel-ratio/

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

As part of trying to answer one of my own questions here, I came across this trick.

In the API Gateway mapping template, use the following to give you the complete query string as sent by the HTTP client:

{
    "querystring": "$input.params().querystring"
}

The advantage is that you don't have to limit yourself to a set of predefined mapped keys in your query string. Now you can accept any key-value pairs in the query string, if this is how you want to handle.

Note: According to this, only $input.params(x) is listed as a variable made available for the VTL template. It is possible that the internals might change and querystring may no longer be available.

URL.Action() including route values

You also can use in this form:

<a href="@Url.Action("Information", "Admin", null)"> Admin</a>

Select last N rows from MySQL

You can do it with a sub-query:

SELECT * FROM (
    SELECT * FROM table ORDER BY id DESC LIMIT 50
) sub
ORDER BY id ASC

This will select the last 50 rows from table, and then order them in ascending order.

Logging framework incompatibility

SLF4J 1.5.11 and 1.6.0 versions are not compatible (see compatibility report) because the argument list of org.slf4j.spi.LocationAwareLogger.log method has been changed (added Object[] p5):

SLF4J 1.5.11:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Throwable p5 )

SLF4J 1.6.0:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Object[] p5, Throwable p6 )

See compatibility reports for other SLF4J versions on this page.

You can generate such reports by the japi-compliance-checker tool.

enter image description here

Read pdf files with php

Check out FPDF (with FPDI):

http://www.fpdf.org/

http://www.setasign.de/products/pdf-php-solutions/fpdi/

These will let you open an pdf and add content to it in PHP. I'm guessing you can also use their functionality to search through the existing content for the values you need.

Another possible library is TCPDF: https://tcpdf.org/

Update to add a more modern library: PDF Parser

`getchar()` gives the same output as the input string

In the simple setup you are likely using, getchar works with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated by EOF; in fact, EOF is not really a character, but a magic value that indicates the end of the file. But EOF is not part of the string read. It's what getchar returns when there is nothing left to read.

Using NSLog for debugging

Why do you have the brackets around digit? It should be

NSLog("%@", digit);

You're also missing an = in the first line...

NSString *digit = [[sender titlelabel] text];

Kill python interpeter in linux from the terminal

pgrep -f youAppFile.py | xargs kill -9

pgrep returns the PID of the specific file will only kill the specific application.

Apache shutdown unexpectedly

This problem may occur because of skype installation in the system. Skype and apache service always conflict. Make sure your skype is not started before starting xampp.

Is there any way I can define a variable in LaTeX?

If you want to use \newcommand, you can also include \usepackage{xspace} and define command by \newcommand{\newCommandName}{text to insert\xspace}. This can allow you to just use \newCommandName rather than \newCommandName{}.

For more detail, http://www.math.tamu.edu/~harold.boas/courses/math696/why-macros.html

Where in an Eclipse workspace is the list of projects stored?

You can also have several workspaces - so you can connect to one and have set "A" of projects - and then connect to a different set when ever you like.

How to find if directory exists in Python

You're looking for os.path.isdir, or os.path.exists if you don't care whether it's a file or a directory:

>>> import os
>>> os.path.isdir('new_folder')
True
>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
False

Alternatively, you can use pathlib:

 >>> from pathlib import Path
 >>> Path('new_folder').is_dir()
 True
 >>> (Path.cwd() / 'new_folder' / 'file.txt').exists()
 False

Oracle error : ORA-00905: Missing keyword

Though this is not directly related to the OP's exact question but I just found out that using a Oracle reserved word in your query (in my case the alias IN) can cause the same error.

Example:

SELECT * FROM TBL_INDEPENTS IN
JOIN TBL_VOTERS VO on IN.VOTERID = VO.VOTERID

Or if its in the query itself as a field name

 SELECT ..., ...., IN, ..., .... FROM SOMETABLE

That would also throw that error. I hope this helps someone.

SeekBar and media player in android

Based on previous statements, for better performance, you can also add an if condition

if (player.isPlaying() {
    handler.postDelayed(..., 1000);
}

How do you keep parents of floated elements from collapsing?

The problem happens when a floated element is within a container box, that element does not automatically force the container’s height adjust to the floated element. When an element is floated, its parent no longer contains it because the float is removed from the flow. You can use 2 methods to fix it:

  • { clear: both; }
  • clearfix

Once you understand what is happening, use the method below to “clearfix” it.

.clearfix:after {
    content: ".";
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
}

.clearfix {
    display: inline-block;
}

html[xmlns] .clearfix {
    display: block;
}

* html .clearfix {
    height: 1%;
}

Demonstration :)

Tainted canvases may not be exported

If you're using ctx.drawImage() function, you can do the following:

var img = loadImage('../yourimage.png', callback);

function loadImage(src, callback) {
    var img = new Image();

    img.onload = callback;
    img.setAttribute('crossorigin', 'anonymous'); // works for me

    img.src = src;

    return img;
}

And in your callback you can now use ctx.drawImage and export it using toDataURL

Cycles in family tree software

I hate commenting on such a screwed up situation, but the easiest way to not rejigger all of your invariants is to create a phantom vertex in your graph that acts as a proxy back to the incestuous dad.

In OS X Lion, LANG is not set to UTF-8, how to fix it?

I recently had the same issue on OS X Sierra with bash shell, and thanks to answers above I only had to edit the file

~/.bash_profile 

and append those lines

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

Initializing IEnumerable<string> In C#

As string[] implements IEnumerable

IEnumerable<string> m_oEnum = new string[] {"1","2","3"}

When is the @JsonProperty property used and what is it used for?

well for what its worth now... JsonProperty is ALSO used to specify getter and setter methods for the variable apart from usual serialization and deserialization. For example suppose you have a payload like this:

{
  "check": true
}

and a Deserializer class:

public class Check {

  @JsonProperty("check")    // It is needed else Jackson will look got getCheck method and will fail
  private Boolean check;

  public Boolean isCheck() {
     return check;
  }
}

Then in this case JsonProperty annotation is neeeded. However if you also have a method in the class

public class Check {

  //@JsonProperty("check")    Not needed anymore
  private Boolean check;

  public Boolean getCheck() {
     return check;
  }
}

Have a look at this documentation too: http://fasterxml.github.io/jackson-annotations/javadoc/2.3.0/com/fasterxml/jackson/annotation/JsonProperty.html

How does bitshifting work in Java?

Firstly, you can not shift a byte in java, you can only shift an int or a long. So the byte will undergo promotion first, e.g.

00101011 -> 00000000000000000000000000101011

or

11010100 -> 11111111111111111111111111010100

Now, x >> N means (if you view it as a string of binary digits):

  • The rightmost N bits are discarded
  • The leftmost bit is replicated as many times as necessary to pad the result to the original size (32 or 64 bits), e.g.

00000000000000000000000000101011 >> 2 -> 00000000000000000000000000001010

11111111111111111111111111010100 >> 2 -> 11111111111111111111111111110101

How to programmatically open the Permission Screen for a specific app on Android Marshmallow?

Instead, you can open particular app's general settings with one line

 startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + BuildConfig.APPLICATION_ID)));

What is the closest thing Windows has to fork()?

I certainly don't know the details on this because I've never done it it, but the native NT API has a capability to fork a process (the POSIX subsystem on Windows needs this capability - I'm not sure if the POSIX subsystem is even supported anymore).

A search for ZwCreateProcess() should get you some more details - for example this bit of information from Maxim Shatskih:

The most important parameter here is SectionHandle. If this parameter is NULL, the kernel will fork the current process. Otherwise, this parameter must be a handle of the SEC_IMAGE section object created on the EXE file before calling ZwCreateProcess().

Though note that Corinna Vinschen indicates that Cygwin found using ZwCreateProcess() still unreliable:

Iker Arizmendi wrote:

> Because the Cygwin project relied solely on Win32 APIs its fork
> implementation is non-COW and inefficient in those cases where a fork
> is not followed by exec.  It's also rather complex. See here (section
> 5.6) for details:
>  
> http://www.redhat.com/support/wpapers/cygnus/cygnus_cygwin/architecture.html

This document is rather old, 10 years or so. While we're still using Win32 calls to emulate fork, the method has changed noticably. Especially, we don't create the child process in the suspended state anymore, unless specific datastructes need a special handling in the parent before they get copied to the child. In the current 1.5.25 release the only case for a suspended child are open sockets in the parent. The upcoming 1.7.0 release will not suspend at all.

One reason not to use ZwCreateProcess was that up to the 1.5.25 release we're still supporting Windows 9x users. However, two attempts to use ZwCreateProcess on NT-based systems failed for one reason or another.

It would be really nice if this stuff would be better or at all documented, especially a couple of datastructures and how to connect a process to a subsystem. While fork is not a Win32 concept, I don't see that it would be a bad thing to make fork easier to implement.

PHP is_numeric or preg_match 0-9 validation

is_numeric would accept "-0.5e+12" as a valid ID.

HTML5 LocalStorage: Checking if a key exists

This method worked for me:

if ("username" in localStorage) {
    alert('yes');
} else {
    alert('no');
}

How to adjust layout when soft keyboard appears

Many answers are right. In AndroidManifest I wrote:

<activity
    android:name=".SomeActivity"
    android:configChanges="orientation|keyboardHidden|screenSize" // Optional, doesn't affect.
    android:theme="@style/AppTheme.NoActionBar"
    android:windowSoftInputMode="adjustResize" />

In my case I added a theme in styles.xml, but you can use your own:

<style name="AppTheme.NoActionBar" parent="AppTheme">
    <!--  Hide ActionBar -->
    <item name="windowNoTitle">true</item>
    <item name="windowActionBar">false</item>
</style>

I noiced that if I use full-screen theme, resizing doesn't occur:

<style name="AppTheme.FullScreenTheme" parent="AppTheme">
    <!--  Hide ActionBar -->
    <item name="windowNoTitle">true</item>
    <item name="windowActionBar">false</item>
    <!--  Hide StatusBar -->
    <item name="android:windowFullscreen">true</item>
</style>

Also in my case adjustResize works, but adjustPan doesn't.

For full-screen layouts see a workaround in Android How to adjust layout in Full Screen Mode when softkeyboard is visible or in https://gist.github.com/grennis/2e3cd5f7a9238c59861015ce0a7c5584.

Also https://medium.com/@sandeeptengale/problem-solved-3-android-full-screen-view-translucent-scrollview-adjustresize-keyboard-b0547c7ced32 works, but it's StatusBar is transparent, so battery, clock, Wi-Fi icons are visible.

If you create an activity with File > New > Activity > Fullscreen Activity, where in code is used:

fullscreen_content.systemUiVisibility =
    View.SYSTEM_UI_FLAG_LOW_PROFILE or
    View.SYSTEM_UI_FLAG_FULLSCREEN or
    View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
    View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
    View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION

you also won't achieve a result. You can use android:fitsSystemWindows="true" in a root container, but StatusBar appears. So use workarounds from the first link.

javax.net.ssl.SSLException: Received fatal alert: protocol_version

I have got that error after update to JDK 1.8. But the JAVA_HOME variable was hard coded furthermore to JDK 1.7. Thew modification solved the problem:

set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_241

How to create named and latest tag in Docker?

You can have multiple tags when building the image:

$ docker build -t whenry/fedora-jboss:latest -t whenry/fedora-jboss:v2.1 .

Reference: https://docs.docker.com/engine/reference/commandline/build/#tag-image-t

Set background image on grid in WPF using C#

In order to avoid path problem, you can simply try this, just keep background image in images folder and add this code

<Grid>
  <Grid.Background>
    <ImageBrush Stretch="Fill" ImageSource="..\Images\background.jpg"
                AlignmentY="Top" AlignmentX="Center"/>
  </Grid.Background>
</Grid>

The view or its master was not found or no view engine supports the searched locations

Problem:

Your View cannot be found in default locations.

Explanation:

Views should be in the same folder named as the Controller or in the Shared folder.

Solution:

Either move your View to the MyAccount folder or create a HomeController.

Alternatives:

If you don't want to move your View or create a new Controller you can check at this link.

JQuery, select first row of table

late in the game , but this worked for me:

$("#container>table>tbody>tr:first").trigger('click');

Can't concatenate 2 arrays in PHP

+ is called the Union operator, which differs from a Concatenation operator (PHP doesn't have one for arrays). The description clearly says:

The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.

With the example:

$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b;

array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}

Since both your arrays have one entry with the key 0, the result is expected.

To concatenate, use array_merge.

How to find elements with 'value=x'?

$(selector).filter(function(){return this.value==yourval}).remove();

base64 encode in MySQL

I was looking for the same thing and I've just seen that MySQL 5.6 has a couple of new string functions supporting this functionality: TO_BASE64 and FROM_BASE64.

Get the item doubleclick event of listview

    private void positionsListView_DoubleClick(object sender, EventArgs e)
    {
        if (positionsListView.SelectedItems.Count == 1)
        {
            ListView.SelectedListViewItemCollection items = positionsListView.SelectedItems;

            ListViewItem lvItem = items[0];
            string what = lvItem.Text;

        }
    }

Sorting arraylist in alphabetical order (case insensitive)

Starting from Java 8 you can use Stream:

List<String> sorted = Arrays.asList(
                          names.stream().sorted(
                              (s1, s2) -> s1.compareToIgnoreCase(s2)
                          ).toArray(String[]::new)
                      );

It gets a stream from that ArrayList, then it sorts it (ignoring the case). After that, the stream is converted to an array which is converted to an ArrayList.

If you print the result using:

System.out.println(sorted);

you get the following output:

[ananya, Athira, bala, jeena, Karthika, Neethu, Nithin, seetha, sudhin, Swetha, Tony, Vinod]

Disable scrolling when touch moving certain element

try overflow hidden on the thing you don't want to scroll while touch event is happening. e.g set overflow hidden on Start and set it back to auto on end.

Did you try it ? I'd be interested to know if this would work.

document.addEventListener('ontouchstart', function(e) {
    document.body.style.overflow = "hidden";
}, false);

document.addEventListener('ontouchmove', function(e) {
    document.body.style.overflow = "auto";
}, false);

Create an array of strings

one of the simplest ways to create a string matrix is as follow :

x = [ {'first string'} {'Second parameter} {'Third text'} {'Fourth component'} ]

How can I set an SQL Server connection string?

We can simply connect to the database like this:

 uid=username;pwd=password;database=databasename;server=servername

For example:

string connectionString = @"uid=spacecraftU1;pwd=Appolo11;
                            database=spacecraft_db;
                            server=DESKTOP-99K0FRS\\PRANEETHDB";
SqlConnection con = new SqlConnection(connectionString);

Difference between long and int data types

The guarantees the standard gives you go like this:

1 == sizeof(char) <= sizeof(short) <= sizeof (int) <= sizeof(long) <= sizeof(long long)

So it's perfectly valid for sizeof (int) and sizeof (long) to be equal, and many platforms choose to go with this approach. You will find some platforms where int is 32 bits, long is 64 bits, and long long is 128 bits, but it seems very common for sizeof (long) to be 4.

(Note that long long is recognized in C from C99 onwards, but was normally implemented as an extension in C++ prior to C++11.)

How to determine the screen width in terms of dp or dip at runtime in Android?

You are missing default density value of 160.

    2 px = 3 dip if dpi == 80(ldpi), 320x240 screen
    1 px = 1 dip if dpi == 160(mdpi), 480x320 screen
    3 px = 2 dip if dpi == 240(hdpi), 840x480 screen

In other words, if you design you layout with width equal to 160dip in portrait mode, it will be half of the screen on all ldpi/mdpi/hdpi devices(except tablets, I think)

How to fix corrupted git repository?

Quick way if you have change on your current project and don't want to lose it , move your current project some where , clone the project from github to this folder and make some change an try to commit again. Or just delete the repo and clone it again , it worked form me .

PHP: How to remove specific element from an array?

Use this simple way hope it will helpful

foreach($array as $k => $value)
    {
      
        if($value == 'strawberry')
        {
          unset($array[$k]);
        }
    }

Best way of invoking getter by reflection

You can use Reflections framework for this

import static org.reflections.ReflectionUtils.*;
Set<Method> getters = ReflectionUtils.getAllMethods(someClass,
      withModifier(Modifier.PUBLIC), withPrefix("get"), withAnnotation(annotation));

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

How to center the content inside a linear layout?

If you are looking for an answer in java code,

LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setGravity(Gravity.CENTER);
// add children

How to parse a String containing XML in Java and retrieve the value of the root node?

One of the above answer states to convert XML String to bytes which is not needed. Instead you can can use InputSource and supply it with StringReader.

String xmlStr = "<message>HELLO!</message>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xmlStr)));
System.out.println(doc.getFirstChild().getNodeValue());

Check if string contains only whitespace

I'm assuming in your scenario, an empty string is a string that is truly empty or one that contains all white space.

if(str.strip()):
    print("string is not empty")
else:
    print("string is empty")

Note this does not check for None

Automatic confirmation of deletion in powershell

Remove-Item .\foldertodelete -Force -Recurse

nodeJs callbacks simple example

This blog-post has a good write-up:

https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced

_x000D_
_x000D_
function doHomework(subject, callback) {_x000D_
  alert(`Starting my ${subject} homework.`);_x000D_
  callback();_x000D_
}_x000D_
_x000D_
function alertFinished(){_x000D_
  alert('Finished my homework');_x000D_
}_x000D_
_x000D_
doHomework('math', alertFinished);
_x000D_
_x000D_
_x000D_

Google maps Places API V3 autocomplete - select first option on enter

How about this?

$("input").keypress(function(event) {
  var firstValue = null;
  if (event.keyCode == 13 || event.keyCode == 9) {
    $(event.target).blur();
    if ($(".pac-container .pac-item:first span:eq(3)").text() == "") {
      firstValue = $(".pac-container .pac-item:first .pac-item-query").text();
    } else {
      firstValue = $(".pac-container .pac-item:first .pac-item-query").text() + ", " + $(".pac-container .pac-item:first span:eq(3)").text();
    }
    event.target.value = firstValue;
  } else
    return true;
});

Command to get nth line of STDOUT

From sed1line:

# print line number 52
sed -n '52p'                 # method 1
sed '52!d'                   # method 2
sed '52q;d'                  # method 3, efficient on large files

From awk1line:

# print line number 52
awk 'NR==52'
awk 'NR==52 {print;exit}'          # more efficient on large files

Sorting multiple keys with Unix sort

The -k option is what you want.

-k 1.4,1.5n -k 1.14,1.15n

Would use character positions 4-5 in the first field (it's all one field for fixed width) and sort numerically as the first key.

The second key would be characters 14-15 in the first field also.

(edit)

Example (all I have is DOS/cygwin handy):

dir | \cygwin\bin\sort.exe -k 1.4,1.5n -k 1.40,1.60r

for the data:

12/10/2008  01:10 PM         1,564,990 outfile.txt

Sorts the directory listing by month number (pos 4-5) numerically, and then by filename (pos 40-60) in reverse. Since there are no tabs, it's all field 1 to sort.

Create Table from View

Select 
    MonthEndDate MED,  
    SUM(GrossBalance/1000000) GrossBalance,
    PortfolioRename PR 
into 
    testDynamic 
from 
    Risk_PortfolioOverview  
    Group By MonthEndDate, PortfolioRename

Java method: Finding object in array list given a known attribute value

I was interested to see that the original poster used a style that avoided early exits. Single Entry; Single Exit (SESE) is an interesting style that I've not really explored. It's late and I've got a bottle of cider, so I've written a solution (not tested) without an early exit.

I should have used an iterator. Unfortunately java.util.Iterator has a side-effect in the get method. (I don't like the Iterator design due to its exception ramifications.)

private Dog findDog(int id) {
    int i = 0;
    for (; i!=dogs.length() && dogs.get(i).getID()!=id; ++i) {
        ;
    }

    return i!=dogs.length() ? dogs.get(i) : null;
}

Note the duplication of the i!=dogs.length() expression (could have chosen dogs.get(i).getID()!=id).

What is the regex for "Any positive integer, excluding 0"

This should only allow decimals > 0

^([0-9]\.\d+)|([1-9]\d*\.?\d*)$

How to create a date and time picker in Android?

You can use one of DatePicker library wdullaer/MaterialDateTimePicker

  • First show DatePicker.

    private void showDatePicker() {
    Calendar now = Calendar.getInstance();
    DatePickerDialog dpd = DatePickerDialog.newInstance(
            HomeActivity.this,
            now.get(Calendar.YEAR),
            now.get(Calendar.MONTH),
            now.get(Calendar.DAY_OF_MONTH)
    );
    dpd.show(getFragmentManager(), "Choose Date:");
    }
    
  • Then onDateSet callback store date & show TimePicker

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
    Calendar cal = Calendar.getInstance();
    cal.set(year, monthOfYear, dayOfMonth);
    filter.setDate(cal.getTime());
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            showTimePicker();
        }
    },500);
    }
    
  • On onTimeSet callback store time

     @Override
     public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
    Calendar cal = Calendar.getInstance();
    if(filter.getDate()!=null)
        cal.setTime(filter.getDate());
    cal.set(Calendar.HOUR_OF_DAY,hourOfDay);
    cal.set(Calendar.MINUTE,minute);
    }
    

What steps are needed to stream RTSP from FFmpeg?

An alternative that I used instead of FFServer was Red5 Pro, on Ubuntu, I used this line: ffmpeg -f pulse -i default -f video4linux2 -thread_queue_size 64 -framerate 25 -video_size 640x480 -i /dev/video0 -pix_fmt yuv420p -bsf:v h264_mp4toannexb -profile:v baseline -level:v 3.2 -c:v libx264 -x264-params keyint=120:scenecut=0 -c:a aac -b:a 128k -ar 44100 -f rtsp -muxdelay 0.1 rtsp://localhost:8554/live/paul

Converting a character code to char (VB.NET)

The Chr function in VB.NET converts the integer back to the character:

Dim i As Integer = Asc("x") ' Convert to ASCII integer.
Dim x As Char = Chr(i)      ' Convert ASCII integer to char.

Getting unique values in Excel by using formulas only

For a solution that works for values in multiple rows and columns, I found the following formula very useful, from http://www.get-digital-help.com/2009/03/16/unique-values-from-multiple-columns-using-array-formulas/ Oscar at get-digital.help.com even goes through it step-by-step and with a visualized example.

1) Give the range of values the label tbl_text

2) Apply the following array formula with CTRL + SHIFT + ENTER, to cell B13 in this case. Change $B$12:B12 to refer to the cell above the cell you enter this formula into.

    =INDEX(tbl_text, MIN(IF(COUNTIF($B$12:B12, tbl_text)=0, ROW(tbl_text)-MIN(ROW(tbl_text))+1)), MATCH(0, COUNTIF($B$12:B12, INDEX(tbl_text, MIN(IF(COUNTIF($B$12:B12, tbl_text)=0, ROW(tbl_text)-MIN(ROW(tbl_text))+1)), , 1)), 0), 1)

3) Copy/drag down until you get N/A's.

How to do multiple arguments to map function where one remains the same in python?

To pass multiple arguments to a map function.

def q(x,y):
    return x*y

print map (q,range(0,10),range(10,20))

Here q is function with multiple argument that map() calls. Make sure, the length of both the ranges i.e.

len (range(a,a')) and len (range(b,b')) are equal.

How can I select all rows with sqlalchemy?

I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Sequence
from sqlalchemy import String, Integer, Float, Boolean, Column
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'MyTable'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    some_col = Column(String(500))

    def __init__(self, some_col):
        self.some_col = some_col

engine = create_engine('sqlite:///sqllight.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()

for class_instance in session.query(MyTable).all():
    print(vars(class_instance))

session.close()

Change Name of Import in Java, or import two classes with the same name

There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.

Import one class and use the fully qualified name for the other one, i.e.

import com.text.Formatter;

private Formatter textFormatter;
private com.json.Formatter jsonFormatter;

How to concatenate string and int in C?

Look at snprintf or, if GNU extensions are OK, asprintf (which will allocate memory for you).

GitLab remote: HTTP Basic: Access denied and fatal Authentication

it worked for me: I use Mac and I wrote the path on finder:

~/Library/Application Support/SourceTree

I deleted the auth file which should be like

[email protected]

then tried to push and pull the code from the source tree and it worked.

You can also read the following answers:

https://community.atlassian.com/t5/Sourcetree-questions/How-to-update-HTTP-S-credentials-in-sourcetree/qaq-p/297564

How to check if an excel cell is empty using Apache POI?

As of Apache POI 3.17 you will have to check if the cell is empty using enumerations:

import org.apache.poi.ss.usermodel.CellType;

if(cell == null || cell.getCellTypeEnum() == CellType.BLANK) { ... }

How to remove space from string?

A funny way to remove all spaces from a variable is to use printf:

$ myvar='a cool variable    with   lots of   spaces in it'
$ printf -v myvar '%s' $myvar
$ echo "$myvar"
acoolvariablewithlotsofspacesinit

It turns out it's slightly more efficient than myvar="${myvar// /}", but not safe regarding globs (*) that can appear in the string. So don't use it in production code.

If you really really want to use this method and are really worried about the globbing thing (and you really should), you can use set -f (which disables globbing altogether):

$ ls
file1  file2
$ myvar='  a cool variable with spaces  and  oh! no! there is  a  glob  *  in it'
$ echo "$myvar"
  a cool variable with spaces  and  oh! no! there is  a  glob  *  in it
$ printf '%s' $myvar ; echo
acoolvariablewithspacesandoh!no!thereisaglobfile1file2init
$ # See the trouble? Let's fix it with set -f:
$ set -f
$ printf '%s' $myvar ; echo
acoolvariablewithspacesandoh!no!thereisaglob*init
$ # Since we like globbing, we unset the f option:
$ set +f

I posted this answer just because it's funny, not to use it in practice.

What are the git concepts of HEAD, master, origin?

I highly recommend the book "Pro Git" by Scott Chacon. Take time and really read it, while exploring an actual git repo as you do.

HEAD: the current commit your repo is on. Most of the time HEAD points to the latest commit in your current branch, but that doesn't have to be the case. HEAD really just means "what is my repo currently pointing at".

In the event that the commit HEAD refers to is not the tip of any branch, this is called a "detached head".

master: the name of the default branch that git creates for you when first creating a repo. In most cases, "master" means "the main branch". Most shops have everyone pushing to master, and master is considered the definitive view of the repo. But it's also common for release branches to be made off of master for releasing. Your local repo has its own master branch, that almost always follows the master of a remote repo.

origin: the default name that git gives to your main remote repo. Your box has its own repo, and you most likely push out to some remote repo that you and all your coworkers push to. That remote repo is almost always called origin, but it doesn't have to be.

HEAD is an official notion in git. HEAD always has a well-defined meaning. master and origin are common names usually used in git, but they don't have to be.

How to remove old Docker containers

You can stop the docker container and once it is stopped you can remove the container.

Stop the container:

$ docker stop "containerID" - you can also mention the first two letters of the container ID, and it works.

Remove the container

$ docker rm "containerID" - again you can also mention the first two letters of the container

If these command do not let you stop/remove the containers, m,ake sure you have sudo access to docker host.

VBScript How can I Format Date?

For anyone who might still need this in the future. My answer is very similar to qaweb, just a lot less intimidating. There seems to be no cool automatic simple function to formate date in VBS. So you'll have to do it manually. I took the different components of the date and concatenated them together.

Dim timeStamp
timeStamp = Month(Date)&"-"&Day(Date)&"-"&Year(Date)
run = msgbox(timeStamp)

Which will result in 11-22-2019 (depending on the current date)

HTML entity for the middle dot

Try the HTML code: &#0149;

Which will appear as: •

What does the star operator mean, in a function call?

I find this particularly useful for when you want to 'store' a function call.

For example, suppose I have some unit tests for a function 'add':

def add(a, b): return a + b
tests = { (1,4):5, (0, 0):0, (-1, 3):3 }
for test, result in tests.items():
    print 'test: adding', test, '==', result, '---', add(*test) == result

There is no other way to call add, other than manually doing something like add(test[0], test[1]), which is ugly. Also, if there are a variable number of variables, the code could get pretty ugly with all the if-statements you would need.

Another place this is useful is for defining Factory objects (objects that create objects for you). Suppose you have some class Factory, that makes Car objects and returns them. You could make it so that myFactory.make_car('red', 'bmw', '335ix') creates Car('red', 'bmw', '335ix'), then returns it.

def make_car(*args):
    return Car(*args)

This is also useful when you want to call a superclass' constructor.

Change <br> height using CSS

The BR is anything but 'extra-special': it is still a valid XML tag that you can give attributes to. For example, you don't have to encase it with a span to change the line-height, rather you can apply the line height directly to the element.

You could do it with inline CSS:

_x000D_
_x000D_
This is a small line_x000D_
<br />_x000D_
break. Whereas, this is a BIG line_x000D_
<br />_x000D_
<br style="line-height:40vh"/>_x000D_
break!
_x000D_
_x000D_
_x000D_

Notice how two line breaks were used instead of one. This is because of how CSS inline elements work. Unfourtunately, the most awesome css feature possible (the lh unit) is still not there yet with any browser compatibility as of 2019. Thus, I have to use JavaScript for the demo below.

_x000D_
_x000D_
addEventListener("load", function(document, getComputedStyle){"use strict";_x000D_
  var allShowLineHeights = document.getElementsByClassName("show-lh");_x000D_
  for (var i=0; i < allShowLineHeights.length; i=i+1|0) {_x000D_
    allShowLineHeights[i].textContent = getComputedStyle(_x000D_
      allShowLineHeights[i]_x000D_
    ).lineHeight;_x000D_
  }_x000D_
}.bind(null, document, getComputedStyle), {once: 1, passive: 1});
_x000D_
.show-lh {padding: 0 .25em}_x000D_
.r {background: #f77}_x000D_
.g {background: #7f5}_x000D_
.b {background: #7cf}
_x000D_
This is a small line_x000D_
<span class="show-lh r"></span><br /><span class="show-lh r"></span>_x000D_
break. Whereas, this is a BIG line_x000D_
<span class="show-lh g"></span><br /><span class="show-lh g"></span>_x000D_
<span class="show-lh b"></span><br style="line-height:40vh"/><span class="show-lh b"></span>_x000D_
break!
_x000D_
_x000D_
_x000D_

You can even use any CSS selectors you want like ID's and classes.

_x000D_
_x000D_
#biglinebreakid {_x000D_
  line-height: 450%;_x000D_
  // 9x the normal height of a line break!_x000D_
}_x000D_
.biglinebreakclass {_x000D_
  line-height: 1em;_x000D_
  // you could even use calc!_x000D_
}
_x000D_
This is a small line_x000D_
<br />_x000D_
break. Whereas, this is a BIG line_x000D_
<br />_x000D_
<br id="biglinebreakid" />_x000D_
break! You can use any CSS selectors you want for things like this line_x000D_
<br />_x000D_
<br class="biglinebreakclass" />_x000D_
break!
_x000D_
_x000D_
_x000D_

You can find our more about line-height at the W3C docs.

Basically, BR tags are not some void in world of CSS styling: they still can be styled. However, I would recommend only using line-height to style BR tags. They were never intended to be anything more than a line-break, and as such they might not always work as expected when using them as something else. Observe how even after applying tons of visual effects, the line break is still invisible:

_x000D_
_x000D_
#paddedlinebreak {_x000D_
  display: block;_x000D_
  width: 6em;_x000D_
  height: 6em;_x000D_
  background: orange;_x000D_
  line-height: calc(6em + 100%);_x000D_
  outline: 1px solid red;_x000D_
  border: 1px solid green;_x000D_
}
_x000D_
<div style="outline: 1px solid yellow;margin:1em;display:inline-block;overflow:visible">_x000D_
This is a padded line_x000D_
<br id="paddedlinebreak" />_x000D_
break._x000D_
</div>
_x000D_
_x000D_
_x000D_

A work-around for things such as margins and paddings is to instead style a span with a br in it like so.

_x000D_
_x000D_
#paddedlinebreak {_x000D_
  background: orange;_x000D_
  line-height: calc(6em + 100%);_x000D_
  padding: 3em;_x000D_
}
_x000D_
<div style="outline: 1px solid yellow;margin:1em;display:inline-block;overflow:visible">_x000D_
This is a padded line_x000D_
<span id="paddedlinebreak"><br /></span>_x000D_
break._x000D_
</div>
_x000D_
_x000D_
_x000D_

Notice how the orange blob above is the span that contains the br.

How do I create an average from a Ruby array?

You can choose one of the below solutions as you wish.

Bruteforce

[0,4,8,2,5,0,2,6].sum.to_f / [0,4,8,2,5,0,2,6].size.to_f

=> 3.375

Method

def avg(array)
  array.sum.to_f / array.size.to_f
end  

avg([0,4,8,2,5,0,2,6])
=> 3.375

Monkey Patching

class Array
  def avg
    sum.to_f / size.to_f
  end
end

[0,4,8,2,5,0,2,6].avg
=> 3.375

But I don't recommend to monkey patch the Array class, this practice is dangerous and can potentially lead to undesirable effects on your system.

For our good, ruby language provides a nice feature to overcome this problem, the Refinements, which is a safe way for monkey patching on ruby.

To simplify, with the Refinements you can monkey patch the Array class and the changes will only be available inside the scope of the class that is using the refinement! :)

You can use the refinement inside the class you are working on and you are ready to go.

Refinements

module ArrayRefinements
  refine Array do
    def avg
      sum.to_f / size.to_f
    end
  end
end

class MyClass
  using ArrayRefinements

  def test(array)
    array.avg
  end
end

MyClass.new.test([0,4,8,2,5,0,2,6])
=> 3.375

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

%i or %d to print integer in C using printf()?

As others said, they produce identical output on printf, but behave differently on scanf. I would prefer %d over %i for this reason. A number that is printed with %d can be read in with %d and you will get the same number. That is not always true with %i, if you ever choose to use zero padding. Because it is common to copy printf format strings into scanf format strings, I would avoid %i, since it could give you a surprising bug introduction:

I write fprintf("%i ...", ...);

You copy and write fscanf(%i ...", ...);

I decide I want to align columns more nicely and make alphabetization behave the same as sorting: fprintf("%03i ...", ...); (or %04d)

Now when you read my numbers, anything between 10 and 99 is interpreted in octal. Oops.

If you want decimal formatting, just say so.

Completely Remove MySQL Ubuntu 14.04 LTS

Different solution for those still having issues. Hopefully I can help those trying to reinstall Mysql. Note, It's a seek and destroy mission. So be weary. Assuming your root:

apt-get purge mysql*
apt-get purge dbconfig-common #the screen used for mysql password
find / -name *mysql*          #delete any traces of mysql
#insert apt-get cleanups, autoremove,updates etc.

Originally, something leftover was interfering with my startup of mysqlserver-5.5. These commands ended up resolving the issue for myself.

MS Access VBA: Sending an email through Outlook

Add a reference to the Outlook object model in the Visual Basic editor. Then you can use the code below to send an email using outlook.

Sub sendOutlookEmail()
Dim oApp As Outlook.Application
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application")

Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "Body of the email"
oMail.Subject = "Test Subject"
oMail.To = "[email protected]"
oMail.Send
Set oMail = Nothing
Set oApp = Nothing


End Sub

Why does the C++ STL not provide any "tree" containers?

All STL container are externally represented as "sequences" with one iteration mechanism. Trees don't follow this idiom.