Programs & Examples On #Http proxy

An HTTP Proxy is a server that receives requests from your web browser and then makes the request to the Internet on your behalf. It then returns the results to your browser.

How to use vagrant in a proxy environment?

The question does not mention the VM Provider but in my case, I use Virtual Box under the same environment. There is an option in the Virtual Box GUI that I needed to enable in order to make it work. Is located in the Virtual Box app preferences: File >> Preferences... >> Proxy. Once I configured this, I was able to work without problems. Hope this tip can also help you guys.

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

How do you run `apt-get` in a dockerfile behind a proxy?

before any apt-get command in your Dockerfile you should put this line

COPY apt.conf /etc/apt/apt.conf

Dont'f forget to create apt.conf in the same folder that you have the Dockerfile, the content of the apt.conf file should be like this:

Acquire::socks::proxy "socks://YOUR-PROXY-IP:PORT/";
Acquire::http::proxy "http://YOUR-PROXY-IP:PORT/";
Acquire::https::proxy "http://YOUR-PROXY-IP:PORT/";

if you use username and password to connect to your proxy then the apt.conf should be like as below:

Acquire::socks::proxy "socks://USERNAME:PASSWORD@YOUR-PROXY-IP:PORT/";
Acquire::http::proxy "http://USERNAME:PASSWORD@YOUR-PROXY-IP:PORT/";
Acquire::https::proxy "http://USERNAME:PASSWORD@YOUR-PROXY-IP:PORT/";

for example :

Acquire::https::proxy "http://foo:[email protected]:8080/";

Where the foo is the username and bar is the password.

C# - Create SQL Server table programmatically

You haven't mentioned the Initial catalog name in the connection string. Give your database name as Initial Catalog name.

<add name ="AutoRepairSqlProvider" connectionString=
     "Data Source=.\SQLEXPRESS; Initial Catalog=MyDatabase; AttachDbFilename=|DataDirectory|\AutoRepairDatabase.mdf;
     Integrated Security=True;User Instance=True"/>

Global variables in Javascript across multiple files

Hi to pass values from one js file to another js file we can use Local storage concept

<body>
<script src="two.js"></script>
<script src="three.js"></script>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>

Two.js file

function myFunction() {
var test =localStorage.name;

 alert(test);
}

Three.js File

localStorage.name = 1;

Unresolved external symbol on static class members

If you are using C++ 17 you can just use the inline specifier (see https://stackoverflow.com/a/11711082/55721)


If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y

unsigned char test::X;
unsigned char test::Y;

somewhere. You might want to also initialize a static member

unsigned char test::X = 4;

and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)

The remote certificate is invalid according to the validation procedure

You must check the certificate hash code.

ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain,
    errors) =>
        {
            var hashString = certificate.GetCertHashString();
            if (hashString != null)
            {
                var certHashString = hashString.ToLower();
                return certHashString == "dec2b525ddeemma8ccfaa8df174455d6e38248c5";
            }
            return false;
        };

How do I get user IP address in django?

The reason the functionality was removed from Django originally was that the header cannot ultimately be trusted. The reason is that it is easy to spoof. For example the recommended way to configure an nginx reverse proxy is to:

add_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header X-Real-Ip       $remote_addr;

When you do:

curl -H 'X-Forwarded-For: 8.8.8.8, 192.168.1.2' http://192.168.1.3/

Your nginx in myhost.com will send onwards:

X-Forwarded-For: 8.8.8.8, 192.168.1.2, 192.168.1.3

The X-Real-IP will be the IP of the first previous proxy if you follow the instructions blindly.

In case trusting who your users are is an issue, you could try something like django-xff: https://pypi.python.org/pypi/django-xff/

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

How to handle static content in Spring MVC?

Place static contents like css ,js in following path

resources 
        ->static
               ->css
               ->js
(or) 
resources 
        ->public
               ->css
               ->js

@Autowired and static method

You have to workaround this via static application context accessor approach:

@Component
public class StaticContextAccessor {

    private static StaticContextAccessor instance;

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void registerInstance() {
        instance = this;
    }

    public static <T> T getBean(Class<T> clazz) {
        return instance.applicationContext.getBean(clazz);
    }

}

Then you can access bean instances in a static manner.

public class Boo {

    public static void randomMethod() {
         StaticContextAccessor.getBean(Foo.class).doStuff();
    }

}

Using css transform property in jQuery

Setting a -vendor prefix that isn't supported in older browsers can cause them to throw an exception with .css. Instead detect the supported prefix first:

// Start with a fall back
var newCss = { 'zoom' : ui.value };

// Replace with transform, if supported
if('WebkitTransform' in document.body.style) 
{
    newCss = { '-webkit-transform': 'scale(' + ui.value + ')'};
}
// repeat for supported browsers
else if('transform' in document.body.style) 
{
    newCss = { 'transform': 'scale(' + ui.value + ')'};
}

// Set the CSS
$('.user-text').css(newCss)

That works in old browsers. I've done scale here but you could replace it with whatever other transform you wanted.

How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

What about using Excel Data Reader (previously hosted here) an open source project on codeplex? Its works really well for me to export data from excel sheets.

The sample code given on the link specified:

FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);

//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//...
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//...
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//...
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();

//5. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}

//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();

UPDATE

After some search around, I came across this article: Faster MS Excel Reading using Office Interop Assemblies. The article only uses Office Interop Assemblies to read data from a given Excel Sheet. The source code is of the project is there too. I guess this article can be a starting point on what you trying to achieve. See if that helps

UPDATE 2

The code below takes an excel workbook and reads all values found, for each excel worksheet inside the excel workbook.

private static void TestExcel()
    {
        ApplicationClass app = new ApplicationClass();
        Workbook book = null;
        Range range = null;

        try
        {
            app.Visible = false;
            app.ScreenUpdating = false;
            app.DisplayAlerts = false;

            string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);

            book = app.Workbooks.Open(@"C:\data.xls", Missing.Value, Missing.Value, Missing.Value
                                              , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                                             , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                                            , Missing.Value, Missing.Value, Missing.Value);
            foreach (Worksheet sheet in book.Worksheets)
            {

                Console.WriteLine(@"Values for Sheet "+sheet.Index);

                // get a range to work with
                range = sheet.get_Range("A1", Missing.Value);
                // get the end of values to the right (will stop at the first empty cell)
                range = range.get_End(XlDirection.xlToRight);
                // get the end of values toward the bottom, looking in the last column (will stop at first empty cell)
                range = range.get_End(XlDirection.xlDown);

                // get the address of the bottom, right cell
                string downAddress = range.get_Address(
                    false, false, XlReferenceStyle.xlA1,
                    Type.Missing, Type.Missing);

                // Get the range, then values from a1
                range = sheet.get_Range("A1", downAddress);
                object[,] values = (object[,]) range.Value2;

                // View the values
                Console.Write("\t");
                Console.WriteLine();
                for (int i = 1; i <= values.GetLength(0); i++)
                {
                    for (int j = 1; j <= values.GetLength(1); j++)
                    {
                        Console.Write("{0}\t", values[i, j]);
                    }
                    Console.WriteLine();
                }
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        finally
        {
            range = null;
            if (book != null)
                book.Close(false, Missing.Value, Missing.Value);
            book = null;
            if (app != null)
                app.Quit();
            app = null;
        }
    }

In the above code, values[i, j] is the value that you need to be added to the dataset. i denotes the row, whereas, j denotes the column.

jQuery text() and newlines

I would suggest to work with the someElem element directly, as replacements with .html() would replace other HTML tags within the string as well.

Here is my function:

function nl2br(el) {
  var lines = $(el).text().split(/\n/);
  $(el).empty();
  for (var i = 0 ; i < lines.length ; i++) {
    if (i > 0) $(el).append('<br>');
    $(el).append(document.createTextNode(lines[i]));
  }
  return el;
}

Call it by:

someElem = nl2br(someElem);

How to get JSON from webpage into Python script

you need import requests and use from json() method :

source = requests.get("url").json()
print(source)

Of course, this method also works:

import json,urllib.request
data = urllib.request.urlopen("url").read()
output = json.loads(data)
print (output)

json.loads will decode it into a Python object using this table, for example a JSON object will become a Python dict.

How do I check the difference, in seconds, between two dates?

We have function total_seconds() with Python 2.7 Please see below code for python 2.6

import datetime
import time  

def diffdates(d1, d2):
    #Date format: %Y-%m-%d %H:%M:%S
    return (time.mktime(time.strptime(d2,"%Y-%m-%d %H:%M:%S")) -
               time.mktime(time.strptime(d1, "%Y-%m-%d %H:%M:%S")))

d1 = datetime.now()
d2 = datetime.now() + timedelta(days=1)
diff = diffdates(d1, d2)

SQL DELETE with INNER JOIN

If the database is InnoDB then it might be a better idea to use foreign keys and cascade on delete, this would do what you want and also result in no redundant data being stored.

For this example however I don't think you need the first s:

DELETE s 
FROM spawnlist AS s 
INNER JOIN npc AS n ON s.npc_templateid = n.idTemplate 
WHERE n.type = "monster";

It might be a better idea to select the rows before deleting so you are sure your deleting what you wish to:

SELECT * FROM spawnlist
INNER JOIN npc ON spawnlist.npc_templateid = npc.idTemplate
WHERE npc.type = "monster";

You can also check the MySQL delete syntax here: http://dev.mysql.com/doc/refman/5.0/en/delete.html

Extracting hours from a DateTime (SQL Server 2005)

select case when [am or _pm] ='PM' and datepart(HOUR,time_received)<>12 
           then dateadd(hour,12,time_received) 
           else time_received 
       END 
from table

works

How to change the remote repository for a git submodule?

With Git 2.25 (Q1 2020), you can modify it.
See "Git submodule url changed" and the new command

git submodule set-url [--] <path> <newurl>

Original answer (May 2009, ten years ago)

Actually, a patch has been submitted in April 2009 to clarify gitmodule role.

So now the gitmodule documentation does not yet include:

The .gitmodules file, located in the top-level directory of a git working tree, is a text file with a syntax matching the requirements -of linkgit:git-config1.
[NEW]:
As this file is managed by Git, it tracks the +records of a project's submodules.
Information stored in this file is used as a hint to prime the authoritative version of the record stored in the project configuration file.
User specific record changes (e.g. to account for differences in submodule URLs due to networking situations) should be made to the configuration file, while record changes to be propagated (e.g. +due to a relocation of the submodule source) should be made to this file.

That pretty much confirm Jim's answer.


If you follow this git submodule tutorial, you see you need a "git submodule init" to add the submodule repository URLs to .git/config.

"git submodule sync" has been added in August 2008 precisely to make that task easier when URL changes (especially if the number of submodules is important).
The associate script with that command is straightforward enough:

module_list "$@" |
while read mode sha1 stage path
do
    name=$(module_name "$path")
    url=$(git config -f .gitmodules --get submodule."$name".url)
    if test -e "$path"/.git
    then
    (
        unset GIT_DIR
        cd "$path"
        remote=$(get_default_remote)
        say "Synchronizing submodule url for '$name'"
        git config remote."$remote".url "$url"
    )
    fi
done

The goal remains: git config remote."$remote".url "$url"

How many bits or bytes are there in a character?

There are 8 bits in a byte (normally speaking in Windows).

However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.

In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.

EDITED

Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.

How to change the value of ${user} variable used in Eclipse templates

Open Eclipse, navigate to Window -> Preferences -> Java -> Code Style -> Code Templates -> Comments -> Types and then press the 'Edit' button. There you can change your name in the generated comment from @Author ${user} to @Author Rajish.

How to embed an autoplaying YouTube video in an iframe?

Multiple queries tip for those who don't know (past me and future me)

If you're making a single query with the url just ?autoplay=1 works as shown by mjhm's answer

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1"></iframe>

If you're making multiple queries remember the first one begins with a ? while the rest begin with a &

Say you want to turn off related videos but enable autoplay...

This works

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?rel=0&autoplay=1"></iframe>

and this works

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1&rel=0"></iframe>

But these won't work..

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?rel=0?autoplay=1"></iframe>

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0&autoplay=1&rel=0"></iframe>

example comparisons

https://jsfiddle.net/Hastig/p4dpo5y4/

more info

Read NextLocal's reply below for more info about using multiple query strings

Python socket connection timeout

You just need to use the socket settimeout() method before attempting the connect(), please note that after connecting you must settimeout(None) to set the socket into blocking mode, such is required for the makefile . Here is the code I am using:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(address)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)

failed to find target with hash string android-23

Download the specific Android release from the link specified in the build console.

Get table name by constraint name

ALL_CONSTRAINTS describes constraint definitions on tables accessible to the current user.

DBA_CONSTRAINTS describes all constraint definitions in the database.

USER_CONSTRAINTS describes constraint definitions on tables in the current user's schema

Select CONSTRAINT_NAME,CONSTRAINT_TYPE ,TABLE_NAME ,STATUS from 
USER_CONSTRAINTS;

Counting the number of occurences of characters in a string

I don't want to give out the full code. So I want to give you the challenge and have fun with it. I encourage you to make the code simpler and with only 1 loop.

Basically, my idea is to pair up the characters comparison, side by side. For example, compare char 1 with char 2, char 2 with char 3, and so on. When char N not the same with char (N+1) then reset the character count. You can do this in one loop only! While processing this, form a new string. Don't use the same string as your input. That's confusing.

Remember, making things simple counts. Life for developers is hard enough looking at complex code.

Have fun!

Tommy "I should be a Teacher" Kwee

Random "Element is no longer attached to the DOM" StaleElementReferenceException

To add to @jarib's answer, I have made several extension methods which help eliminate the race condition.

Here is my setup:

I have a class Called "Driver.cs". It contains a static class full of extension methods for the driver and other useful static functions.

For elements I commonly need to retrieve, I create an extension method like the following:

public static IWebElement SpecificElementToGet(this IWebDriver driver) {
    return driver.FindElement(By.SomeSelector("SelectorText"));
}

This allows you to retrieve that element from any test class with the code:

driver.SpecificElementToGet();

Now, if this results in a StaleElementReferenceException, I have the following static method in my driver class:

public static void WaitForDisplayed(Func<IWebElement> getWebElement, int timeOut)
{
    for (int second = 0; ; second++)
    {
        if (second >= timeOut) Assert.Fail("timeout");
        try
        {
            if (getWebElement().Displayed) break;
        }
        catch (Exception)
        { }
        Thread.Sleep(1000);
    }
}

This function's first parameter is any function which returns an IWebElement object. The second parameter is a timeout in seconds (the code for the timeout was copied from the Selenium IDE for FireFox). The code can be used to avoid the stale element exception the following way:

MyTestDriver.WaitForDisplayed(driver.SpecificElementToGet,5);

The above code will call driver.SpecificElementToGet().Displayed until driver.SpecificElementToGet() throws no exceptions and .Displayed evaluates to true and 5 seconds have not passed. After 5 seconds, the test will fail.

On the flip side, to wait for an element to not be present, you can use the following function the same way:

public static void WaitForNotPresent(Func<IWebElement> getWebElement, int timeOut) {
    for (int second = 0;; second++) {
        if (second >= timeOut) Assert.Fail("timeout");
            try
            {
                if (!getWebElement().Displayed) break;
            }
            catch (ElementNotVisibleException) { break; }
            catch (NoSuchElementException) { break; }
            catch (StaleElementReferenceException) { break; }
            catch (Exception)
            { }
            Thread.Sleep(1000);
        }
}

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

ORA-01031: insufficient privileges happens when the object exists in the schema but do not have any access to that object.

ORA-00942: table or view does not exist happens when the object does not exist in the current schema. If the object exists in another schema, you need to access it using .. Still you can get insufficient privileges error if the owner has not given access to the calling schema.

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

You can apply the when method to your array:

var arr = [ /* Deferred objects */ ];

$.when.apply($, arr);

How do you work with an array of jQuery Deferreds?

Download data url file

Your problem essentially boils down to "not all browsers will support this".

You could try a workaround and serve the unzipped files from a Flash object, but then you'd lose the JS-only purity (anyway, I'm not sure whether you currently can "drag files into browser" without some sort of Flash workaround - is that a HTML5 feature maybe?)

How to add form validation pattern in Angular 2?

Since version 2.0.0-beta.8 (2016-03-02), Angular now includes a Validators.pattern regex validator.

See the CHANGELOG

Git: copy all files in a directory from another branch

If there are no spaces in paths, and you are interested, like I was, in files of specific extension only, you can use

git checkout otherBranch -- $(git ls-tree --name-only -r otherBranch | egrep '*.java')

Styling HTML5 input type number

There are only 4 specific atrributes:

  1. value - Value is the default value of the input box when a page is first loaded. This is a common attribute for element regardless which type you are using.
  2. min - Obviously, the minimum value you of the number. I should have specified minimum value to 0 for my demo up there as a negative number doesn't make sense for number of movie watched in a week.
  3. max - Apprently, this represents the biggest number of the number input.
  4. step - Step scale factor, default value is 1 if this attribute is not specified.

So you cannot control length of what user type by keyword. But the implementation of browsers may change.

How do I count the number of occurrences of a char in a String?

I had an idea similar to Mladen, but the opposite...

String s = "a.b.c.d";
int charCount = s.replaceAll("[^.]", "").length();
println(charCount);

"cannot resolve symbol R" in Android Studio

In the project gradle(i.e)build.gradle just update the com.android.tools.build:gradle as

dependencies {

classpath 'com.android.tools.build:gradle:3.2.1'

}

Elevating process privilege programmatically?

You should use Impersonation to elevate the state.

WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();

Don't forget to undo the impersonated context when you are done.

What are the differences between json and simplejson Python modules?

simplejson module is simply 1,5 times faster than json (On my computer, with simplejson 2.1.1 and Python 2.7 x86).

If you want, you can try the benchmark: http://abral.altervista.org/jsonpickle-bench.zip On my PC simplejson is faster than cPickle. I would like to know also your benchmarks!

Probably, as said Coady, the difference between simplejson and json is that simplejson includes _speedups.c. So, why don't python developers use simplejson?

How to bind WPF button to a command in ViewModelBase?

 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

the code behind for the window:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

The ViewModel:

public class ViewModelBase
{
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
        }
    }
     public bool CanExecute
     {
        get
        {
            // check if executing is allowed, i.e., validate, check if a process is running, etc. 
            return true/false;
        }
     }

    public void MyAction()
    {

    }
}

Command Handler:

 public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

    public void Execute(object parameter)
    {
        _action();
    }
}

I hope this will give you the idea.

Match at every second occurrence

If you're using C#, you can either get all the matches at once (i.e. use Regex.Matches(), which returns a MatchCollection, and check the index of the item: index % 2 != 0).

If you want to find the occurrence to replace it, use one of the overloads of Regex.Replace() that uses a MatchEvaluator (e.g. Regex.Replace(String, String, MatchEvaluator). Here's the code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "abcdabcd";

            // Replace *second* a with m

            string replacedString = Regex.Replace(
                input,
                "a",
                new SecondOccuranceFinder("m").MatchEvaluator);

            Console.WriteLine(replacedString);
            Console.Read();

        }

        class SecondOccuranceFinder
        {
            public SecondOccuranceFinder(string replaceWith)
            {
                _replaceWith = replaceWith;
                _matchEvaluator = new MatchEvaluator(IsSecondOccurance);
            }

            private string _replaceWith;

            private MatchEvaluator _matchEvaluator;
            public MatchEvaluator MatchEvaluator
            {
                get
                {
                    return _matchEvaluator;
                }
            }

            private int _matchIndex;
            public string IsSecondOccurance(Match m)
            {
                _matchIndex++;
                if (_matchIndex % 2 == 0)
                    return _replaceWith;
                else
                    return m.Value;
            }
        }
    }
}

Specify sudo password for Ansible

Very simple, and only add in the variable file:

Example:

$ vim group_vars/all

And add these:

Ansible_connection: ssh
Ansible_ssh_user: rafael
Ansible_ssh_pass: password123
Ansible_become_pass: password123

Python timedelta in years

I liked John Mee's solution for its simplicity, and I am not that concerned about how, on Feb 28 or March 1 when it is not a leap year, to determine age of people born on Feb 29. But here is a tweak of his code which I think addresses the complaints:

def age(dob):
    import datetime
    today = datetime.date.today()
    age = today.year - dob.year
    if ( today.month == dob.month == 2 and
         today.day == 28 and dob.day == 29 ):
         pass
    elif today.month < dob.month or \
      (today.month == dob.month and today.day < dob.day):
        age -= 1
    return age

Convert Variable Name to String?

Technically the information is available to you, but as others have asked, how would you make use of it in a sensible way?

>>> x = 52
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 
'x': 52, '__doc__': None, '__package__': None}

This shows that the variable name is present as a string in the globals() dictionary.

>>> globals().keys()[2]
'x'

In this case it happens to be the third key, but there's no reliable way to know where a given variable name will end up

>>> for k in globals().keys():
...   if not k.startswith("_"):
...     print k
...
x
>>>

You could filter out system variables like this, but you're still going to get all of your own items. Just running that code above created another variable "k" that changed the position of "x" in the dict.

But maybe this is a useful start for you. If you tell us what you want this capability for, more helpful information could possibly be given.

How to format a URL to get a file from Amazon S3?

Its actually formulated more like:

https://<bucket-name>.s3.amazonaws.com/<key>

See here

How to access full source of old commit in BitBucket?

Step 1

Step 1


Step 2

Step 2


Step 3

Step 3


Step 4

Step 4


Final Step

Final Step

How to check whether a string contains a substring in JavaScript?

ECMAScript 6 introduced String.prototype.includes:

_x000D_
_x000D_
const string = "foo";_x000D_
const substring = "oo";_x000D_
_x000D_
console.log(string.includes(substring));
_x000D_
_x000D_
_x000D_

includes doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:

_x000D_
_x000D_
var string = "foo";_x000D_
var substring = "oo";_x000D_
_x000D_
console.log(string.indexOf(substring) !== -1);
_x000D_
_x000D_
_x000D_

Parallel.ForEach vs Task.Factory.StartNew

In my view the most realistic scenario is when tasks have a heavy operation to complete. Shivprasad's approach focuses more on object creation/memory allocation than on computing itself. I made a research calling the following method:

public static double SumRootN(int root)
{
    double result = 0;
    for (int i = 1; i < 10000000; i++)
        {
            result += Math.Exp(Math.Log(i) / root);
        }
        return result; 
}

Execution of this method takes about 0.5sec.

I called it 200 times using Parallel:

Parallel.For(0, 200, (int i) =>
{
    SumRootN(10);
});

Then I called it 200 times using the old-fashioned way:

List<Task> tasks = new List<Task>() ;
for (int i = 0; i < loopCounter; i++)
{
    Task t = new Task(() => SumRootN(10));
    t.Start();
    tasks.Add(t);
}

Task.WaitAll(tasks.ToArray()); 

First case completed in 26656ms, the second in 24478ms. I repeated it many times. Everytime the second approach is marginaly faster.

What is the symbol for whitespace in C?

#include <stdio.h>
main()
{
int c,sp,tb,nl;
sp = 0;
tb = 0;
nl = 0;
while((c = getchar()) != EOF)
{
   switch( c )
{
   case ' ':
        ++sp;
     printf("space:%d\n", sp);
     break;
   case  '\t':
        ++tb;
     printf("tab:%d\n", tb);
     break;
   case '\n':
        ++nl;
     printf("new line:%d\n", nl);
     break;
  }
 }
}

Hexadecimal string to byte array in C

Here is a solution to deal with files, which may be used more frequently...

int convert(char *infile, char *outfile) {

char *source = NULL;
FILE *fp = fopen(infile, "r");
long bufsize;
if (fp != NULL) {
    /* Go to the end of the file. */
    if (fseek(fp, 0L, SEEK_END) == 0) {
        /* Get the size of the file. */
        bufsize = ftell(fp);
        if (bufsize == -1) { /* Error */ }

        /* Allocate our buffer to that size. */
        source = malloc(sizeof(char) * (bufsize + 1));

        /* Go back to the start of the file. */
        if (fseek(fp, 0L, SEEK_SET) != 0) { /* Error */ }

        /* Read the entire file into memory. */
        size_t newLen = fread(source, sizeof(char), bufsize, fp);
        if ( ferror( fp ) != 0 ) {
            fputs("Error reading file", stderr);
        } else {
            source[newLen++] = '\0'; /* Just to be safe. */
        }
    }
    fclose(fp);
}
     
int sourceLen = bufsize - 1;
int destLen = sourceLen/2;
unsigned char* dest = malloc(destLen);
short i;  
unsigned char highByte, lowByte;  
      
for (i = 0; i < sourceLen; i += 2)  
{  
        highByte = toupper(source[i]);  
        lowByte  = toupper(source[i + 1]);  
  
        if (highByte > 0x39)  
            highByte -= 0x37;  
        else  
            highByte -= 0x30;  
  
        if (lowByte > 0x39)  
            lowByte -= 0x37;  
        else  
            lowByte -= 0x30;  
  
        dest[i / 2] = (highByte << 4) | lowByte;  
}  
        

FILE *fop = fopen(outfile, "w");
if (fop == NULL) return 1;
fwrite(dest, 1, destLen, fop);
fclose(fop);
free(source);
free(dest);
return 0;
}  

How to change xampp localhost to another folder ( outside xampp folder)?

@Hooman: actually with the latest versions of Xampp you don't need to know where the configuration or log files are; in the Control panel you have log and config buttons for each tool (php, mysql, tomcat...) and clicking them offers to open all the relevant file (you can even change the default editing application with the general Config button at the top right). Well done for whoever designed it!

Move an item inside a list?

If you don't know the position of the item, you may need to find the index first:

old_index = list1.index(item)

then move it:

list1.insert(new_index, list1.pop(old_index))

or IMHO a cleaner way:

try:
  list1.remove(item)
  list1.insert(new_index, item)
except ValueError:
  pass

How do I get a reference to the app delegate in Swift?

Swift 4.2

In Swift, easy to access in your VC's

extension UIViewController {
    var appDelegate: AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate
   }
}

Jquery - How to make $.post() use contentType=application/json?

You can't send application/json directly -- it has to be a parameter of a GET/POST request.

So something like

$.post(url, {json: "...json..."}, function());

if else condition in blade file (laravel 5.3)

I think you are putting one too many curly brackets. Try this

 @if($user->status=='waiting')
            <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{!! $user->travel_id !!}" data-toggle="modal" data-target="#myModal">Approve/Reject</a> </td>
            @else
            <td>{!! $user->status !!}</td>
        @endif

"Strict Standards: Only variables should be passed by reference" error

I had a similar problem.

I think the problem is that when you try to enclose two or more functions that deals with an array type of variable, php will return an error.

Let's say for example this one.

$data = array('key1' => 'Robert', 'key2' => 'Pedro', 'key3' => 'Jose');

// This function returns the last key of an array (in this case it's $data)
$lastKey = array_pop(array_keys($data));

// Output is "key3" which is the last array.
// But php will return “Strict Standards: Only variables should 
// be passed by reference” error.
// So, In order to solve this one... is that you try to cut 
// down the process one by one like this.

$data1  = array_keys($data);
$lastkey = array_pop($data1);

echo $lastkey;

There you go!

How can you check for a #hash in a URL using JavaScript?

function getHash() {
  if (window.location.hash) {
    var hash = window.location.hash.substring(1);

    if (hash.length === 0) { 
      return false;
    } else { 
      return hash; 
    }
  } else { 
    return false; 
  }
}

How to automatically start a service when running a docker container?

This not works CMD service mysql start && /bin/bash

This not works CMD service mysql start ; /bin/bash ;

-- i guess interactive mode would not support foreground.

This works !! CMD service nginx start ; while true ; do sleep 100; done;

This works !! CMD service nginx start && tail -F /var/log/nginx/access.log

beware you should using docker run -p 80:80 nginx_bash without command parameter.

Multiline TextView in Android?

Why don't you declare a string instead of writing a long lines into the layout file. For this you have to declare a line of code into layout file 'android:text="@string/text"' and go to the \\app\src\main\res\values\strings.xml and add a line of code ' Your multiline text here' Also use '\n' to break the line from any point else the line will automatically be adjusted.

Reversing a string in C

Rather than breaking half-way through, you should simply shorten your loop.

size_t length = strlen(str);
size_t i;

for (i = 0; i < (length / 2); i++)
{
    char temp = str[length - i - 1];
    str[length - i - 1] = str[i];
    str[i] = temp;
}

Tesseract running error

The simpliest way is to install the needed package:

sudo apt-get install tesseract-ocr-eng  #for english
sudo apt-get install tesseract-ocr-tam  #for tamil
sudo apt-get install tesseract-ocr-deu  #for deutsch (German)

As you can notice, it opens the road to others languages (i.e. tesseract-ocr-fra).

How to encode a string in JavaScript for displaying in HTML?

If you want to use a library rather than doing it yourself:

The most commonly used way is using jQuery for this purpose:

var safestring = $('<div>').text(unsafestring).html();

If you want to to encode all the HTML entities you will have to use a library or write it yourself.

You can use a more compact library than jQuery, like HTML Encoder and Decode

"Fade" borders in CSS

How to fade borders with CSS:

<div style="border-style:solid;border-image:linear-gradient(red, transparent) 1;border-bottom:0;">Text</div>

Please excuse the inline styles for the sake of demonstration. The 1 property for the border-image is border-image-slice, and in this case defines the border as a single continuous region.

Source: Gradient Borders

a page can have only one server-side form tag

Does your page contain these

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
Runat="Server">
</asp:content>

tags, and are all your controls inside these? You should only have the Form tags in the MasterPage.


Here are some of my understanding and suggestion:

Html element can be put in the body of html pages and html page does support multiple elements, however they can not be nested each other, you can find the detailed description from the W3C html specification:

The FORM element

http://www.w3.org/MarkUp/html3/forms.html

And as for ASP.NET web form page, it is based on a single server-side form element which contains all the controls inside it, so generally we do not recommend that we put multiple elements. However, this is still supported in ASP.NET page(master page) and I think the problem in your master page should be caused by the unsupported nested element, and multiple in the same level should be ok. e.g:

In addition, if what you want to do through multiple forms is just make our page posting to multiple pages, I think you can consider using the new feature for cross-page posting in ASP.NET 2.0. This can help us use button controls to postback to different pages without having multpile forms on the page:

Cross-Page Posting in ASP.NET Web Pages

http://msdn2.microsoft.com/en-us/lib...39(VS.80).aspx

http://msdn2.microsoft.com/en-us/lib...40(VS.80).aspx

Sending event when AngularJS finished loading

Just a hunch: why not look at how the ngCloak directive does it? Clearly the ngCloak directive manages to show content after things have loaded. I bet looking at ngCloak will lead to the exact answer...

EDIT 1 hour later: Ok, well, I looked at ngCloak and it's really short. What this obviously implies is that the compile function won't get executed until {{template}} expressions have been evaluated (i.e. the template it loaded), thus the nice functionality of the ngCloak directive.

My educated guess would be to just make a directive with the same simplicity of ngCloak, then in your compile function do whatever you want to do. :) Place the directive on the root element of your app. You can call the directive something like myOnload and use it as an attribute my-onload. The compile function will execute once the template has been compiled (expressions evaluated and sub-templates loaded).

EDIT, 23 hours later: Ok, so I did some research, and I also asked my own question. The question I asked was indirectly related to this question, but it coincidentally lead me to the answer that solves this question.

The answer is that you can create a simple directive and put your code in the directive's link function, which (for most use cases, explained below) will run when your element is ready/loaded. Based on Josh's description of the order in which compile and link functions are executed,

if you have this markup:

<div directive1>
  <div directive2>
    <!-- ... -->
  </div>
</div>

Then AngularJS will create the directives by running directive functions in a certain order:

directive1: compile
  directive2: compile
directive1: controller
directive1: pre-link
  directive2: controller
  directive2: pre-link
  directive2: post-link
directive1: post-link

By default a straight "link" function is a post-link, so your outer directive1's link function will not run until after the inner directive2's link function has ran. That's why we say that it's only safe to do DOM manipulation in the post-link. So toward the original question, there should be no issue accessing the child directive's inner html from the outer directive's link function, though dynamically inserted contents must be compiled, as said above.

From this we can conclude that we can simply make a directive to execute our code when everything is ready/compiled/linked/loaded:

    app.directive('ngElementReady', [function() {
        return {
            priority: -1000, // a low number so this directive loads after all other directives have loaded. 
            restrict: "A", // attribute only
            link: function($scope, $element, $attributes) {
                console.log(" -- Element ready!");
                // do what you want here.
            }
        };
    }]);

Now what you can do is put the ngElementReady directive onto the root element of the app, and the console.log will fire when it's loaded:

<body data-ng-app="MyApp" data-ng-element-ready="">
   ...
   ...
</body>

It's that simple! Just make a simple directive and use it. ;)

You can further customize it so it can execute an expression (i.e. a function) by adding $scope.$eval($attributes.ngElementReady); to it:

    app.directive('ngElementReady', [function() {
        return {
            priority: Number.MIN_SAFE_INTEGER, // execute last, after all other directives if any.
            restrict: "A",
            link: function($scope, $element, $attributes) {
                $scope.$eval($attributes.ngElementReady); // execute the expression in the attribute.
            }
        };
    }]);

Then you can use it on any element:

<body data-ng-app="MyApp" data-ng-controller="BodyCtrl" data-ng-element-ready="bodyIsReady()">
    ...
    <div data-ng-element-ready="divIsReady()">...<div>
</body>

Just make sure you have your functions (e.g. bodyIsReady and divIsReady) defined in the scope (in the controller) that your element lives under.

Caveats: I said this will work for most cases. Be careful when using certain directives like ngRepeat and ngIf. They create their own scope, and your directive may not fire. For example if you put our new ngElementReady directive on an element that also has ngIf, and the condition of the ngIf evaluates to false, then our ngElementReady directive won't get loaded. Or, for example, if you put our new ngElementReady directive on an element that also has a ngInclude directive, our directive won't be loaded if the template for the ngInclude does not exist. You can get around some of these problems by making sure you nest the directives instead of putting them all on the same element. For example, by doing this:

<div data-ng-element-ready="divIsReady()">
    <div data-ng-include="non-existent-template.html"></div>
<div>

instead of this:

<div data-ng-element-ready="divIsReady()" data-ng-include="non-existent-template.html"></div>

The ngElementReady directive will be compiled in the latter example, but it's link function will not be executed. Note: directives are always compiled, but their link functions are not always executed depending on certain scenarios like the above.

EDIT, a few minutes later:

Oh, and to fully answer the question, you can now $emit or $broadcast your event from the expression or function that is executed in the ng-element-ready attribute. :) E.g.:

<div data-ng-element-ready="$emit('someEvent')">
    ...
<div>

EDIT, even more few minutes later:

@satchmorun's answer works too, but only for the initial load. Here's a very useful SO question that describes the order things are executed including link functions, app.run, and others. So, depending on your use case, app.run might be good, but not for specific elements, in which case link functions are better.

EDIT, five months later, Oct 17 at 8:11 PST:

This doesn't work with partials that are loaded asynchronously. You'll need to add bookkeeping into your partials (e.g. one way is to make each partial keep track of when its content is done loading then emit an event so the parent scope can count how many partials have loaded and finally do what it needs to do after all partials are loaded).

EDIT, Oct 23 at 10:52pm PST:

I made a simple directive for firing some code when an image is loaded:

/*
 * This img directive makes it so that if you put a loaded="" attribute on any
 * img element in your app, the expression of that attribute will be evaluated
 * after the images has finished loading. Use this to, for example, remove
 * loading animations after images have finished loading.
 */
  app.directive('img', function() {
    return {
      restrict: 'E',
      link: function($scope, $element, $attributes) {
        $element.bind('load', function() {
          if ($attributes.loaded) {
            $scope.$eval($attributes.loaded);
          }
        });
      }
    };
  });

EDIT, Oct 24 at 12:48am PST:

I improved my original ngElementReady directive and renamed it to whenReady.

/*
 * The whenReady directive allows you to execute the content of a when-ready
 * attribute after the element is ready (i.e. done loading all sub directives and DOM
 * content except for things that load asynchronously like partials and images).
 *
 * Execute multiple expressions by delimiting them with a semi-colon. If there
 * is more than one expression, and the last expression evaluates to true, then
 * all expressions prior will be evaluated after all text nodes in the element
 * have been interpolated (i.e. {{placeholders}} replaced with actual values). 
 *
 * Caveats: if other directives exists on the same element as this directive
 * and destroy the element thus preventing other directives from loading, using
 * this directive won't work. The optimal way to use this is to put this
 * directive on an outer element.
 */
app.directive('whenReady', ['$interpolate', function($interpolate) {
  return {
    restrict: 'A',
    priority: Number.MIN_SAFE_INTEGER, // execute last, after all other directives if any.
    link: function($scope, $element, $attributes) {
      var expressions = $attributes.whenReady.split(';');
      var waitForInterpolation = false;

      function evalExpressions(expressions) {
        expressions.forEach(function(expression) {
          $scope.$eval(expression);
        });
      }

      if ($attributes.whenReady.trim().length == 0) { return; }

      if (expressions.length > 1) {
        if ($scope.$eval(expressions.pop())) {
          waitForInterpolation = true;
        }
      }

      if (waitForInterpolation) {
        requestAnimationFrame(function checkIfInterpolated() {
          if ($element.text().indexOf($interpolate.startSymbol()) >= 0) { // if the text still has {{placeholders}}
            requestAnimationFrame(checkIfInterpolated);
          }
          else {
            evalExpressions(expressions);
          }
        });
      }
      else {
        evalExpressions(expressions);
      }
    }
  }
}]);

For example, use it like this to fire someFunction when an element is loaded and {{placeholders}} not yet replaced:

<div when-ready="someFunction()">
  <span ng-repeat="item in items">{{item.property}}</span>
</div>

someFunction will be called before all the item.property placeholders are replaced.

Evaluate as many expressions as you want, and make the last expression true to wait for {{placeholders}} to be evaluated like this:

<div when-ready="someFunction(); anotherFunction(); true">
  <span ng-repeat="item in items">{{item.property}}</span>
</div>

someFunction and anotherFunction will be fired after {{placeholders}} have been replaced.

This only works the first time an element is loaded, not on future changes. It may not work as desired if a $digest keeps happening after placeholders have initially been replaced (a $digest can happen up to 10 times until data stops changing). It'll be suitable for a vast majority of use cases.

EDIT, Oct 31 at 7:26pm PST:

Alright, this is probably my last and final update. This will probably work for 99.999 of the use cases out there:

/*
 * The whenReady directive allows you to execute the content of a when-ready
 * attribute after the element is ready (i.e. when it's done loading all sub directives and DOM
 * content). See: https://stackoverflow.com/questions/14968690/sending-event-when-angular-js-finished-loading
 *
 * Execute multiple expressions in the when-ready attribute by delimiting them
 * with a semi-colon. when-ready="doThis(); doThat()"
 *
 * Optional: If the value of a wait-for-interpolation attribute on the
 * element evaluates to true, then the expressions in when-ready will be
 * evaluated after all text nodes in the element have been interpolated (i.e.
 * {{placeholders}} have been replaced with actual values).
 *
 * Optional: Use a ready-check attribute to write an expression that
 * specifies what condition is true at any given moment in time when the
 * element is ready. The expression will be evaluated repeatedly until the
 * condition is finally true. The expression is executed with
 * requestAnimationFrame so that it fires at a moment when it is least likely
 * to block rendering of the page.
 *
 * If wait-for-interpolation and ready-check are both supplied, then the
 * when-ready expressions will fire after interpolation is done *and* after
 * the ready-check condition evaluates to true.
 *
 * Caveats: if other directives exists on the same element as this directive
 * and destroy the element thus preventing other directives from loading, using
 * this directive won't work. The optimal way to use this is to put this
 * directive on an outer element.
 */
app.directive('whenReady', ['$interpolate', function($interpolate) {
  return {
    restrict: 'A',
    priority: Number.MIN_SAFE_INTEGER, // execute last, after all other directives if any.
    link: function($scope, $element, $attributes) {
      var expressions = $attributes.whenReady.split(';');
      var waitForInterpolation = false;
      var hasReadyCheckExpression = false;

      function evalExpressions(expressions) {
        expressions.forEach(function(expression) {
          $scope.$eval(expression);
        });
      }

      if ($attributes.whenReady.trim().length === 0) { return; }

    if ($attributes.waitForInterpolation && $scope.$eval($attributes.waitForInterpolation)) {
        waitForInterpolation = true;
    }

      if ($attributes.readyCheck) {
        hasReadyCheckExpression = true;
      }

      if (waitForInterpolation || hasReadyCheckExpression) {
        requestAnimationFrame(function checkIfReady() {
          var isInterpolated = false;
          var isReadyCheckTrue = false;

          if (waitForInterpolation && $element.text().indexOf($interpolate.startSymbol()) >= 0) { // if the text still has {{placeholders}}
            isInterpolated = false;
          }
          else {
            isInterpolated = true;
          }

          if (hasReadyCheckExpression && !$scope.$eval($attributes.readyCheck)) { // if the ready check expression returns false
            isReadyCheckTrue = false;
          }
          else {
            isReadyCheckTrue = true;
          }

          if (isInterpolated && isReadyCheckTrue) { evalExpressions(expressions); }
          else { requestAnimationFrame(checkIfReady); }

        });
      }
      else {
        evalExpressions(expressions);
      }
    }
  };
}]);

Use it like this

<div when-ready="isReady()" ready-check="checkIfReady()" wait-for-interpolation="true">
   isReady will fire when this {{placeholder}} has been evaluated
   and when checkIfReady finally returns true. checkIfReady might
   contain code like `$('.some-element').length`.
</div>

Of course, it can probably be optimized, but I'll just leave it at that. requestAnimationFrame is nice.

PHP: How to handle <![CDATA[ with SimpleXMLElement?

This is working perfect for me.

$content = simplexml_load_string(
    $raw_xml
    , null
    , LIBXML_NOCDATA
);

How to replace a hash key with another key

Previous answers are good enough, but they might update original data. In case if you don't want the original data to be affected, you can try my code.

 newhash=hash.reject{|k| k=='_id'}.merge({id:hash['_id']})

First it will ignore the key '_id' then merge with the updated one.

How do you change text to bold in Android?

It's very easy

setTypeface(Typeface.DEFAULT_BOLD);

Objective-C and Swift URL encoding

 NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NUL,(CFStringRef)@"parameter",NULL,(CFStringRef)@"!*'();@&+$,/?%#[]~=_-.:",kCFStringEncodingUTF8 );

NSURL * url = [[NSURL alloc] initWithString:[@"address here" stringByAppendingFormat:@"?cid=%@",encodedString, nil]];

print call stack in C or C++

You can implement the functionality yourself:

Use a global (string)stack and at start of each function push the function name and such other values (eg parameters) onto this stack; at exit of function pop it again.

Write a function that will printout the stack content when it is called, and use this in the function where you want to see the callstack.

This may sound like a lot of work but is quite useful.

Interfaces vs. abstract classes

The real question is: whether to use interfaces or base classes. This has been covered before.

In C#, an abstract class (one marked with the keyword "abstract") is simply a class from which you cannot instantiate objects. This serves a different purpose than simply making the distinction between base classes and interfaces.

Default password of mysql in ubuntu server 16.04

Early versions allowed root password to be blank but, in Newer versions set the root password is the admin(main) user login password during the installation.

Add line break to 'git commit -m' from the command line

You should be able to use

git commit -m $'first line\nsecond line'

From the Bash manual:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.

This includes support for newlines as shown above, plus hex and Unicode codes and others. Go to the linked section to see a list of the backslash-escaped characters.

Get pandas.read_csv to read empty values as empty string instead of nan

I was still confused after reading the other answers and comments. But the answer now seems simpler, so here you go.

Since Pandas version 0.9 (from 2012), you can read your csv with empty cells interpreted as empty strings by simply setting keep_default_na=False:

pd.read_csv('test.csv', keep_default_na=False)

This issue is more clearly explained in

That was fixed on on Aug 19, 2012 for Pandas version 0.9 in

Basic text editor in command prompt?

The standard text editor in windows is notepad. There are no built-in command line editors.

Windows does not ship a C or C++ compiler. The .NET framework comes with several compilers, though: csc.exe (C# compiler), vbc.exe (VB.NET compiler), jsc.exe (JavaScript compiler).

If you want a free alternative you can download Visual Studio Express 2013 for Windows Desktop that comes with an optimizing C/C++ compiler (cl.exe).

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

Using f-strings, in Python 3.6+.

from datetime import datetime

date_string = f'{datetime.now():%Y-%m-%d %H:%M:%S%z}'

NameError: global name is not defined

Importing the namespace is somewhat cleaner. Imagine you have two different modules you import, both of them with the same method/class. Some bad stuff might happen. I'd dare say it is usually good practice to use:

import module

over

from module import function/class

Pass multiple parameters in Html.BeginForm MVC

There are two options here.

  1. a hidden field within the form, or
  2. Add it to the route values parameter in the begin form method.

Edit

@Html.Hidden("clubid", ViewBag.Club.id)

or

 @using(Html.BeginForm("action", "controller",
                       new { clubid = @Viewbag.Club.id }, FormMethod.Post, null)

Convert integer into byte array (Java)

If you like Guava, you may use its Ints class:


For int ? byte[], use toByteArray():

byte[] byteArray = Ints.toByteArray(0xAABBCCDD);

Result is {0xAA, 0xBB, 0xCC, 0xDD}.


Its reverse is fromByteArray() or fromBytes():

int intValue = Ints.fromByteArray(new byte[]{(byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD});
int intValue = Ints.fromBytes((byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD);

Result is 0xAABBCCDD.

Python Selenium Chrome Webdriver

Here's a simpler solution: install python-chromedrive package, import it in your script, and it's done.

Step by step:
1. pip install chromedriver-binary
2. import the package

from selenium import webdriver
import chromedriver_binary  # Adds chromedriver binary to path

driver = webdriver.Chrome()
driver.get("http://www.python.org")

Reference: https://pypi.org/project/chromedriver-binary/

How to add new item to hash

hash[key]=value Associates the value given by value with the key given by key.

hash[:newKey] = "newValue"

From Ruby documentation: http://www.tutorialspoint.com/ruby/ruby_hashes.htm

How to concatenate items in a list to a single string?

Use join:

>>> sentence = ['this', 'is', 'a', 'sentence']
>>> '-'.join(sentence)
'this-is-a-sentence'
>>> ' '.join(sentence)
'this is a sentence'

What is the difference between “int” and “uint” / “long” and “ulong”?

The difference is that the uint and ulong are unsigned data types, meaning the range is different: They do not accept negative values:

int range: -2,147,483,648 to 2,147,483,647
uint range: 0 to 4,294,967,295

long range: –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong range: 0 to 18,446,744,073,709,551,615

Loop through list with both content and index

enumerate is what you want:

for i, s in enumerate(S):
    print s, i

What does upstream mean in nginx?

It's used for proxying requests to other servers.

An example from http://wiki.nginx.org/LoadBalanceExample is:

http {
  upstream myproject {
    server 127.0.0.1:8000 weight=3;
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;    
    server 127.0.0.1:8003;
  }

  server {
    listen 80;
    server_name www.domain.com;
    location / {
      proxy_pass http://myproject;
    }
  }
}

This means all requests for / go to the any of the servers listed under upstream XXX, with a preference for port 8000.

Stop Excel from automatically converting certain text values to dates

Hi I have the same issue,

I write this vbscipt to create another CSV file. The new CSV file will have a space in font of each field, so excel will understand it as text.

So you create a .vbs file with the code below (for example Modify_CSV.vbs), save and close it. Drag and Drop your original file to your vbscript file. It will create a new file with "SPACE_ADDED" to file name in the same location.

Set objArgs = WScript.Arguments

Set objFso = createobject("scripting.filesystemobject")

dim objTextFile
dim arrStr ' an array to hold the text content
dim sLine  ' holding text to write to new file

'Looping through all dropped file
For t = 0 to objArgs.Count - 1
    ' Input Path
    inPath = objFso.GetFile(wscript.arguments.item(t))

    ' OutPut Path
    outPath = replace(inPath, objFso.GetFileName(inPath), left(objFso.GetFileName(inPath), InStrRev(objFso.GetFileName(inPath),".") - 1) & "_SPACE_ADDED.csv")

    ' Read the file
    set objTextFile = objFso.OpenTextFile(inPath)


    'Now Creating the file can overwrite exiting file
    set aNewFile = objFso.CreateTextFile(outPath, True) 
    aNewFile.Close  

    'Open the file to appending data
    set aNewFile = objFso.OpenTextFile(outPath, 8) '2=Open for writing 8 for appending

    ' Reading data and writing it to new file
    Do while NOT objTextFile.AtEndOfStream
        arrStr = split(objTextFile.ReadLine,",")

        sLine = ""  'Clear previous data

        For i=lbound(arrStr) to ubound(arrStr)
            sLine = sLine + " " + arrStr(i) + ","
        Next

        'Writing data to new file
        aNewFile.WriteLine left(sLine, len(sLine)-1) 'Get rid of that extra comma from the loop


    Loop

    'Closing new file
    aNewFile.Close  

Next ' This is for next file

set aNewFile=nothing
set objFso = nothing
set objArgs = nothing

How to get enum value by string or int

Here is an example to get string/value

    public enum Suit
    {
        Spades = 0x10,
        Hearts = 0x11,
        Clubs = 0x12,
        Diamonds = 0x13
    }

    private void print_suit()
    {
        foreach (var _suit in Enum.GetValues(typeof(Suit)))
        {
            int suitValue = (byte)(Suit)Enum.Parse(typeof(Suit), _suit.ToString());
            MessageBox.Show(_suit.ToString() + " value is 0x" + suitValue.ToString("X2"));
        }
    }

    Result of Message Boxes
    Spade value is 0x10
    Hearts value is 0x11
    Clubs value is 0x12
    Diamonds value is 0x13

How can I strip all punctuation from a string in JavaScript using regex?

If you want to retain only alphabets and spaces, you can do:

str.replace(/[^a-zA-Z ]+/g, '').replace('/ {2,}/',' ')

Iterating through all nodes in XML file

This is what I quickly wrote for myself:

public static class XmlDocumentExtensions
{
    public static void IterateThroughAllNodes(
        this XmlDocument doc, 
        Action<XmlNode> elementVisitor)
    {
        if (doc != null && elementVisitor != null)
        {
            foreach (XmlNode node in doc.ChildNodes)
            {
                doIterateNode(node, elementVisitor);
            }
        }
    }

    private static void doIterateNode(
        XmlNode node, 
        Action<XmlNode> elementVisitor)
    {
        elementVisitor(node);

        foreach (XmlNode childNode in node.ChildNodes)
        {
            doIterateNode(childNode, elementVisitor);
        }
    }
}

To use it, I've used something like:

var doc = new XmlDocument();
doc.Load(somePath);

doc.IterateThroughAllNodes(
    delegate(XmlNode node)
    {
        // ...Do something with the node...
    });

Maybe it helps someone out there.

Set active tab style with AngularJS

Maybe a directive like this is might solve your problem: http://jsfiddle.net/p3ZMR/4/

HTML

<div ng-app="link">
<a href="#/one" active-link="active">One</a>
<a href="#/two" active-link="active">One</a>
<a href="#" active-link="active">home</a>


</div>

JS

angular.module('link', []).
directive('activeLink', ['$location', function(location) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs, controller) {
            var clazz = attrs.activeLink;
            var path = attrs.href;
            path = path.substring(1); //hack because path does bot return including hashbang
            scope.location = location;
            scope.$watch('location.path()', function(newPath) {
                if (path === newPath) {
                    element.addClass(clazz);
                } else {
                    element.removeClass(clazz);
                }
            });
        }

    };

}]);

Watching variables in SSIS during debug

I believe you can only add variables to the Watch window while the debugger is stopped on a breakpoint. If you set a breakpoint on a step, you should be able to enter variables into the Watch window when the breakpoint is hit. You can select the first empty row in the Watch window and enter the variable name (you may or may not get some Intellisense there, I can't remember how well that works.)

How do I properly force a Git push?

This was our solution for replacing master on a corporate gitHub repository while maintaining history.

push -f to master on corporate repositories is often disabled to maintain branch history. This solution worked for us.

git fetch desiredOrigin
git checkout -b master desiredOrigin/master // get origin master

git checkout currentBranch  // move to target branch
git merge -s ours master  // merge using ours over master
// vim will open for the commit message
git checkout master  // move to master
git merge currentBranch  // merge resolved changes into master

push your branch to desiredOrigin and create a PR

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

It is not necessary to stop timer, see nice solution from this post:

"You could let the timer continue firing the callback method but wrap your non-reentrant code in a Monitor.TryEnter/Exit. No need to stop/restart the timer in that case; overlapping calls will not acquire the lock and return immediately."

private void CreatorLoop(object state) 
 {
   if (Monitor.TryEnter(lockObject))
   {
     try
     {
       // Work here
     }
     finally
     {
       Monitor.Exit(lockObject);
     }
   }
 }

How can I set the request header for curl?

To pass multiple headers in a curl request you simply add additional -H or --header to your curl command.

Example

//Simplified
$ curl -v -H 'header1:val' -H 'header2:val' URL

//Explanatory
$ curl -v -H 'Connection: keep-alive' -H 'Content-Type: application/json'  https://www.example.com

Going Further

For standard HTTP header fields such as User-Agent, Cookie, Host, there is actually another way to setting them. The curl command offers designated options for setting these header fields:

  • -A (or --user-agent): set "User-Agent" field.
  • -b (or --cookie): set "Cookie" field.
  • -e (or --referer): set "Referer" field.
  • -H (or --header): set "Header" field

For example, the following two commands are equivalent. Both of them change "User-Agent" string in the HTTP header.

    $ curl -v -H "Content-Type: application/json" -H "User-Agent: UserAgentString" https://www.example.com
    $ curl -v -H "Content-Type: application/json" -A "UserAgentString" https://www.example.com

How to define servlet filter order of execution using annotations in WAR

  1. Make the servlet filter implement the spring Ordered interface.
  2. Declare the servlet filter bean manually in configuration class.
    import org.springframework.core.Ordered;
    
    public class MyFilter implements Filter, Ordered {

        @Override
        public void init(FilterConfig filterConfig) {
            // do something
        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            // do something
        }

        @Override
        public void destroy() {
            // do something
        }

        @Override
        public int getOrder() {
            return -100;
        }
    }


    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;

    @Configuration
    @ComponentScan
    public class MyAutoConfiguration {

        @Bean
        public MyFilter myFilter() {
            return new MyFilter();
        }
    }

How to add anything in <head> through jquery/javascript?

Try a javascript pure:

Library JS:

appendHtml = function(element, html) {
    var div = document.createElement('div');
    div.innerHTML = html;
    while (div.children.length > 0) {
        element.appendChild(div.children[0]);
    }
}

Type: appendHtml(document.head, '<link rel="stylesheet" type="text/css" href="http://example.com/example.css"/>');

or jQuery:

$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', 'http://example.com/example.css'));

How do I get the directory from a file's full path?

If you are working with a FileInfo object, then there is an easy way to extract a string representation of the directory's full path via the DirectoryName property.

Description of the FileInfo.DirectoryName Property via MSDN:

Gets a string representing the directory's full path.

Sample usage:

string filename = @"C:\MyDirectory\MyFile.bat";
FileInfo fileInfo = new FileInfo(filename);
string directoryFullPath = fileInfo.DirectoryName; // contains "C:\MyDirectory"

Link to the MSDN documentation.

How to Configure SSL for Amazon S3 bucket

If you really need it, consider redirections.

For example, on request to assets.my-domain.example.com/path/to/file you could perform a 301 or 302 redirection to my-bucket-name.s3.amazonaws.com/path/to/file or s3.amazonaws.com/my-bucket-name/path/to/file (please remember that in the first case my-bucket-name cannot contain any dots, otherwise it won't match *.s3.amazonaws.com, s3.amazonaws.com stated in S3 certificate).

Not tested, but I believe it would work. I see few gotchas, however.

The first one is pretty obvious, an additional request to get this redirection. And I doubt you could use redirection server provided by your domain name registrar — you'd have to upload proper certificate there somehow — so you have to use your own server for this.

The second one is that you can have urls with your domain name in page source code, but when for example user opens the pic in separate tab, then address bar will display the target url.

What is the difference between "screen" and "only screen" in media queries?

To style for many smartphones with smaller screens, you could write:

@media screen and (max-width:480px) { … } 

To block older browsers from seeing an iPhone or Android phone style sheet, you could write:

@media only screen and (max-width: 480px;) { … } 

Read this article for more http://webdesign.about.com/od/css3/a/css3-media-queries.htm

How can I concatenate strings in VBA?

There is the concatenate function. For example

=CONCATENATE(E2,"-",F2)
But the & operator always concatenates strings. + often will work, but if there is a number in one of the cells, it won't work as expected.

What's a simple way to get a text input popup dialog box on an iPhone

Try this Swift code in a UIViewController -

func doAlertControllerDemo() {

    var inputTextField: UITextField?;

    let passwordPrompt = UIAlertController(title: "Enter Password", message: "You have selected to enter your passwod.", preferredStyle: UIAlertControllerStyle.Alert);

    passwordPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        // Now do whatever you want with inputTextField (remember to unwrap the optional)

        let entryStr : String = (inputTextField?.text)! ;

        print("BOOM! I received '\(entryStr)'");

        self.doAlertViewDemo(); //do again!
    }));


    passwordPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        print("done");
    }));


    passwordPrompt.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
        textField.placeholder = "Password"
        textField.secureTextEntry = false       /* true here for pswd entry */
        inputTextField = textField
    });


    self.presentViewController(passwordPrompt, animated: true, completion: nil);


    return;
}

How to get the selected value from drop down list in jsp?

I've got one more additional option to get value by id:

var idElement = document.getElementById("idName");
var selectedValue = idElement.options[idElement.selectedIndex].value;

It's a simple JavaScript solution.

Adjust UILabel height depending on the text

Instead doing this programmatically, you can do this in Storyboard/XIB while designing.

  • Set UIlabel's number of lines property to 0 in attribute inspector.
  • Then set width constraint/(or) leading and trailing constraint as per the requirement.
  • Then set height constraint with minimum value. Finally select the height constraint you added and in the size inspector the one next to attribute inspector, change the height constraint's relation from equal to - greater than.

Windows ignores JAVA_HOME: how to set JDK as default?

Set Path environment variable to your desired jdk/bin directory

How to fix libeay32.dll was not found error

Please check if the dll in application is of the same version as that in the sys32 or wow64 folder depending on your version of windows.

You can check that from the filesize of the dlls.

Eg: I faced this issue because my libeay32.dll and ssleay32.dll file in system32 had a different dll than my libeay32.dll and ssleay32.dll file in openssl application.

I copied the one in sys32 into openssl and everything worked well.

How open PowerShell as administrator from the run window

Yes, it is possible to run PowerShell through the run window. However, it would be burdensome and you will need to enter in the password for computer. This is similar to how you will need to set up when you run cmd:

runas /user:(ComputerName)\(local admin) powershell.exe

So a basic example would be:

runas /user:MyLaptop\[email protected]  powershell.exe

You can find more information on this subject in Runas.

However, you could also do one more thing :

  • 1: `Windows+R`
  • 2: type: `powershell`
  • 3: type: `Start-Process powershell -verb runAs`

then your system will execute the elevated powershell.

Selecting a Linux I/O Scheduler

As documented in /usr/src/linux/Documentation/block/switching-sched.txt, the I/O scheduler on any particular block device can be changed at runtime. There may be some latency as the previous scheduler's requests are all flushed before bringing the new scheduler into use, but it can be changed without problems even while the device is under heavy use.

# cat /sys/block/hda/queue/scheduler
noop deadline [cfq]
# echo anticipatory > /sys/block/hda/queue/scheduler
# cat /sys/block/hda/queue/scheduler
noop [deadline] cfq

Ideally, there would be a single scheduler to satisfy all needs. It doesn't seem to exist yet. The kernel often doesn't have enough knowledge to choose the best scheduler for your workload:

  • noop is often the best choice for memory-backed block devices (e.g. ramdisks) and other non-rotational media (flash) where trying to reschedule I/O is a waste of resources
  • deadline is a lightweight scheduler which tries to put a hard limit on latency
  • cfq tries to maintain system-wide fairness of I/O bandwidth

The default was anticipatory for a long time, and it received a lot of tuning, but was removed in 2.6.33 (early 2010). cfq became the default some while ago, as its performance is reasonable and fairness is a good goal for multi-user systems (and even single-user desktops). For some scenarios -- databases are often used as examples, as they tend to already have their own peculiar scheduling and access patterns, and are often the most important service (so who cares about fairness?) -- anticipatory has a long history of being tunable for best performance on these workloads, and deadline very quickly passes all requests through to the underlying device.

How to change the Content of a <textarea> with JavaScript

Although many correct answers have already been given, the classical (read non-DOM) approach would be like this:

document.forms['yourform']['yourtextarea'].value = 'yourvalue';

where in the HTML your textarea is nested somewhere in a form like this:

<form name="yourform">
    <textarea name="yourtextarea" rows="10" cols="60"></textarea>
</form>

And as it happens, that would work with Netscape Navigator 4 and Internet Explorer 3 too. And, not unimportant, Internet Explorer on mobile devices.

Get Value From Select Option in Angular 4

You just need to put [(ngModel)] on your select element:

<select class="form-control col-lg-8" #corporation required [(ngModel)]="selectedValue">

What is a web service endpoint?

This is a shorter and hopefully clearer answer... Yes, the endpoint is the URL where your service can be accessed by a client application. The same web service can have multiple endpoints, for example in order to make it available using different protocols.

Automatically create an Enum based on values in a database lookup table?

Does it have to be an actual enum? How about using a Dictionary<string,int> instead?

for example

Dictionary<string, int> MyEnum = new Dictionary(){{"One", 1}, {"Two", 2}};
Console.WriteLine(MyEnum["One"]);

Specifying a custom DateTime format when serializing with Json.Net

Also available using one of the serializer settings overloads:

var json = JsonConvert.SerializeObject(someObject, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddThh:mm:ssZ" });

Or

var json = JsonConvert.SerializeObject(someObject, Formatting.Indented, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddThh:mm:ssZ" });

Overloads taking a Type are also available.

How can I make text appear on next line instead of overflowing?

Just add

white-space: initial;

to the text, a line text will come automatically in the next line.

Get Application Directory

Just use this in your code

 context.getApplicationInfo().dataDir

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

For Spring 5.2+ this works for me:

@PostMapping("/foo")
ResponseEntity<Void> foo(@PathVariable UUID fooId) {
    return fooService.findExam(fooId)
            .map(uri -> ResponseEntity.noContent().<Void>build())
            .orElse(ResponseEntity.notFound().build());
}

The EntityManager is closed

I faced the same problem while testing the changes in Symfony 4.3.2

I lowered the log level to INFO

And ran the test again

And the logged showed this:

console.ERROR: Error thrown while running command "doctrine:schema:create". Message: "[Semantical Error] The annotation "@ORM\Id" in property App\Entity\Common::$id was never imported. Did you maybe forget to add a "use" statement for this annotation?" {"exception":"[object] (Doctrine\\Common\\Annotations\\AnnotationException(code: 0): [Semantical Error] The annotation \"@ORM\\Id\" in property App\\Entity\\Common::$id was never imported. Did you maybe forget to add a \"use\" statement for this annotation? at C:\\xampp\\htdocs\\dirty7s\\vendor\\doctrine\\annotations\\lib\\Doctrine\\Common\\Annotations\\AnnotationException.php:54)","command":"doctrine:schema:create","message":"[Semantical Error] The annotation \"@ORM\\Id\" in property App\\Entity\\Common::$id was never imported. Did you maybe forget to add a \"use\" statement for this annotation?"} []

This means that some error in the code causes the:

Doctrine\ORM\ORMException: The EntityManager is closed.

So it is a good idea to check the log

Using isKindOfClass with Swift

The proper Swift operator is is:

if touch.view is UIPickerView {
    // touch.view is of type UIPickerView
}

Of course, if you also need to assign the view to a new constant, then the if let ... as? ... syntax is your boy, as Kevin mentioned. But if you don't need the value and only need to check the type, then you should use the is operator.

What does LPCWSTR stand for and how should it be handled with?

LPCWSTR stands for "Long Pointer to Constant Wide String". The W stands for Wide and means that the string is stored in a 2 byte character vs. the normal char. Common for any C/C++ code that has to deal with non-ASCII only strings.=

To get a normal C literal string to assign to a LPCWSTR, you need to prefix it with L

LPCWSTR a = L"TestWindow";

Which characters are valid/invalid in a JSON key name?

Unicode codepoints U+D800 to U+DFFF must be avoided: they are invalid in Unicode because they are reserved for UTF-16 surrogate pairs. Some JSON encoders/decoders will replace them with U+FFFD. See for example how the Go language and its JSON library deals with them.

So avoid "\uD800" to "\uDFFF" alone (not in surrogate pairs).

Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error?

An example with variable (ES6):

const item = document.querySelector([data-itemid="${id}"]);

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

I have stuck with same problem. As I didn't define Main.class and the following annotations in Spring-Boot using Maven:

@SpringBootApplication
public class Main {
    public static void main(String args[]){
        SpringApplication.run(Main.class, args);
    }
}

JSON Structure for List of Objects

As others mentioned, Justin's answer was close, but not quite right. I tested this using Visual Studio's "Paste JSON as C# Classes"

{
    "foos" : [
        {
            "prop1":"value1",
            "prop2":"value2"
        },
        {
            "prop1":"value3", 
            "prop2":"value4"
        }
    ]
}

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

Even I faced the same problem in my XMPP notification application, receivers message needs to be added back to list view (implemented with ArrayList). When I tried to add the receiver content through MessageListener (separate thread), application quits with above error. I solved this by adding the content to my arraylist & setListviewadapater through runOnUiThread method which is part of Activity class. This solved my problem.

Split text file into smaller multiple text file using command line

This "File Splitter" Windows command line program works nicely: https://github.com/dubasdey/File-Splitter

It's open source, simple, documented, proven, and worked for me.

Example:

fsplit -split 50 mb mylargefile.txt

Sanitizing user input before adding it to the DOM in Javascript

You can use this:

function sanitize(string) {
  const map = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#x27;',
      "/": '&#x2F;',
  };
  const reg = /[&<>"'/]/ig;
  return string.replace(reg, (match)=>(map[match]));
}

Also see OWASP XSS Prevention Cheat Sheet.

Can I extend a class using more than 1 class in PHP?

This is not a real answer, we have duplicate class

...but it works :)

class A {
    //do some things
}

class B {
    //do some things
}

class copy_B is copy all class B

class copy_B extends A {

    //do some things (copy class B)
}

class A_B extends copy_B{}

now

class C_A extends A{}
class C_B extends B{}
class C_A_b extends A_B{}  //extends A & B

How to set environment variables in PyCharm?

I was able to figure out this using a PyCharm plugin called EnvFile. This plugin, basically allows setting environment variables to run configurations from one or multiple files.

The installation is pretty simple:

Preferences > Plugins > Browse repositories... > Search for "Env File" > Install Plugin.

Then, I created a file, in my project root, called environment.env which contains:

DATABASE_URL=postgres://127.0.0.1:5432/my_db_name
DEBUG=1

Then I went to Run->Edit Configurations, and I followed the steps in the next image:

Set Environment Variables

In 3, I chose the file environment.env, and then I could just click the play button in PyCharm, and everything worked like a charm.

Testing if a list of integer is odd or even

You could try using Linq to project the list:

var output = lst.Select(x => x % 2 == 0).ToList();

This will return a new list of bools such that {1, 2, 3, 4, 5} will map to {false, true, false, true, false}.

Python's equivalent of && (logical-and) in an if-statement

A single & (not double &&) is enough or as the top answer suggests you can use 'and'. I also found this in pandas

cities['Is wide and has saint name'] = (cities['Population'] > 1000000) 
& cities['City name'].apply(lambda name: name.startswith('San'))

if we replace the "&" with "and", it won't work.

What does "exec sp_reset_connection" mean in Sql Server Profiler?

It's an indication that connection pooling is being used (which is a good thing).

How to get main div container to align to centre?

The basic principle of centering a page is to have a body CSS and main_container CSS. It should look something like this:

body {
     margin: 0;
     padding: 0;
     text-align: center;
}
#main_container {
     margin: 0 auto;
     text-align: left;
}

How do I capture SIGINT in Python?

Register your handler with signal.signal like this:

#!/usr/bin/env python
import signal
import sys

def signal_handler(sig, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()

Code adapted from here.

More documentation on signal can be found here.  

Full Page <iframe>

Here's the working code. Works in desktop and mobile browsers. hope it helps. thanks for everyone responding.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Test Layout</title>
        <style type="text/css">
            body, html
            {
                margin: 0; padding: 0; height: 100%; overflow: hidden;
            }

            #content
            {
                position:absolute; left: 0; right: 0; bottom: 0; top: 0px; 
            }
        </style>
    </head>
    <body>
        <div id="content">
            <iframe width="100%" height="100%" frameborder="0" src="http://cnn.com" />
        </div>
    </body>
</html>

Dataset - Vehicle make/model/year (free)

How about Freebase? I think they have an API available, too.

http://www.freebase.com/

jQuery show/hide not working

The content is not ready yet, you can move your js to the end of the file or do

<script>
$(function () { 
    $( '.expand' ).click(function() {
       $( '.img_display_content' ).show();
    });
});

So that the document waits to be loaded before running.

Replace CRLF using powershell

Below is my script for converting all files recursively. You can specify folders or files to exclude.

$excludeFolders = "node_modules|dist|.vs";
$excludeFiles = ".*\.map.*|.*\.zip|.*\.png|.*\.ps1"

Function Dos2Unix {
    [CmdletBinding()]
    Param([Parameter(ValueFromPipeline)] $fileName)

    Write-Host -Nonewline "."

    $fileContents = Get-Content -raw $fileName
    $containsCrLf = $fileContents | %{$_ -match "\r\n"}
    If($containsCrLf -contains $true)
    {
        Write-Host "`r`nCleaing file: $fileName"
        set-content -Nonewline -Encoding utf8 $fileName ($fileContents -replace "`r`n","`n")
    }
}

Get-Childitem -File "." -Recurse |
Where-Object {$_.PSParentPath -notmatch $excludeFolders} |
Where-Object {$_.PSPath -notmatch $excludeFiles} |
foreach { $_.PSPath | Dos2Unix }

Truncate Two decimal places without rounding

This is an old question, but many anwsers don't perform well or overflow for big numbers. I think D. Nesterov answer is the best one: robust, simple and fast. I just want to add my two cents. I played around with decimals and also checked out the source code. From the public Decimal (int lo, int mid, int hi, bool isNegative, byte scale) constructor documentation.

The binary representation of a Decimal number consists of a 1-bit sign, a 96-bit integer number, and a scaling factor used to divide the integer number and specify what portion of it is a decimal fraction. The scaling factor is implicitly the number 10 raised to an exponent ranging from 0 to 28.

Knowing this, my first approach was to create another decimal whose scale corresponds to the decimals that I wanted to discard, then truncate it and finally create a decimal with the desired scale.

private const int ScaleMask = 0x00FF0000;
    public static Decimal Truncate(decimal target, byte decimalPlaces)
    {
        var bits = Decimal.GetBits(target);
        var scale = (byte)((bits[3] & (ScaleMask)) >> 16);

        if (scale <= decimalPlaces)
            return target;

        var temporalDecimal = new Decimal(bits[0], bits[1], bits[2], target < 0, (byte)(scale - decimalPlaces));
        temporalDecimal = Math.Truncate(temporalDecimal);

        bits = Decimal.GetBits(temporalDecimal);
        return new Decimal(bits[0], bits[1], bits[2], target < 0, decimalPlaces);
    }

This method is not faster than D. Nesterov's and it is more complex, so I played around a little bit more. My guess is that having to create an auxiliar decimal and retrieving the bits twice is making it slower. On my second attempt, I manipulated the components returned by Decimal.GetBits(Decimal d) method myself. The idea is to divide the components by 10 as many times as needed and reduce the scale. The code is based (heavily) on the Decimal.InternalRoundFromZero(ref Decimal d, int decimalCount) method.

private const Int32 MaxInt32Scale = 9;
private const int ScaleMask = 0x00FF0000;
    private const int SignMask = unchecked((int)0x80000000);
    // Fast access for 10^n where n is 0-9        
    private static UInt32[] Powers10 = new UInt32[] {
        1,
        10,
        100,
        1000,
        10000,
        100000,
        1000000,
        10000000,
        100000000,
        1000000000
    };

    public static Decimal Truncate(decimal target, byte decimalPlaces)
    {
        var bits = Decimal.GetBits(target);
        int lo = bits[0];
        int mid = bits[1];
        int hi = bits[2];
        int flags = bits[3];

        var scale = (byte)((flags & (ScaleMask)) >> 16);
        int scaleDifference = scale - decimalPlaces;
        if (scaleDifference <= 0)
            return target;

        // Divide the value by 10^scaleDifference
        UInt32 lastDivisor;
        do
        {
            Int32 diffChunk = (scaleDifference > MaxInt32Scale) ? MaxInt32Scale : scaleDifference;
            lastDivisor = Powers10[diffChunk];
            InternalDivRemUInt32(ref lo, ref mid, ref hi, lastDivisor);
            scaleDifference -= diffChunk;
        } while (scaleDifference > 0);


        return new Decimal(lo, mid, hi, (flags & SignMask)!=0, decimalPlaces);
    }
    private static UInt32 InternalDivRemUInt32(ref int lo, ref int mid, ref int hi, UInt32 divisor)
    {
        UInt32 remainder = 0;
        UInt64 n;
        if (hi != 0)
        {
            n = ((UInt32)hi);
            hi = (Int32)((UInt32)(n / divisor));
            remainder = (UInt32)(n % divisor);
        }
        if (mid != 0 || remainder != 0)
        {
            n = ((UInt64)remainder << 32) | (UInt32)mid;
            mid = (Int32)((UInt32)(n / divisor));
            remainder = (UInt32)(n % divisor);
        }
        if (lo != 0 || remainder != 0)
        {
            n = ((UInt64)remainder << 32) | (UInt32)lo;
            lo = (Int32)((UInt32)(n / divisor));
            remainder = (UInt32)(n % divisor);
        }
        return remainder;
    }

I haven't performed rigorous performance tests, but on a MacOS Sierra 10.12.6, 3,06 GHz Intel Core i3 processor and targeting .NetCore 2.1 this method seems to be much faster than D. Nesterov's (I won't give numbers since, as I have mentioned, my tests are not rigorous). It is up to whoever implements this to evaluate whether or not the performance gains pay off for the added code complexity.

Metadata file '.dll' could not be found

Well, my answer is not just the summary of all the solutions, but it offers more than that.

Section (1):

In general solutions:

I had four errors of this kind (‘metadata file could not be found’) along with one error saying 'Source File Could Not Be Opened (‘Unspecified error ‘)'.

I tried to get rid of ‘metadata file could not be found’ error. For that, I read many posts, blogs, etc. and found these solutions may be effective (summarizing them over here):

  1. Restart Visual Studio and try building again.

  2. Go to 'Solution Explorer'. Right click on Solution. Go to Properties. Go to 'Configuration Manager'. Check if the checkboxes under 'Build' are checked or not. If any or all of them are unchecked, then check them and try building again.

  3. If the above solution(s) do not work, then follow sequence mentioned in step 2 above, and even if all the checkboxes are checked, uncheck them, check again and try to build again.

  4. Build Order and Project Dependencies:

    Go to 'Solution Explorer'. Right click on Solution. Go to 'Project Dependencies...'. You will see two tabs: 'Dependencies' and 'Build Order'. This build order is the one in which solution builds. Check the project dependencies and the build order to verify if some project (say 'project1') which is dependent on other (say 'project2') is trying to build before that one (project2). This might be the cause for the error.

  5. Check the path of the missing .dll:

    Check the path of the missing .dll. If the path contains space or any other invalid path character, remove it and try building again.

    If this is the cause, then adjust the build order.


Section (2):

My particular case:

I tried all the steps above with various permutations and combinations with restarting Visual Studio a few times. But, it did not help me.

So, I decided to get rid of other error I was coming across ('Source File Could Not Be Opened (‘Unspecified error ‘)').

I came across a blog post: TFS Error–Source File Could Not Be Opened (‘Unspecified error ‘)

I tried the steps mentioned in that blog post, and I got rid of the error 'Source File Could Not Be Opened (‘Unspecified error ‘)' and surprisingly I got rid of other errors (‘metadata file could not be found’) as well.


Section (3):

Moral of the story:

Try all solutions as mentioned in section (1) above (and any other solutions) for getting rid of the error. If nothing works out, as per the blog mentioned in section (2) above, delete the entries of all source files which are no longer present in the source control and the file system from your .csproj file.

What is the difference between 'java', 'javaw', and 'javaws'?

From http://publib.boulder.ibm.com/infocenter/javasdk/v6r0/index.jsp?topic=%2Fcom.ibm.java.doc.user.aix32.60%2Fuser%2Fjava.html:

The javaw command is identical to java, except that javaw has no associated console window. Use javaw when you do not want a command prompt window to be displayed. The javaw launcher displays a window with error information if it fails.

And javaws is for Java web start applications, applets, or something like that, I would suspect.

Benefits of inline functions in C++?

Inline function is the optimization technique used by the compilers. One can simply prepend inline keyword to function prototype to make a function inline. Inline function instruct compiler to insert complete body of the function wherever that function got used in code.

Advantages :-

  1. It does not require function calling overhead.

  2. It also save overhead of variables push/pop on the stack, while function calling.

  3. It also save overhead of return call from a function.

  4. It increases locality of reference by utilizing instruction cache.

  5. After in-lining compiler can also apply intra-procedural optimization if specified. This is the most important one, in this way compiler can now focus on dead code elimination, can give more stress on branch prediction, induction variable elimination etc..

To check more about it one can follow this link http://tajendrasengar.blogspot.com/2010/03/what-is-inline-function-in-cc.html

How to pass a vector to a function?

You're using the argument as a reference but actually it's a pointer. Change vector<int>* to vector<int>&. And you should really set search4 to something before using it.

curl usage to get header

You need to add the -i flag to the first command, to include the HTTP header in the output. This is required to print headers.

curl -X HEAD -i http://www.google.com

More here: https://serverfault.com/questions/140149/difference-between-curl-i-and-curl-x-head

Put spacing between divs in a horizontal row?

Put all the divs in a individual table cells and set the table style to padding: 5px;.

E.g.

_x000D_
_x000D_
<table style="width: 100%; padding: 5px;">_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>_x000D_
<div style="background-color: red;">A</div>_x000D_
</td>_x000D_
<td>_x000D_
<div style="background-color: orange;">B</div>_x000D_
</td>_x000D_
<td>_x000D_
<div style="background-color: green;">C</div>_x000D_
</td>_x000D_
<td>_x000D_
<div style="background-color: blue;">D</div>_x000D_
</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Installing Pandas on Mac OSX

You need to install XCode AND you need to make sure you install the command line tools for XCode so you can get gcc.

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

I have build such kind of application using approximatively the same approach except :

  • I cache the generated image on the disk and always generate two to three images in advance in a separate thread.
  • I don't overlay with a UIImage but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued.

Whenever the user start zooming, I acquire the CGPDFPage and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context is like :

CGAffineTransform currentCTM = CGContextGetCTM(context);    
if (currentCTM.a == 1.0 && baseImage) {
    //Calculate ideal scale
    CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width;
    CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height; 
    CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight);

    CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor);
    CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height);
    CGContextDrawImage(context, imageRect, [baseImage CGImage]);
} else {
    @synchronized(issue) { 
        CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1);
        pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true);
        CGContextConcatCTM(context, pdfToPageTransform);    
        CGContextDrawPDFPage(context, pdfPage);
    }
}

issue is the object containg the CGPDFDocumentRef. I synchronize the part where I access the pdfDoc property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef object do some internal caching that I did not find how to get rid of.

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

If its a maven project, add the below dependency in your pom file

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.3.4</version>
    </dependency>

How to add a JAR in NetBeans

You want to add libraries to your project and in doing so you have two options as you yourself identified:

Compile-time libraries are libraries which is needed to compile your application. They are not included when your application is assembled (e.g., into a war-file). Libraries of this kind must be provided by the container running your project.

This is useful in situation when you want to vary API and implementation, or when the library is supplied by the container (which is typically the case with javax.servlet which is required to compile but provided by the application server, e.g., Apache Tomcat).

Run-time libraries are libraries which is needed both for compilation and when running your project. This is probably what you want in most cases. If for instance your project is packaged into a war/ear, then these libraries will be included in the package.

As for the other alernatives you have either global libraries using Library Manageror jdk libraries. The latter is simply your regular java libraries, while the former is just a way for your to store a set of libraries under a common name. For all your future projects, instead of manually assigning the libraries you can simply select to import them from your Library Manager.

what's the easiest way to put space between 2 side-by-side buttons in asp.net

Can you just just some &nbsp; ?

<div style="text-align: center"> 
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="89px" OnClick="btnSubmit_Click" />
    &nbsp;&nbsp;
    <asp:Button ID="btnClear" runat="server" Text="Clear" Width="89px" OnClick="btnClear_Click" />
</div>

CodeIgniter - return only one row?

This is better way as it gives you result in a single line:

$this->db->query("Your query")->row()->campaign_id;

Xcode Simulator: how to remove older unneeded devices?

Another thing you can do is to change the Deployment target to the highest value. This will prevent the Scheme Menu from displaying older versions.

To do this go to: Target->Summary then change the Deployment Target.

jQuery and TinyMCE: textarea value doesn't submit

I just hide() the tinymce and submit form, the changed value of textarea missing. So I added this:

$("textarea[id='id_answer']").change(function(){
    var editor_id = $(this).attr('id');
    var editor = tinymce.get(editor_id);
    editor.setContent($(this).val()).save();
});

It works for me.

How does the keyword "use" work in PHP and can I import classes with it?

You'll have to include/require the class anyway, otherwise PHP won't know about the namespace.
You don't necessary have to do it in the same file though. You can do it in a bootstrap file for example. (or use an autoloader, but that's not the topic actually)

Android Crop Center of Bitmap

public Bitmap getResizedBitmap(Bitmap bm) {
    int width = bm.getWidth();
    int height = bm.getHeight();

    int narrowSize = Math.min(width, height);
    int differ = (int)Math.abs((bm.getHeight() - bm.getWidth())/2.0f);
    width  = (width  == narrowSize) ? 0 : differ;
    height = (width == 0) ? differ : 0;

    Bitmap resizedBitmap = Bitmap.createBitmap(bm, width, height, narrowSize, narrowSize);
    bm.recycle();
    return resizedBitmap;
}

Getting "TypeError: failed to fetch" when the request hasn't actually failed

I understand this question might have a React-specific cause, but it shows up first in search results for "Typeerror: Failed to fetch" and I wanted to lay out all possible causes here.

The Fetch spec lists times when you throw a TypeError from the Fetch API: https://fetch.spec.whatwg.org/#fetch-api

Relevant passages as of January 2021 are below. These are excerpts from the text.

4.6 HTTP-network fetch

To perform an HTTP-network fetch using request with an optional credentials flag, run these steps:
...
16. Run these steps in parallel:
...
2. If aborted, then:
...
3. Otherwise, if stream is readable, error stream with a TypeError.

To append a name/value name/value pair to a Headers object (headers), run these steps:

  1. Normalize value.
  2. If name is not a name or value is not a value, then throw a TypeError.
  3. If headers’s guard is "immutable", then throw a TypeError.

Filling Headers object headers with a given object object:

To fill a Headers object headers with a given object object, run these steps:

  1. If object is a sequence, then for each header in object:
    1. If header does not contain exactly two items, then throw a TypeError.

Method steps sometimes throw TypeError:

The delete(name) method steps are:

  1. If name is not a name, then throw a TypeError.
  2. If this’s guard is "immutable", then throw a TypeError.

The get(name) method steps are:

  1. If name is not a name, then throw a TypeError.
  2. Return the result of getting name from this’s header list.

The has(name) method steps are:

  1. If name is not a name, then throw a TypeError.

The set(name, value) method steps are:

  1. Normalize value.
  2. If name is not a name or value is not a value, then throw a TypeError.
  3. If this’s guard is "immutable", then throw a TypeError.

To extract a body and a Content-Type value from object, with an optional boolean keepalive (default false), run these steps:
...
5. Switch on object:
...
ReadableStream
If keepalive is true, then throw a TypeError.
If object is disturbed or locked, then throw a TypeError.

In the section "Body mixin" if you are using FormData there are several ways to throw a TypeError. I haven't listed them here because it would make this answer very long. Relevant passages: https://fetch.spec.whatwg.org/#body-mixin

In the section "Request Class" the new Request(input, init) constructor is a minefield of potential TypeErrors:

The new Request(input, init) constructor steps are:
...
6. If input is a string, then:
...
2. If parsedURL is a failure, then throw a TypeError.
3. IF parsedURL includes credentials, then throw a TypeError.
...
11. If init["window"] exists and is non-null, then throw a TypeError.
...
15. If init["referrer" exists, then:
...
1. Let referrer be init["referrer"].
2. If referrer is the empty string, then set request’s referrer to "no-referrer".
3. Otherwise:
1. Let parsedReferrer be the result of parsing referrer with baseURL.
2. If parsedReferrer is failure, then throw a TypeError.
...
18. If mode is "navigate", then throw a TypeError.
...
23. If request's cache mode is "only-if-cached" and request's mode is not "same-origin" then throw a TypeError.
...
27. If init["method"] exists, then:
...
2. If method is not a method or method is a forbidden method, then throw a TypeError.
...
32. If this’s request’s mode is "no-cors", then:
1. If this’s request’s method is not a CORS-safelisted method, then throw a TypeError.
...
35. If either init["body"] exists and is non-null or inputBody is non-null, and request’s method is GET or HEAD, then throw a TypeError.
...
38. If body is non-null and body's source is null, then:
1. If this’s request’s mode is neither "same-origin" nor "cors", then throw a TypeError.
...
39. If inputBody is body and input is disturbed or locked, then throw a TypeError.

The clone() method steps are:

  1. If this is disturbed or locked, then throw a TypeError.

In the Response class:

The new Response(body, init) constructor steps are:
...
2. If init["statusText"] does not match the reason-phrase token production, then throw a TypeError.
...
8. If body is non-null, then:
1. If init["status"] is a null body status, then throw a TypeError.
...

The static redirect(url, status) method steps are:
...
2. If parsedURL is failure, then throw a TypeError.

The clone() method steps are:

  1. If this is disturbed or locked, then throw a TypeError.

In section "The Fetch method"

The fetch(input, init) method steps are:
...
9. Run the following in parallel:
To process response for response, run these substeps:
...
3. If response is a network error, then reject p with a TypeError and terminate these substeps.

In addition to these potential problems, there are some browser-specific behaviors which can throw a TypeError. For instance, if you set keepalive to true and have a payload > 64 KB you'll get a TypeError on Chrome, but the same request can work in Firefox. These behaviors aren't documented in the spec, but you can find information about them by Googling for limitations for each option you're setting in fetch.

Is there a way to get LaTeX to place figures in the same page as a reference to that figure?

I don't want to sound too negative, but there are occasions when what you want is almost impossible without a lot of "artificial" tuning of page breaks.

If the callout falls naturally near the bottom of a page, and the figure falls on the following page, moving the figure back one page will probably displace the callout forward.

I would recommend (as far as possible, and depending on the exact size of the figures):

  • Place the figures with [t] (or [h] if you must)
  • Place the figures as near as possible to the "right" place (differs for [t] and [h])
  • Include the figures from separate files with \input, which will make them much easier to move around when you're doing the final tuning

In my experience, this is a big eater-up of non-available time (:-)


In reply to Jon's comment, I think this is an inherently difficult problem, because the LaTeX guys are no slouches. You may like to read Frank Mittelbach's paper.

Count of "Defined" Array Elements

If the undefined's are implicit then you can do:

var len = 0;
for (var i in arr) { len++ };

undefined's are implicit if you don't set them explicitly

//both are a[0] and a[3] are explicit undefined
var arr = [undefined, 1, 2, undefined];

arr[6] = 3;
//now arr[4] and arr[5] are implicit undefined

delete arr[1]
//now arr[1] is implicit undefined

arr[2] = undefined
//now arr[2] is explicit undefined

What special characters must be escaped in regular expressions?

Unfortunately there really isn't a set set of escape codes since it varies based on the language you are using.

However, keeping a page like the Regular Expression Tools Page or this Regular Expression Cheatsheet can go a long way to help you quickly filter things out.

How to Convert unsigned char* to std::string in C++?

BYTE* is probably a typedef for unsigned char*, but I can't say for sure. It would help if you tell us what BYTE is.

If BYTE* is unsigned char*, you can convert it to an std::string using the std::string range constructor, which will take two generic Iterators.

const BYTE* str1 = reinterpret_cast<const BYTE*> ("Hello World");
int len = strlen(reinterpret_cast<const char*>(str1));
std::string str2(str1, str1 + len);

That being said, are you sure this is a good idea? If BYTE is unsigned char it may contain non-ASCII characters, which can include NULLs. This will make strlen give an incorrect length.

How do I attach events to dynamic HTML elements with jQuery?

Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.

link text

$(function(){
    $(".myclass").live("click", function() {
        // do something
    });
});

Check that a input to UITextField is numeric only

This answer uses NSFormatter as said previously. Check it out:

@interface NSString (NSNumber)
- (BOOL) isNumberWithLocale:(NSLocale *) stringLocale;  
- (BOOL) isNumber;
- (NSNumber *) getNumber; 
- (NSNumber *) getNumberWithLocale:(NSLocale*) stringLocale;
@end

@implementation NSString (NSNumber)
- (BOOL) isNumberWithLocale:(NSLocale *) stringLocale
{
    return [self getNumberWithLocale:stringLocale] != nil;
}
- (BOOL) isNumber
{
    return [ self getNumber ] != nil;
}
- (NSNumber *) getNumber
{
    NSLocale *l_en = [[NSLocale alloc] initWithLocaleIdentifier: @"en_US"] ;  
    return [self getNumberWithLocale: [l_en autorelease] ];
}

- (NSNumber *) getNumberWithLocale:(NSLocale*) stringLocale
{
    NSNumberFormatter *formatter = [[ [ NSNumberFormatter alloc ] init ] autorelease];
    [formatter setLocale: stringLocale ];
    return [ formatter numberFromString:self ]; 
}
@end

I hope it helps someone. =)

HTML5 <video> element on Android

Maybe you have to encode the video specifically for the device eg:

<video id="movie" width="320" height="240" autobuffer controls>
  <source src="pr6.ogv" type='video/ogg; codecs="theora, vorbis"'>
  <source src="pr6.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
<source src="pr6.mp4" type='video/mp4; codecs="some droid video codec, some droid audio codec"'>
</video>

There are some examples of encoding configurations that worked on here:

https://supportforums.motorola.com

Access Control Origin Header error using Axios in React Web throwing error in Chrome

If your backend support CORS, you probably need to add to your request this header:

headers: {"Access-Control-Allow-Origin": "*"}

[Update] Access-Control-Allow-Origin is a response header - so in order to enable CORS - you need to add this header to the response from your server.

But for the most cases better solution would be configuring the reverse proxy, so that your server would be able to redirect requests from the frontend to backend, without enabling CORS.

You can find documentation about CORS mechanism here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

You use RAISE_APPLICATION_ERROR in order to create an Oracle style exception/error that is specific to your code/needs. Good use of these help to produce code that is clearer, more maintainable, and easier to debug.

For example, if I have an application calling a stored procedure that adds a user and that user already exists, you'll usually get back an error like:

ORA-00001: unique constraint (USERS.PK_USER_KEY) violated

Obviously this error and associated message are not unique to the task you were trying to do. Creating your own Oracle application errors allow you to be clearer on the intent of the action and the cause of the issue.

raise_application_error(-20101, 'User ' || in_user || ' already exists!');

Now your application code can write an exception handler in order to process this specific error condition. Think of it as a way to make Oracle communicate error conditions that your application expects in a "language" (for lack of a better term) that you have defined and is more meaningful to your application's problem domain.

Note that user defined errors must be in the range between -20000 and -20999.

The following link provides lots of good information on this topic and Oracle exceptions in general.

Find all stored procedures that reference a specific column in some table

One option is to create a script file.

Right click on the database -> Tasks -> Generate Scripts

Then you can select all the stored procedures and generate the script with all the sps. So you can find the reference from there.

Or

-- Search in All Objects
SELECT OBJECT_NAME(OBJECT_ID),
definition
FROM sys.sql_modules
WHERE definition LIKE '%' + 'CreatedDate' + '%'
GO

-- Search in Stored Procedure Only
SELECT DISTINCT OBJECT_NAME(OBJECT_ID),
object_definition(OBJECT_ID)
FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%' + 'CreatedDate' + '%'
GO

Source SQL SERVER – Find Column Used in Stored Procedure – Search Stored Procedure for Column Name

What is the difference between mocking and spying when using Mockito?

The answer is in the documentation:

Real partial mocks (Since 1.8.0)

Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito. Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks.

Before release 1.8 spy() was not producing real partial mocks and it was confusing for some users. Read more about spying: here or in javadoc for spy(Object) method.

callRealMethod() was introduced after spy(), but spy() was left there of course, to ensure backward compatibility.

Otherwise, you're right: all the methods of a spy are real unless stubbed. All the methods of a mock are stubbed unless callRealMethod() is called. In general, I would prefer using callRealMethod(), because it doesn't force me to use the doXxx().when() idiom instead of the traditional when().thenXxx()

Jquery - How to get the style display attribute "none / block"

My answer

/**
 * Display form to reply comment
 */
function displayReplyForm(commentId) {
    var replyForm = $('#reply-form-' + commentId);
    if (replyForm.css('display') == 'block') { // Current display
        replyForm.css('display', 'none');
    } else { // Hide reply form
        replyForm.css('display', 'block');
    }
}

Correct set of dependencies for using Jackson mapper

The package names in Jackson 2.x got changed to com.fasterxml1 from org.codehaus2. So if you just need ObjectMapper, I think Jackson 1.X can satisfy with your needs.

Android Intent Cannot resolve constructor

Or you can simply start the activity as shown below;

startActivity( new Intent(currentactivity.this, Tostartactivity.class));

Difference between map and collect in Ruby?

I've been told they are the same.

Actually they are documented in the same place under ruby-doc.org:

http://www.ruby-doc.org/core/classes/Array.html#M000249

  • ary.collect {|item| block } ? new_ary
  • ary.map {|item| block } ? new_ary
  • ary.collect ? an_enumerator
  • ary.map ? an_enumerator

Invokes block once for each element of self. Creates a new array containing the values returned by the block. See also Enumerable#collect.
If no block is given, an enumerator is returned instead.

a = [ "a", "b", "c", "d" ]
a.collect {|x| x + "!" }   #=> ["a!", "b!", "c!", "d!"]
a                          #=> ["a", "b", "c", "d"]

Replace line break characters with <br /> in ASP.NET MVC Razor view

I needed to break some text into paragraphs ("p" tags), so I created a simple helper using some of the recommendations in previous answers (thank you guys).

public static MvcHtmlString ToParagraphs(this HtmlHelper html, string value) 
    { 
        value = html.Encode(value).Replace("\r", String.Empty);
        var arr = value.Split('\n').Where(a => a.Trim() != string.Empty);
        var htmlStr = "<p>" + String.Join("</p><p>", arr) + "</p>";
        return MvcHtmlString.Create(htmlStr);
    }

Usage:

@Html.ToParagraphs(Model.Comments)

MVC razor form with multiple different submit buttons?

This answer will show you that how to work in asp.net with razor, and to control multiple submit button event. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".

@{
  if (IsPost)
    {
       if(Request["btn"].Equals("button_A"))
        {
          Response.Redirect("PageA.cshtml");
        }
      if(Request[&quot;btn"].Equals("button_B"))
        {
          Response.Redirect(&quot;PageB.cshtml&quot;);
        }
  }
}
<form method="post">
   <input type="submit" value="button_A" name="btn"/>;
   <input type="submit" value="button_B" name="btn"/>;          
</form>

Editing legend (text) labels in ggplot

The legend titles can be labeled by specific aesthetic.

This can be achieved using the guides() or labs() functions from ggplot2 (more here and here). It allows you to add guide/legend properties using the aesthetic mapping.

Here's an example using the mtcars data set and labs():

ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
  geom_point() +
  labs(x="miles per gallon", y="displacement", size="horsepower", 
       col="# of cylinders", shape="# of gears")

enter image description here

Answering the OP's question using guides():

# transforming the data from wide to long
require(reshape2)
dfm <- melt(df, id="TY")

# creating a scatterplot
ggplot(data = dfm, aes(x=TY, y=value, color=variable)) + 
  geom_point(size=5) +
  labs(title="Temperatures\n", x="TY [°C]", y="Txxx") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  guides(color=guide_legend("my title"))  # add guide properties by aesthetic

enter image description here

how to declare global variable in SQL Server..?

You cannot declare global variables in SQLServer.

If you're using Management Studio you can use SQLCMD mode like @Lanorkin pointed out.

Otherwise you can use CONTEXT_INFO to store a single variable that is visible during a session and connection, but it'll disappear after that.

Only truly global would be to create a global temp table (named ##yourTableName), and store your variables there, but that will also disappear when all connection are closed.

How to print binary tree diagram?

I've created simple binary tree printer. You can use and modify it as you want, but it's not optimized anyway. I think that a lot of things can be improved here ;)

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class BTreePrinterTest {

    private static Node<Integer> test1() {
        Node<Integer> root = new Node<Integer>(2);
        Node<Integer> n11 = new Node<Integer>(7);
        Node<Integer> n12 = new Node<Integer>(5);
        Node<Integer> n21 = new Node<Integer>(2);
        Node<Integer> n22 = new Node<Integer>(6);
        Node<Integer> n23 = new Node<Integer>(3);
        Node<Integer> n24 = new Node<Integer>(6);
        Node<Integer> n31 = new Node<Integer>(5);
        Node<Integer> n32 = new Node<Integer>(8);
        Node<Integer> n33 = new Node<Integer>(4);
        Node<Integer> n34 = new Node<Integer>(5);
        Node<Integer> n35 = new Node<Integer>(8);
        Node<Integer> n36 = new Node<Integer>(4);
        Node<Integer> n37 = new Node<Integer>(5);
        Node<Integer> n38 = new Node<Integer>(8);

        root.left = n11;
        root.right = n12;

        n11.left = n21;
        n11.right = n22;
        n12.left = n23;
        n12.right = n24;

        n21.left = n31;
        n21.right = n32;
        n22.left = n33;
        n22.right = n34;
        n23.left = n35;
        n23.right = n36;
        n24.left = n37;
        n24.right = n38;

        return root;
    }

    private static Node<Integer> test2() {
        Node<Integer> root = new Node<Integer>(2);
        Node<Integer> n11 = new Node<Integer>(7);
        Node<Integer> n12 = new Node<Integer>(5);
        Node<Integer> n21 = new Node<Integer>(2);
        Node<Integer> n22 = new Node<Integer>(6);
        Node<Integer> n23 = new Node<Integer>(9);
        Node<Integer> n31 = new Node<Integer>(5);
        Node<Integer> n32 = new Node<Integer>(8);
        Node<Integer> n33 = new Node<Integer>(4);

        root.left = n11;
        root.right = n12;

        n11.left = n21;
        n11.right = n22;

        n12.right = n23;
        n22.left = n31;
        n22.right = n32;

        n23.left = n33;

        return root;
    }

    public static void main(String[] args) {

        BTreePrinter.printNode(test1());
        BTreePrinter.printNode(test2());

    }
}

class Node<T extends Comparable<?>> {
    Node<T> left, right;
    T data;

    public Node(T data) {
        this.data = data;
    }
}

class BTreePrinter {

    public static <T extends Comparable<?>> void printNode(Node<T> root) {
        int maxLevel = BTreePrinter.maxLevel(root);

        printNodeInternal(Collections.singletonList(root), 1, maxLevel);
    }

    private static <T extends Comparable<?>> void printNodeInternal(List<Node<T>> nodes, int level, int maxLevel) {
        if (nodes.isEmpty() || BTreePrinter.isAllElementsNull(nodes))
            return;

        int floor = maxLevel - level;
        int endgeLines = (int) Math.pow(2, (Math.max(floor - 1, 0)));
        int firstSpaces = (int) Math.pow(2, (floor)) - 1;
        int betweenSpaces = (int) Math.pow(2, (floor + 1)) - 1;

        BTreePrinter.printWhitespaces(firstSpaces);

        List<Node<T>> newNodes = new ArrayList<Node<T>>();
        for (Node<T> node : nodes) {
            if (node != null) {
                System.out.print(node.data);
                newNodes.add(node.left);
                newNodes.add(node.right);
            } else {
                newNodes.add(null);
                newNodes.add(null);
                System.out.print(" ");
            }

            BTreePrinter.printWhitespaces(betweenSpaces);
        }
        System.out.println("");

        for (int i = 1; i <= endgeLines; i++) {
            for (int j = 0; j < nodes.size(); j++) {
                BTreePrinter.printWhitespaces(firstSpaces - i);
                if (nodes.get(j) == null) {
                    BTreePrinter.printWhitespaces(endgeLines + endgeLines + i + 1);
                    continue;
                }

                if (nodes.get(j).left != null)
                    System.out.print("/");
                else
                    BTreePrinter.printWhitespaces(1);

                BTreePrinter.printWhitespaces(i + i - 1);

                if (nodes.get(j).right != null)
                    System.out.print("\\");
                else
                    BTreePrinter.printWhitespaces(1);

                BTreePrinter.printWhitespaces(endgeLines + endgeLines - i);
            }

            System.out.println("");
        }

        printNodeInternal(newNodes, level + 1, maxLevel);
    }

    private static void printWhitespaces(int count) {
        for (int i = 0; i < count; i++)
            System.out.print(" ");
    }

    private static <T extends Comparable<?>> int maxLevel(Node<T> node) {
        if (node == null)
            return 0;

        return Math.max(BTreePrinter.maxLevel(node.left), BTreePrinter.maxLevel(node.right)) + 1;
    }

    private static <T> boolean isAllElementsNull(List<T> list) {
        for (Object object : list) {
            if (object != null)
                return false;
        }

        return true;
    }

}

Output 1 :

         2               
        / \       
       /   \      
      /     \     
     /       \    
     7       5       
    / \     / \   
   /   \   /   \  
   2   6   3   6   
  / \ / \ / \ / \ 
  5 8 4 5 8 4 5 8 

Output 2 :

       2               
      / \       
     /   \      
    /     \     
   /       \    
   7       5       
  / \       \   
 /   \       \  
 2   6       9   
    / \     /   
    5 8     4   

Flexbox not giving equal width to elements

To create elements with equal width using Flex, you should set to your's child (flex elements):

flex-basis: 25%;
flex-grow: 0;

It will give to all elements in row 25% width. They will not grow and go one by one.

How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

I will show visually the problem, using the great example from James answer and adding the alternative solution.

When you do the follow query, without the FETCH:

Select e from Employee e 
join e.phones p 
where p.areaCode = '613'

You will have the follow results from Employee as you expected:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613
1 James 6 416

But when you add the FETCH word on JOIN, this is what happens:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613

The generated SQL is the same for the two queries, but the Hibernate removes on memory the 416 register when you use WHERE on the FETCH join.

So, to bring all phones and apply the WHERE correctly, you need to have two JOINs: one for the WHERE and another for the FETCH. Like:

Select e from Employee e 
join e.phones p 
join fetch e.phones      //no alias, to not commit the mistake
where p.areaCode = '613'

Angular cli generate a service and include the provider in one step

In Command prompt go to project folder and execute following:

ng g s servicename

Various ways to remove local Git changes

First of all check is your important change saved or not by:

$ git status

than try

$ git reset --hard

it will reset your branch to default

but if you need just undo:

$ edit (1) $ git add frotz.c filfre.c $ mailx (2) $ git reset
(3) $ git pull git://info.example.com/ nitfol


Read more >> https://git-scm.com/docs/git-reset

INSERT INTO from two different server database

It sounds like you might need to create and query linked database servers in SQL Server

At the moment you've created a query that's going between different databases using a 3 part name mydatabase.dbo.mytable but you need to go up a level and use a 4 part name myserver.mydatabase.dbo.mytable, see this post on four part naming for more info

edit
The four part naming for your existing query would be as shown below (which I suspect you may have already tried?), but this assumes you can "get to" the remote database with the four part name, you might need to edit your host file / register the server or otherwise identify where to find database.windows.net.

INSERT INTO [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]
       ([InvoiceNumber]
       ,[TotalAmount]
       ,[IsActive]
       ,[CreatedBy]
       ,[UpdatedBy]
       ,[CreatedDate]
       ,[UpdatedDate]
       ,[Remarks])
SELECT [InvoiceNumber]
       ,[TotalAmount]
       ,[IsActive]
       ,[CreatedBy]
       ,[UpdatedBy]
       ,[CreatedDate]
       ,[UpdatedDate]
       ,[Remarks] FROM [BC1-PC].[testdabse].[dbo].[invoice]

If you can't access the remote server then see if you can create a linked database server:

EXEC sp_addlinkedserver [database.windows.net];
GO
USE tempdb;
GO
CREATE SYNONYM MyInvoice FOR 
    [database.windows.net].basecampdev.dbo.invoice;
GO

Then you can just query against MyEmployee without needing the full four part name

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

How to make the background DIV only transparent using CSS

I had the same problem, this is the solution i came up with, which is much easier!

Make a little 1px x 1px transparent image and save it as a .png file.

In the CSS for your DIV, use this code:

background:transparent url('/images/trans-bg.png') repeat center top;

Remember to change the file path to your transparent image.

I think this solution works in all browsers, maybe except for IE 6, but I haven't tested.

How to use CSS to surround a number with a circle?

Late to the party, but here is a bootstrap-only solution that has worked for me. I'm using Bootstrap 4:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<body>_x000D_
<div class="row mt-4">_x000D_
<div class="col-md-12">_x000D_
<span class="bg-dark text-white rounded-circle px-3 py-1 mx-2 h3">1</span>_x000D_
<span class="bg-dark text-white rounded-circle px-3 py-1 mx-2 h3">2</span>_x000D_
<span class="bg-dark text-white rounded-circle px-3 py-1 mx-2 h3">3</span>_x000D_
</div>_x000D_
</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

You basically add bg-dark text-white rounded-circle px-3 py-1 mx-2 h3 classes to your <span> (or whatever) element and you're done.

Note that you might need to adjust margin and padding classes if your content has more than one digits.

Import and Export Excel - What is the best library?

You could try the following library, it is easy enough and it is just a light wrapper over Microsoft's Open XML SDK (you can even reuse formatting, styles and even entire worksheets from secondary Excel file) : http://officehelper.codeplex.com

How to change UINavigationBar background color from the AppDelegate

To change the background color and not the tint the following piece of code will work:

[self.navigationController.navigationBar setBarTintColor:[UIColor greenColor]];
[self.navigationController.navigationBar setTranslucent:NO];

How do I close a single buffer (out of many) in Vim?

You can map next and previous to function keys too, making cycling through buffers a breeze

map <F2> :bprevious<CR>
map <F3> :bnext<CR>

from my vimrc

Cannot import XSSF in Apache POI

You did not described the environment, anyway, you should download apache poi libraries. If you are using eclipse , right click on your root project , so properties and in java build path add external jar and import in your project those libraries :

xmlbeans-2.6.0 ; poi-ooxml-schemas- ... ; poi-ooxml- ... ; poi- .... ;

System.BadImageFormatException An attempt was made to load a program with an incorrect format

I was having problems with a new install of VS with an x64 project - for Visual Studio 2013, Visual Studio 2015 and Visual Studio 2017:

Tools
  -> Options
   -> Projects and Solutions
    -> Web Projects
     -> Check "Use the 64 bit version of IIS Express for web sites and projects"

How to declare and initialize a static const array as a class member?

// in foo.h
class Foo {
    static const unsigned char* Msg;
};

// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;

What is a postback?

ASP.Net uses a new concept (well, new compared to asp... it's antiquated now) of ViewState to maintain the state of your asp.net controls. What does this mean? In a nutshell, if you type something into a textbox or select a dropdown from a dropdownlist, it will remember the values when you click on a button. Old asp would force you to write code to remember these values.

This is useful when if a user encounters an error. Instead of the programmer having to deal with remembering to re-populate each web control, the asp.net viewstate does this for you automatically. It's also useful because now the code behind can access the values of these controls on your asp.net web form with intellisense.

As for posting to the same page, yes, a "submit" button will post to an event handler on the code behind of the page. It's up to the event handler in the code behind to redirect to a different page if needs be (or serve up an error message to your page or whatever else you might need to do).

How to remove constraints from my MySQL table?

There is no DROP CONSTRAINT In MySql. This work like magic in mysql 5.7

ALTER TABLE answer DROP KEY const_name;

python re.split() to split by spaces, commas, and periods, but not in cases like 1,000 or 1.50

So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:

r" |(?<![0-9])[.,](?![0-9])"

Remove a JSON attribute

Simple:

delete myObj.test.key1;

How to generate xsd from wsdl

Follow these steps :

  1. Create a project using the WSDL.
  2. Choose your interface and open in interface viewer.
  3. Navigate to the tab 'WSDL Content'.
  4. Use the last icon under the tab 'WSDL Content' : 'Export the entire WSDL and included/imported files to a local directory'.
  5. select the folder where you want the XSDs to be exported to.

Note: SOAPUI will remove all relative paths and will save all XSDs to the same folder. Refer the screenshot : enter image description here

Find the files existing in one directory but not in the other

The accepted answer will also list the files that exist in both directories, but have different content. To list ONLY the files that exist in dir1 you can use:

diff -r dir1 dir2 | grep 'Only in' | grep dir1 | awk '{print $4}' > difference1.txt

Explanation:

  • diff -r dir1 dir2 : compare
  • grep 'Only in': get lines that contain 'Only in'
  • grep dir1 : get lines that contain dir

How to update a git clone --mirror?

Regarding commits, refs, branches and "et cetera", Magnus answer just works (git remote update).

But unfortunately there is no way to clone / mirror / update the hooks, as I wanted...

I have found this very interesting thread about cloning/mirroring the hooks:

http://kerneltrap.org/mailarchive/git/2007/8/28/256180/thread

I learned:

  • The hooks are not considered part of the repository contents.

  • There is more data, like the .git/description folder, which does not get cloned, just as the hooks.

  • The default hooks that appear in the hooks dir comes from the TEMPLATE_DIR

  • There is this interesting template feature on git.

So, I may either ignore this "clone the hooks thing", or go for a rsync strategy, given the purposes of my mirror (backup + source for other clones, only).

Well... I will just forget about hooks cloning, and stick to the git remote update way.

  • Sehe has just pointed out that not only "hooks" aren't managed by the clone / update process, but also stashes, rerere, etc... So, for a strict backup, rsync or equivalent would really be the way to go. As this is not really necessary in my case (I can afford not having hooks, stashes, and so on), like I said, I will stick to the remote update.

Thanks! Improved a bit of my own "git-fu"... :-)

What is a CSRF token? What is its importance and how does it work?

The site generates a unique token when it makes the form page. This token is required to post/get data back to the server.

Since the token is generated by your site and provided only when the page with the form is generated, some other site can't mimic your forms -- they won't have the token and therefore can't post to your site.

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

jquery change style of a div on click

As what I have understand on your question, this is what you want.

Here is a jsFiddle of the below:

_x000D_
_x000D_
$('.childDiv').click(function() {_x000D_
  $(this).parent().find('.childDiv').css('background-color', '#ffffff');_x000D_
  $(this).css('background-color', '#ff0000');_x000D_
});
_x000D_
.parentDiv {_x000D_
  border: 1px solid black;_x000D_
  padding: 10px;_x000D_
  width: 80px;_x000D_
  margin: 5px;_x000D_
  display: relative;_x000D_
}_x000D_
.childDiv {_x000D_
  border: 1px solid blue;_x000D_
  height: 50px;_x000D_
  margin: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>_x000D_
<div id="divParent1" class="parentDiv">_x000D_
  Group 1_x000D_
  <div id="child1" class="childDiv">_x000D_
    Child 1_x000D_
  </div>_x000D_
  <div id="child2" class="childDiv">_x000D_
    Child 2_x000D_
  </div>_x000D_
</div>_x000D_
<div id="divParent2" class="parentDiv">_x000D_
  Group 2_x000D_
  <div id="child1" class="childDiv">_x000D_
    Child 1_x000D_
  </div>_x000D_
  <div id="child2" class="childDiv">_x000D_
    Child 2_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Best way to specify whitespace in a String.Split operation

Can't you do it inline?

var sizes = subject.Split(new char[] { ' ', '\t' });

Otherwise, if you do this exact thing often, you could always create constant or something containing that char array.

As others have noted you can according to the documentation also use null or an empty array. When you do that it will use whitespace characters automatically.

var sizes = subject.Split(null);

Assign variable value inside if-statement

Yes, it is possible to assign inside if conditional check. But, your variable should have already been declared to assign something.